code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
__version__ = "1.0c2"
| zzangtest123-google-drive-sdk-samples | python/lib/apiclient/__init__.py | Python | asf20 | 22 |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model objects for requests and responses.
Each API may support one or more serializations, such
as JSON, Atom, etc. The model classes are responsible
for converting between the wire format and the Python
object representation.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import urllib
from errors import HttpError
from oauth2client.anyjson import simplejson
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('dump_request_response', False,
'Dump all http server requests and responses. '
)
def _abstract():
raise NotImplementedError('You need to override this function')
class Model(object):
"""Model base class.
All Model classes should implement this interface.
The Model serializes and de-serializes between a wire
format such as JSON and a Python object representation.
"""
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized in the desired wire format.
"""
_abstract()
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
_abstract()
class BaseModel(Model):
"""Base model class.
Subclasses should provide implementations for the "serialize" and
"deserialize" methods, as well as values for the following class attributes.
Attributes:
accept: The value to use for the HTTP Accept header.
content_type: The value to use for the HTTP Content-type header.
no_content_response: The value to return when deserializing a 204 "No
Content" response.
alt_param: The value to supply as the "alt" query parameter for requests.
"""
accept = None
content_type = None
no_content_response = None
alt_param = None
def _log_request(self, headers, path_params, query, body):
"""Logs debugging information about the request if requested."""
if FLAGS.dump_request_response:
logging.info('--request-start--')
logging.info('-headers-start-')
for h, v in headers.iteritems():
logging.info('%s: %s', h, v)
logging.info('-headers-end-')
logging.info('-path-parameters-start-')
for h, v in path_params.iteritems():
logging.info('%s: %s', h, v)
logging.info('-path-parameters-end-')
logging.info('body: %s', body)
logging.info('query: %s', query)
logging.info('--request-end--')
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable by simplejson.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized as JSON
"""
query = self._build_query(query_params)
headers['accept'] = self.accept
headers['accept-encoding'] = 'gzip, deflate'
if 'user-agent' in headers:
headers['user-agent'] += ' '
else:
headers['user-agent'] = ''
headers['user-agent'] += 'google-api-python-client/1.0'
if body_value is not None:
headers['content-type'] = self.content_type
body_value = self.serialize(body_value)
self._log_request(headers, path_params, query, body_value)
return (headers, path_params, query, body_value)
def _build_query(self, params):
"""Builds a query string.
Args:
params: dict, the query parameters
Returns:
The query parameters properly encoded into an HTTP URI query string.
"""
if self.alt_param is not None:
params.update({'alt': self.alt_param})
astuples = []
for key, value in params.iteritems():
if type(value) == type([]):
for x in value:
x = x.encode('utf-8')
astuples.append((key, x))
else:
if getattr(value, 'encode', False) and callable(value.encode):
value = value.encode('utf-8')
astuples.append((key, value))
return '?' + urllib.urlencode(astuples)
def _log_response(self, resp, content):
"""Logs debugging information about the response if requested."""
if FLAGS.dump_request_response:
logging.info('--response-start--')
for h, v in resp.iteritems():
logging.info('%s: %s', h, v)
if content:
logging.info(content)
logging.info('--response-end--')
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
self._log_response(resp, content)
# Error handling is TBD, for example, do we retry
# for some operation/error combinations?
if resp.status < 300:
if resp.status == 204:
# A 204: No Content response should be treated differently
# to all the other success states
return self.no_content_response
return self.deserialize(content)
else:
logging.debug('Content from bad request was: %s' % content)
raise HttpError(resp, content)
def serialize(self, body_value):
"""Perform the actual Python object serialization.
Args:
body_value: object, the request body as a Python object.
Returns:
string, the body in serialized form.
"""
_abstract()
def deserialize(self, content):
"""Perform the actual deserialization from response string to Python
object.
Args:
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
"""
_abstract()
class JsonModel(BaseModel):
"""Model class for JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request and response bodies.
"""
accept = 'application/json'
content_type = 'application/json'
alt_param = 'json'
def __init__(self, data_wrapper=False):
"""Construct a JsonModel.
Args:
data_wrapper: boolean, wrap requests and responses in a data wrapper
"""
self._data_wrapper = data_wrapper
def serialize(self, body_value):
if (isinstance(body_value, dict) and 'data' not in body_value and
self._data_wrapper):
body_value = {'data': body_value}
return simplejson.dumps(body_value)
def deserialize(self, content):
body = simplejson.loads(content)
if isinstance(body, dict) and 'data' in body:
body = body['data']
return body
@property
def no_content_response(self):
return {}
class RawModel(JsonModel):
"""Model class for requests that don't return JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = None
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class MediaModel(JsonModel):
"""Model class for requests that return Media.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = 'media'
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class ProtocolBufferModel(BaseModel):
"""Model class for protocol buffers.
Serializes and de-serializes the binary protocol buffer sent in the HTTP
request and response bodies.
"""
accept = 'application/x-protobuf'
content_type = 'application/x-protobuf'
alt_param = 'proto'
def __init__(self, protocol_buffer):
"""Constructs a ProtocolBufferModel.
The serialzed protocol buffer returned in an HTTP response will be
de-serialized using the given protocol buffer class.
Args:
protocol_buffer: The protocol buffer class used to de-serialize a
response from the API.
"""
self._protocol_buffer = protocol_buffer
def serialize(self, body_value):
return body_value.SerializeToString()
def deserialize(self, content):
return self._protocol_buffer.FromString(content)
@property
def no_content_response(self):
return self._protocol_buffer()
def makepatch(original, modified):
"""Create a patch object.
Some methods support PATCH, an efficient way to send updates to a resource.
This method allows the easy construction of patch bodies by looking at the
differences between a resource before and after it was modified.
Args:
original: object, the original deserialized resource
modified: object, the modified deserialized resource
Returns:
An object that contains only the changes from original to modified, in a
form suitable to pass to a PATCH method.
Example usage:
item = service.activities().get(postid=postid, userid=userid).execute()
original = copy.deepcopy(item)
item['object']['content'] = 'This is updated.'
service.activities.patch(postid=postid, userid=userid,
body=makepatch(original, item)).execute()
"""
patch = {}
for key, original_value in original.iteritems():
modified_value = modified.get(key, None)
if modified_value is None:
# Use None to signal that the element is deleted
patch[key] = None
elif original_value != modified_value:
if type(original_value) == type({}):
# Recursively descend objects
patch[key] = makepatch(original_value, modified_value)
else:
# In the case of simple types or arrays we just replace
patch[key] = modified_value
else:
# Don't add anything to patch if there's no change
pass
for key in modified:
if key not in original:
patch[key] = modified[key]
return patch
| zzangtest123-google-drive-sdk-samples | python/lib/apiclient/model.py | Python | asf20 | 11,757 |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Errors for the library.
All exceptions defined by the library
should be defined in this file.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from oauth2client.anyjson import simplejson
class Error(Exception):
"""Base error for this module."""
pass
class HttpError(Error):
"""HTTP data was invalid or unexpected."""
def __init__(self, resp, content, uri=None):
self.resp = resp
self.content = content
self.uri = uri
def _get_reason(self):
"""Calculate the reason for the error from the response content."""
if self.resp.get('content-type', '').startswith('application/json'):
try:
data = simplejson.loads(self.content)
reason = data['error']['message']
except (ValueError, KeyError):
reason = self.content
else:
reason = self.resp.reason
return reason
def __repr__(self):
if self.uri:
return '<HttpError %s when requesting %s returned "%s">' % (
self.resp.status, self.uri, self._get_reason())
else:
return '<HttpError %s "%s">' % (self.resp.status, self._get_reason())
__str__ = __repr__
class InvalidJsonError(Error):
"""The JSON returned could not be parsed."""
pass
class UnknownLinkType(Error):
"""Link type unknown or unexpected."""
pass
class UnknownApiNameOrVersion(Error):
"""No API with that name and version exists."""
pass
class UnacceptableMimeTypeError(Error):
"""That is an unacceptable mimetype for this operation."""
pass
class MediaUploadSizeError(Error):
"""Media is larger than the method can accept."""
pass
class ResumableUploadError(Error):
"""Error occured during resumable upload."""
pass
class BatchError(HttpError):
"""Error occured during batch operations."""
def __init__(self, reason, resp=None, content=None):
self.resp = resp
self.content = content
self.reason = reason
def __repr__(self):
return '<BatchError %s "%s">' % (self.resp.status, self.reason)
__str__ = __repr__
class UnexpectedMethodError(Error):
"""Exception raised by RequestMockBuilder on unexpected calls."""
def __init__(self, methodId=None):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedMethodError, self).__init__(
'Received unexpected call %s' % methodId)
class UnexpectedBodyError(Error):
"""Exception raised by RequestMockBuilder on unexpected bodies."""
def __init__(self, expected, provided):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedBodyError, self).__init__(
'Expected: [%s] - Provided: [%s]' % (expected, provided))
| zzangtest123-google-drive-sdk-samples | python/lib/apiclient/errors.py | Python | asf20 | 3,221 |
"""
iri2uri
Converts an IRI to a URI.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = []
__version__ = "1.0.0"
__license__ = "MIT"
__history__ = """
"""
import urlparse
# Convert an IRI to a URI following the rules in RFC 3987
#
# The characters we need to enocde and escape are defined in the spec:
#
# iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD
# ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
# / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
# / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
# / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
# / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
# / %xD0000-DFFFD / %xE1000-EFFFD
escape_range = [
(0xA0, 0xD7FF ),
(0xE000, 0xF8FF ),
(0xF900, 0xFDCF ),
(0xFDF0, 0xFFEF),
(0x10000, 0x1FFFD ),
(0x20000, 0x2FFFD ),
(0x30000, 0x3FFFD),
(0x40000, 0x4FFFD ),
(0x50000, 0x5FFFD ),
(0x60000, 0x6FFFD),
(0x70000, 0x7FFFD ),
(0x80000, 0x8FFFD ),
(0x90000, 0x9FFFD),
(0xA0000, 0xAFFFD ),
(0xB0000, 0xBFFFD ),
(0xC0000, 0xCFFFD),
(0xD0000, 0xDFFFD ),
(0xE1000, 0xEFFFD),
(0xF0000, 0xFFFFD ),
(0x100000, 0x10FFFD)
]
def encode(c):
retval = c
i = ord(c)
for low, high in escape_range:
if i < low:
break
if i >= low and i <= high:
retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')])
break
return retval
def iri2uri(uri):
"""Convert an IRI to a URI. Note that IRIs must be
passed in a unicode strings. That is, do not utf-8 encode
the IRI before passing it into the function."""
if isinstance(uri ,unicode):
(scheme, authority, path, query, fragment) = urlparse.urlsplit(uri)
authority = authority.encode('idna')
# For each character in 'ucschar' or 'iprivate'
# 1. encode as utf-8
# 2. then %-encode each octet of that utf-8
uri = urlparse.urlunsplit((scheme, authority, path, query, fragment))
uri = "".join([encode(c) for c in uri])
return uri
if __name__ == "__main__":
import unittest
class Test(unittest.TestCase):
def test_uris(self):
"""Test that URIs are invariant under the transformation."""
invariant = [
u"ftp://ftp.is.co.za/rfc/rfc1808.txt",
u"http://www.ietf.org/rfc/rfc2396.txt",
u"ldap://[2001:db8::7]/c=GB?objectClass?one",
u"mailto:John.Doe@example.com",
u"news:comp.infosystems.www.servers.unix",
u"tel:+1-816-555-1212",
u"telnet://192.0.2.16:80/",
u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ]
for uri in invariant:
self.assertEqual(uri, iri2uri(uri))
def test_iri(self):
""" Test that the right type of escaping is done for each part of the URI."""
self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}"))
self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}"))
self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}"))
self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}"))
self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))
self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")))
self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8')))
unittest.main()
| zzangtest123-google-drive-sdk-samples | python/lib/httplib2/iri2uri.py | Python | asf20 | 3,850 |
from __future__ import generators
"""
httplib2
A caching http interface that supports ETags and gzip
to conserve bandwidth.
Requires Python 2.3 or later
Changelog:
2007-08-18, Rick: Modified so it's able to use a socks proxy if needed.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger"]
__license__ = "MIT"
__version__ = "0.7.2"
import re
import sys
import email
import email.Utils
import email.Message
import email.FeedParser
import StringIO
import gzip
import zlib
import httplib
import urlparse
import base64
import os
import copy
import calendar
import time
import random
import errno
# remove depracated warning in python2.6
try:
from hashlib import sha1 as _sha, md5 as _md5
except ImportError:
import sha
import md5
_sha = sha.new
_md5 = md5.new
import hmac
from gettext import gettext as _
import socket
try:
from httplib2 import socks
except ImportError:
socks = None
# Build the appropriate socket wrapper for ssl
try:
import ssl # python 2.6
ssl_SSLError = ssl.SSLError
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if disable_validation:
cert_reqs = ssl.CERT_NONE
else:
cert_reqs = ssl.CERT_REQUIRED
# We should be specifying SSL version 3 or TLS v1, but the ssl module
# doesn't expose the necessary knobs. So we need to go with the default
# of SSLv23.
return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file,
cert_reqs=cert_reqs, ca_certs=ca_certs)
except (AttributeError, ImportError):
ssl_SSLError = None
def _ssl_wrap_socket(sock, key_file, cert_file,
disable_validation, ca_certs):
if not disable_validation:
raise CertificateValidationUnsupported(
"SSL certificate validation is not supported without "
"the ssl module installed. To avoid this error, install "
"the ssl module, or explicity disable validation.")
ssl_sock = socket.ssl(sock, key_file, cert_file)
return httplib.FakeSocket(sock, ssl_sock)
if sys.version_info >= (2,3):
from iri2uri import iri2uri
else:
def iri2uri(uri):
return uri
def has_timeout(timeout): # python 2.6
if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'):
return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT)
return (timeout is not None)
__all__ = ['Http', 'Response', 'ProxyInfo', 'HttpLib2Error',
'RedirectMissingLocation', 'RedirectLimit', 'FailedToDecompressContent',
'UnimplementedDigestAuthOptionError', 'UnimplementedHmacDigestAuthOptionError',
'debuglevel', 'ProxiesUnavailableError']
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# Python 2.3 support
if sys.version_info < (2,4):
def sorted(seq):
seq.sort()
return seq
# Python 2.3 support
def HTTPResponse__getheaders(self):
"""Return list of (header, value) tuples."""
if self.msg is None:
raise httplib.ResponseNotReady()
return self.msg.items()
if not hasattr(httplib.HTTPResponse, 'getheaders'):
httplib.HTTPResponse.getheaders = HTTPResponse__getheaders
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception): pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass
class RedirectLimit(HttpLib2ErrorWithResponse): pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass
class MalformedHeader(HttpLib2Error): pass
class RelativeURIError(HttpLib2Error): pass
class ServerNotFoundError(HttpLib2Error): pass
class ProxiesUnavailableError(HttpLib2Error): pass
class CertificateValidationUnsupported(HttpLib2Error): pass
class SSLHandshakeError(HttpLib2Error): pass
class NotSupportedOnThisPlatform(HttpLib2Error): pass
class CertificateHostnameMismatch(SSLHandshakeError):
def __init__(self, desc, host, cert):
HttpLib2Error.__init__(self, desc)
self.host = host
self.cert = cert
# Open Items:
# -----------
# Proxy support
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
# Default CA certificates file bundled with httplib2.
CA_CERTS = os.path.join(
os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt")
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade']
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')])
return [header for header in response.keys() if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r'^\w+://')
re_slash = re.compile(r'[?/:|]+')
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
try:
if re_url_scheme.match(filename):
if isinstance(filename,str):
filename = filename.decode('utf-8')
filename = filename.encode('idna')
else:
filename = filename.encode('idna')
except UnicodeError:
pass
if isinstance(filename,unicode):
filename=filename.encode('utf-8')
filemd5 = _md5(filename).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_slash.sub(",", filename)
# limit length of filename
if len(filename)>200:
filename=filename[:200]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+')
def _normalize_headers(headers):
return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()])
def _parse_cache_control(headers):
retval = {}
if headers.has_key('cache-control'):
parts = headers['cache-control'].split(',')
parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")]
parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, usefull for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$")
WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$")
UNQUOTE_PAIRS = re.compile(r'\\(.)')
def _parse_www_authenticate(headers, headername='www-authenticate'):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headers.has_key(headername):
try:
authenticate = headers[headername].strip()
www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
while authenticate:
# Break off the scheme at the beginning of the line
if headername == 'authentication-info':
(auth_scheme, the_rest) = ('digest', authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1:
retval = "TRANSPARENT"
if 'cache-control' not in request_headers:
request_headers['cache-control'] = 'no-cache'
elif cc.has_key('no-cache'):
retval = "TRANSPARENT"
elif cc_response.has_key('no-cache'):
retval = "STALE"
elif cc.has_key('only-if-cached'):
retval = "FRESH"
elif response_headers.has_key('date'):
date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date']))
now = time.time()
current_age = max(0, now - date)
if cc_response.has_key('max-age'):
try:
freshness_lifetime = int(cc_response['max-age'])
except ValueError:
freshness_lifetime = 0
elif response_headers.has_key('expires'):
expires = email.Utils.parsedate_tz(response_headers['expires'])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if cc.has_key('max-age'):
try:
freshness_lifetime = int(cc['max-age'])
except ValueError:
freshness_lifetime = 0
if cc.has_key('min-fresh'):
try:
min_fresh = int(cc['min-fresh'])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get('content-encoding', None)
if encoding in ['gzip', 'deflate']:
if encoding == 'gzip':
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == 'deflate':
content = zlib.decompress(content)
response['content-length'] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response['-content-encoding'] = response['content-encoding']
del response['content-encoding']
except IOError:
content = ""
raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content)
return content
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if cc.has_key('no-store') or cc_response.has_key('no-store'):
cache.delete(cachekey)
else:
info = email.Message.Message()
for key, value in response_headers.iteritems():
if key not in ['status','content-encoding','transfer-encoding']:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get('vary', None)
if vary:
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = 'status: %d\r\n' % status
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = "".join([status_header, header_str, content])
cache.set(cachekey, text)
def _cnonce():
dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path):].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-rise this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
class BasicAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip()
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['digest']
qop = self.challenge.get('qop', 'auth')
self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None
if self.challenge['qop'] is None:
raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper()
if self.challenge['algorithm'] != 'MD5':
raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]])
self.challenge['nc'] = 1
def request(self, method, request_uri, headers, content, cnonce = None):
"""Modify the request headers"""
H = lambda x: _md5(x).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge['cnonce'] = cnonce or _cnonce()
request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (self.challenge['nonce'],
'%08x' % self.challenge['nc'],
self.challenge['cnonce'],
self.challenge['qop'], H(A2)
))
headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['nonce'],
request_uri,
self.challenge['algorithm'],
request_digest,
self.challenge['qop'],
self.challenge['nc'],
self.challenge['cnonce'],
)
if self.challenge.get('opaque'):
headers['authorization'] += ', opaque="%s"' % self.challenge['opaque']
self.challenge['nc'] += 1
def response(self, response, content):
if not response.has_key('authentication-info'):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {})
if 'true' == challenge.get('stale'):
self.challenge['nonce'] = challenge['nonce']
self.challenge['nc'] = 1
return True
else:
updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {})
if updated_challenge.has_key('nextnonce'):
self.challenge['nonce'] = updated_challenge['nextnonce']
self.challenge['nc'] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
self.challenge = challenge['hmacdigest']
# TODO: self.challenge['domain']
self.challenge['reason'] = self.challenge.get('reason', 'unauthorized')
if self.challenge['reason'] not in ['unauthorized', 'integrity']:
self.challenge['reason'] = 'unauthorized'
self.challenge['salt'] = self.challenge.get('salt', '')
if not self.challenge.get('snonce'):
raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty."))
self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1')
if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm']))
self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1')
if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']:
raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm']))
if self.challenge['algorithm'] == 'HMAC-MD5':
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge['pw-algorithm'] == 'MD5':
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join([self.credentials[0], ":",
self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(),
":", self.challenge['realm']
])
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val)
request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % (
self.credentials[0],
self.challenge['realm'],
self.challenge['snonce'],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {})
if challenge.get('reason') in ['integrity', 'stale']:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(self, credentials, host, request_uri, headers, response, content, http):
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % (
self.credentials[0],
password_digest,
cnonce,
iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(self, credentials, host, request_uri, headers, response, content, http):
from urllib import urlencode
Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http)
challenge = _parse_www_authenticate(response, 'www-authenticate')
service = challenge['googlelogin'].get('service', 'xapi')
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == 'xapi' and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
#elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent'])
resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'})
lines = content.split('\n')
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d['Auth']
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers['authorization'] = 'GoogleLogin Auth=' + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = file(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = file(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None):
"""The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX
constants. For example:
p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000)
"""
self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass = proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass
def astuple(self):
return (self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns,
self.proxy_user, self.proxy_pass)
def isgood(self):
return (self.proxy_host != None) and (self.proxy_port != None)
class HTTPConnectionWithTimeout(httplib.HTTPConnection):
"""
HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
httplib.HTTPConnection.__init__(self, host, port, strict)
self.timeout = timeout
self.proxy_info = proxy_info
def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
'Proxy support missing but proxy use was requested!')
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(self.host, self.port, 0,
socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if self.proxy_info and self.proxy_info.isgood():
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(*self.proxy_info.astuple())
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# Different from httplib: support timeouts.
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
# End of difference from httplib.
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
"""
This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
httplib.HTTPSConnection.__init__(self, host, port=port, key_file=key_file,
cert_file=cert_file, strict=strict)
self.timeout = timeout
self.proxy_info = proxy_info
if ca_certs is None:
ca_certs = CA_CERTS
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# The following two methods were adapted from https_wrapper.py, released
# with the Google Appengine SDK at
# http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
# under the following license:
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def _GetValidHostsForCert(self, cert):
"""Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.
"""
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def _ValidateCertificateHostname(self, cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.
"""
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def connect(self):
"Connect to a host on a given (SSL) port."
msg = "getaddrinfo returns an empty list"
for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(
self.host, self.port, 0, socket.SOCK_STREAM):
try:
if self.proxy_info and self.proxy_info.isgood():
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(*self.proxy_info.astuple())
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
self.sock =_ssl_wrap_socket(
sock, self.key_file, self.cert_file,
self.disable_ssl_certificate_validation, self.ca_certs)
if self.debuglevel > 0:
print "connect: (%s, %s)" % (self.host, self.port)
if not self.disable_ssl_certificate_validation:
cert = self.sock.getpeercert()
hostname = self.host.split(':', 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise CertificateHostnameMismatch(
'Server presented certificate that does not match '
'host %s: %s' % (hostname, cert), hostname, cert)
except ssl_SSLError, e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
# Unfortunately the ssl module doesn't seem to provide any way
# to get at more detailed error information, in particular
# whether the error is due to certificate validation or
# something else (such as SSL protocol mismatch).
if e.errno == ssl.SSL_ERROR_SSL:
raise SSLHandshakeError(e)
else:
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error, msg:
if self.debuglevel > 0:
print 'connect fail:', (self.host, self.port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
SCHEME_TO_CONNECTION = {
'http': HTTPConnectionWithTimeout,
'https': HTTPSConnectionWithTimeout
}
# Use a different connection object for Google App Engine
try:
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None:
raise ImportError # Bail out; we're not actually running on App Engine.
from google.appengine.api.urlfetch import fetch
from google.appengine.api.urlfetch import InvalidURLError
from google.appengine.api.urlfetch import DownloadError
from google.appengine.api.urlfetch import ResponseTooLargeError
from google.appengine.api.urlfetch import SSLCertificateError
class ResponseDict(dict):
"""Is a dictionary that also has a read() method, so
that it can pass itself off as an httlib.HTTPResponse()."""
def read(self):
pass
class AppEngineHttpConnection(object):
"""Emulates an httplib.HTTPConnection object, but actually uses the Google
App Engine urlfetch library. This allows the timeout to be properly used on
Google App Engine, and avoids using httplib, which on Google App Engine is
just another wrapper around urlfetch.
"""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None, ca_certs=None,
disable_certificate_validation=False):
self.host = host
self.port = port
self.timeout = timeout
if key_file or cert_file or proxy_info or ca_certs:
raise NotSupportedOnThisPlatform()
self.response = None
self.scheme = 'http'
self.validate_certificate = not disable_certificate_validation
self.sock = True
def request(self, method, url, body, headers):
# Calculate the absolute URI, which fetch requires
netloc = self.host
if self.port:
netloc = '%s:%s' % (self.host, self.port)
absolute_uri = '%s://%s%s' % (self.scheme, netloc, url)
try:
response = fetch(absolute_uri, payload=body, method=method,
headers=headers, allow_truncated=False, follow_redirects=False,
deadline=self.timeout,
validate_certificate=self.validate_certificate)
self.response = ResponseDict(response.headers)
self.response['status'] = str(response.status_code)
self.response.status = response.status_code
setattr(self.response, 'read', lambda : response.content)
# Make sure the exceptions raised match the exceptions expected.
except InvalidURLError:
raise socket.gaierror('')
except (DownloadError, ResponseTooLargeError, SSLCertificateError):
raise httplib.HTTPException()
def getresponse(self):
if self.response:
return self.response
else:
raise httplib.HTTPException()
def set_debuglevel(self, level):
pass
def connect(self):
pass
def close(self):
pass
class AppEngineHttpsConnection(AppEngineHttpConnection):
"""Same as AppEngineHttpConnection, but for HTTPS URIs."""
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None, timeout=None, proxy_info=None):
AppEngineHttpConnection.__init__(self, host, port, key_file, cert_file,
strict, timeout, proxy_info)
self.scheme = 'https'
# Update the connection classes to use the Googel App Engine specific ones.
SCHEME_TO_CONNECTION = {
'http': AppEngineHttpConnection,
'https': AppEngineHttpsConnection
}
except ImportError:
pass
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(self, cache=None, timeout=None, proxy_info=None,
ca_certs=None, disable_ssl_certificate_validation=False):
"""
The value of proxy_info is a ProxyInfo instance.
If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = \
disable_ssl_certificate_validation
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, basestring):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, 'www-authenticate')
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if challenges.has_key(scheme):
yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
for i in range(2):
try:
if conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except ssl_SSLError:
conn.close()
raise
except socket.error, e:
err = 0
if hasattr(e, 'args'):
err = getattr(e, 'args')[0]
else:
err = e.errno
if err == errno.ECONNREFUSED: # Connection refused
raise
except httplib.HTTPException:
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
if conn.sock is None:
if i == 0:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i == 0:
conn.close()
conn.connect()
continue
try:
response = conn.getresponse()
except (socket.error, httplib.HTTPException):
if i == 0:
conn.close()
conn.connect()
continue
else:
raise
else:
content = ""
if method == "HEAD":
response.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers )
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(host, request_uri, headers, response, content):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(conn, request_uri, method, body, headers, )
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303):
if self.follow_redirects and response.status in [300, 301, 302, 303, 307]:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if not response.has_key('location') and response.status != 300:
raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if response.has_key('location'):
location = response['location']
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response['location'] = urlparse.urljoin(absolute_uri, location)
if response.status == 301 and method in ["GET", "HEAD"]:
response['-x-permanent-redirect-url'] = response['location']
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if headers.has_key('if-none-match'):
del headers['if-none-match']
if headers.has_key('if-modified-since'):
del headers['if-modified-since']
if response.has_key('location'):
location = response['location']
old_response = copy.deepcopy(response)
if not old_response.has_key('content-location'):
old_response['content-location'] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1)
response.previous = old_response
else:
raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content)
elif response.status in [200, 203] and method in ["GET", "HEAD"]:
# Don't cache 206's since we aren't going to handle byte range requests
if not response.has_key('content-location'):
response['content-location'] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin
with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc.
There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a string
object.
Any extra headers that are to be sent with the request should be provided in the
'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if not headers.has_key('user-agent'):
headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
domain_port = authority.split(":")[0:2]
if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http':
scheme = 'https'
authority = domain_port[0]
conn_key = scheme+":"+authority
if conn_key in self.connections:
conn = self.connections[conn_key]
else:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if issubclass(connection_type, HTTPSConnectionWithTimeout):
if certs:
conn = self.connections[conn_key] = connection_type(
authority, key_file=certs[0][0],
cert_file=certs[0][1], timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=
self.disable_ssl_certificate_validation)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout,
proxy_info=self.proxy_info)
conn.set_debuglevel(debuglevel)
if 'range' not in headers and 'accept-encoding' not in headers:
headers['accept-encoding'] = 'gzip, deflate'
info = email.Message.Message()
cached_value = None
if self.cache:
cachekey = defrag_uri
cached_value = self.cache.get(cachekey)
if cached_value:
# info = email.message_from_string(cached_value)
#
# Need to replace the line above with the kludge below
# to fix the non-existent bug not fixed in this
# bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html
try:
info, content = cached_value.split('\r\n\r\n', 1)
feedparser = email.FeedParser.FeedParser()
feedparser.feed(info)
info = feedparser.close()
feedparser._parse = None
except IndexError:
self.cache.delete(cachekey)
cachekey = None
cached_value = None
else:
cachekey = None
if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers:
# http://www.w3.org/1999/04/Editing/
headers['if-match'] = info['etag']
if method not in ["GET", "HEAD"] and self.cache and cachekey:
# RFC 2616 Section 13.10
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in ['GET', 'HEAD'] and 'vary' in info:
vary = info['vary']
vary_headers = vary.lower().replace(' ', '').split(',')
for header in vary_headers:
key = '-varied-%s' % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers:
if info.has_key('-x-permanent-redirect-url'):
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "")
(response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info['status'] = '504'
content = ""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers:
headers['if-none-match'] = info['etag']
if info.has_key('last-modified') and not 'last-modified' in headers:
headers['if-modified-since'] = info['last-modified']
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(headers, merged_response, content, self.cache, cachekey)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if cc.has_key('only-if-cached'):
info['status'] = '504'
response = Response(info)
content = ""
else:
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
except Exception, e:
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = "Request Timeout"
response = Response( {
"content-type": "text/plain",
"status": "408",
"content-length": len(content)
})
response.reason = "Request Timeout"
else:
content = str(e)
response = Response( {
"content-type": "text/plain",
"status": "400",
"content-length": len(content)
})
response.reason = "Bad Request"
else:
raise
return (response, content)
class Response(dict):
"""An object more like email.Message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.Message or
# an httplib.HTTPResponse object.
if isinstance(info, httplib.HTTPResponse):
for key, value in info.getheaders():
self[key.lower()] = value
self.status = info.status
self['status'] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.Message.Message):
for key, value in info.items():
self[key] = value
self.status = int(self['status'])
else:
for key, value in info.iteritems():
self[key] = value
self.status = int(self.get('status', self.status))
def __getattr__(self, name):
if name == 'dict':
return self
else:
raise AttributeError, name
| zzangtest123-google-drive-sdk-samples | python/lib/httplib2/__init__.py | Python | asf20 | 64,159 |
"""SocksiPy - Python SOCKS module.
Version 1.00
Copyright 2006 Dan-Haim. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
3. Neither the name of Dan Haim nor the names of his contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY DAN HAIM "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 DAN HAIM OR HIS 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, 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 DAMANGE.
This module provides a standard socket-like interface for Python
for tunneling connections through SOCKS proxies.
"""
"""
Minor modifications made by Christopher Gilbert (http://motomastyle.com/)
for use in PyLoris (http://pyloris.sourceforge.net/)
Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/)
mainly to merge bug fixes found in Sourceforge
"""
import base64
import socket
import struct
import sys
if getattr(socket, 'socket', None) is None:
raise ImportError('socket.socket missing, proxy support unusable')
PROXY_TYPE_SOCKS4 = 1
PROXY_TYPE_SOCKS5 = 2
PROXY_TYPE_HTTP = 3
PROXY_TYPE_HTTP_NO_TUNNEL = 4
_defaultproxy = None
_orgsocket = socket.socket
class ProxyError(Exception): pass
class GeneralProxyError(ProxyError): pass
class Socks5AuthError(ProxyError): pass
class Socks5Error(ProxyError): pass
class Socks4Error(ProxyError): pass
class HTTPError(ProxyError): pass
_generalerrors = ("success",
"invalid data",
"not connected",
"not available",
"bad proxy type",
"bad input")
_socks5errors = ("succeeded",
"general SOCKS server failure",
"connection not allowed by ruleset",
"Network unreachable",
"Host unreachable",
"Connection refused",
"TTL expired",
"Command not supported",
"Address type not supported",
"Unknown error")
_socks5autherrors = ("succeeded",
"authentication is required",
"all offered authentication methods were rejected",
"unknown username or invalid password",
"unknown error")
_socks4errors = ("request granted",
"request rejected or failed",
"request rejected because SOCKS server cannot connect to identd on the client",
"request rejected because the client program and identd report different user-ids",
"unknown error")
def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
"""setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets a default proxy which all further socksocket objects will use,
unless explicitly changed.
"""
global _defaultproxy
_defaultproxy = (proxytype, addr, port, rdns, username, password)
def wrapmodule(module):
"""wrapmodule(module)
Attempts to replace a module's socket library with a SOCKS socket. Must set
a default proxy using setdefaultproxy(...) first.
This will only work on modules that import socket directly into the namespace;
most of the Python Standard Library falls into this category.
"""
if _defaultproxy != None:
module.socket.socket = socksocket
else:
raise GeneralProxyError((4, "no proxy specified"))
class socksocket(socket.socket):
"""socksocket([family[, type[, proto]]]) -> socket object
Open a SOCKS enabled socket. The parameters are the same as
those of the standard socket init. In order for SOCKS to work,
you must specify family=AF_INET, type=SOCK_STREAM and proto=0.
"""
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None):
_orgsocket.__init__(self, family, type, proto, _sock)
if _defaultproxy != None:
self.__proxy = _defaultproxy
else:
self.__proxy = (None, None, None, None, None, None)
self.__proxysockname = None
self.__proxypeername = None
self.__httptunnel = True
def __recvall(self, count):
"""__recvall(count) -> data
Receive EXACTLY the number of bytes requested from the socket.
Blocks until the required number of bytes have been received.
"""
data = self.recv(count)
while len(data) < count:
d = self.recv(count-len(data))
if not d: raise GeneralProxyError((0, "connection closed unexpectedly"))
data = data + d
return data
def sendall(self, content, *args):
""" override socket.socket.sendall method to rewrite the header
for non-tunneling proxies if needed
"""
if not self.__httptunnel:
content = self.__rewriteproxy(content)
return super(socksocket, self).sendall(content, *args)
def __rewriteproxy(self, header):
""" rewrite HTTP request headers to support non-tunneling proxies
(i.e. those which do not support the CONNECT method).
This only works for HTTP (not HTTPS) since HTTPS requires tunneling.
"""
host, endpt = None, None
hdrs = header.split("\r\n")
for hdr in hdrs:
if hdr.lower().startswith("host:"):
host = hdr
elif hdr.lower().startswith("get") or hdr.lower().startswith("post"):
endpt = hdr
if host and endpt:
hdrs.remove(host)
hdrs.remove(endpt)
host = host.split(" ")[1]
endpt = endpt.split(" ")
if (self.__proxy[4] != None and self.__proxy[5] != None):
hdrs.insert(0, self.__getauthheader())
hdrs.insert(0, "Host: %s" % host)
hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2]))
return "\r\n".join(hdrs)
def __getauthheader(self):
auth = self.__proxy[4] + ":" + self.__proxy[5]
return "Proxy-Authorization: Basic " + base64.b64encode(auth)
def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None):
"""setproxy(proxytype, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxytype - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
addr - The address of the server (IP or DNS).
port - The port of the server. Defaults to 1080 for SOCKS
servers and 8080 for HTTP proxy servers.
rdns - Should DNS queries be preformed on the remote side
(rather than the local side). The default is True.
Note: This has no effect with SOCKS4 servers.
username - Username to authenticate with to the server.
The default is no authentication.
password - Password to authenticate with to the server.
Only relevant when username is also provided.
"""
self.__proxy = (proxytype, addr, port, rdns, username, password)
def __negotiatesocks5(self, destaddr, destport):
"""__negotiatesocks5(self,destaddr,destport)
Negotiates a connection through a SOCKS5 server.
"""
# First we'll send the authentication packages we support.
if (self.__proxy[4]!=None) and (self.__proxy[5]!=None):
# The username/password details were supplied to the
# setproxy method so we support the USERNAME/PASSWORD
# authentication (in addition to the standard none).
self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02))
else:
# No username/password were entered, therefore we
# only support connections with no authentication.
self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00))
# We'll receive the server's response to determine which
# method was selected
chosenauth = self.__recvall(2)
if chosenauth[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
# Check the chosen authentication method
if chosenauth[1:2] == chr(0x00).encode():
# No authentication is required
pass
elif chosenauth[1:2] == chr(0x02).encode():
# Okay, we need to perform a basic username/password
# authentication.
self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5])
authstat = self.__recvall(2)
if authstat[0:1] != chr(0x01).encode():
# Bad response
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if authstat[1:2] != chr(0x00).encode():
# Authentication failed
self.close()
raise Socks5AuthError((3, _socks5autherrors[3]))
# Authentication succeeded
else:
# Reaching here is always bad
self.close()
if chosenauth[1] == chr(0xFF).encode():
raise Socks5AuthError((2, _socks5autherrors[2]))
else:
raise GeneralProxyError((1, _generalerrors[1]))
# Now we can request the actual connection
req = struct.pack('BBB', 0x05, 0x01, 0x00)
# If the given destination address is an IP address, we'll
# use the IPv4 address request even if remote resolving was specified.
try:
ipaddr = socket.inet_aton(destaddr)
req = req + chr(0x01).encode() + ipaddr
except socket.error:
# Well it's not an IP number, so it's probably a DNS name.
if self.__proxy[3]:
# Resolve remotely
ipaddr = None
req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr
else:
# Resolve locally
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
req = req + chr(0x01).encode() + ipaddr
req = req + struct.pack(">H", destport)
self.sendall(req)
# Get the response
resp = self.__recvall(4)
if resp[0:1] != chr(0x05).encode():
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
elif resp[1:2] != chr(0x00).encode():
# Connection failed
self.close()
if ord(resp[1:2])<=8:
raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])]))
else:
raise Socks5Error((9, _socks5errors[9]))
# Get the bound address/port
elif resp[3:4] == chr(0x01).encode():
boundaddr = self.__recvall(4)
elif resp[3:4] == chr(0x03).encode():
resp = resp + self.recv(1)
boundaddr = self.__recvall(ord(resp[4:5]))
else:
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
boundport = struct.unpack(">H", self.__recvall(2))[0]
self.__proxysockname = (boundaddr, boundport)
if ipaddr != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport)
def getproxysockname(self):
"""getsockname() -> address info
Returns the bound IP address and port number at the proxy.
"""
return self.__proxysockname
def getproxypeername(self):
"""getproxypeername() -> address info
Returns the IP and port number of the proxy.
"""
return _orgsocket.getpeername(self)
def getpeername(self):
"""getpeername() -> address info
Returns the IP address and port number of the destination
machine (note: getproxypeername returns the proxy)
"""
return self.__proxypeername
def __negotiatesocks4(self,destaddr,destport):
"""__negotiatesocks4(self,destaddr,destport)
Negotiates a connection through a SOCKS4 server.
"""
# Check if the destination address provided is an IP address
rmtrslv = False
try:
ipaddr = socket.inet_aton(destaddr)
except socket.error:
# It's a DNS name. Check where it should be resolved.
if self.__proxy[3]:
ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01)
rmtrslv = True
else:
ipaddr = socket.inet_aton(socket.gethostbyname(destaddr))
# Construct the request packet
req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
# The username parameter is considered userid for SOCKS4
if self.__proxy[4] != None:
req = req + self.__proxy[4]
req = req + chr(0x00).encode()
# DNS name if remote resolving is required
# NOTE: This is actually an extension to the SOCKS4 protocol
# called SOCKS4A and may not be supported in all cases.
if rmtrslv:
req = req + destaddr + chr(0x00).encode()
self.sendall(req)
# Get the response from the server
resp = self.__recvall(8)
if resp[0:1] != chr(0x00).encode():
# Bad data
self.close()
raise GeneralProxyError((1,_generalerrors[1]))
if resp[1:2] != chr(0x5A).encode():
# Server returned an error
self.close()
if ord(resp[1:2]) in (91, 92, 93):
self.close()
raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90]))
else:
raise Socks4Error((94, _socks4errors[4]))
# Get the bound address/port
self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
if rmtrslv != None:
self.__proxypeername = (socket.inet_ntoa(ipaddr), destport)
else:
self.__proxypeername = (destaddr, destport)
def __negotiatehttp(self, destaddr, destport):
"""__negotiatehttp(self,destaddr,destport)
Negotiates a connection through an HTTP server.
"""
# If we need to resolve locally, we do this now
if not self.__proxy[3]:
addr = socket.gethostbyname(destaddr)
else:
addr = destaddr
headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"]
headers += ["Host: ", destaddr, "\r\n"]
if (self.__proxy[4] != None and self.__proxy[5] != None):
headers += [self.__getauthheader(), "\r\n"]
headers.append("\r\n")
self.sendall("".join(headers).encode())
# We read the response until we get the string "\r\n\r\n"
resp = self.recv(1)
while resp.find("\r\n\r\n".encode()) == -1:
resp = resp + self.recv(1)
# We just need the first line to check if the connection
# was successful
statusline = resp.splitlines()[0].split(" ".encode(), 2)
if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()):
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
try:
statuscode = int(statusline[1])
except ValueError:
self.close()
raise GeneralProxyError((1, _generalerrors[1]))
if statuscode != 200:
self.close()
raise HTTPError((statuscode, statusline[2]))
self.__proxysockname = ("0.0.0.0", 0)
self.__proxypeername = (addr, destport)
def connect(self, destpair):
"""connect(self, despair)
Connects to the specified destination through a proxy.
destpar - A tuple of the IP/DNS address and the port number.
(identical to socket's connect).
To select the proxy server use setproxy().
"""
# Do a minimal input check first
if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int):
raise GeneralProxyError((5, _generalerrors[5]))
if self.__proxy[0] == PROXY_TYPE_SOCKS5:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self, (self.__proxy[1], portnum))
self.__negotiatesocks5(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_SOCKS4:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 1080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatesocks4(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1], portnum))
self.__negotiatehttp(destpair[0], destpair[1])
elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL:
if self.__proxy[2] != None:
portnum = self.__proxy[2]
else:
portnum = 8080
_orgsocket.connect(self,(self.__proxy[1],portnum))
if destpair[1] == 443:
self.__negotiatehttp(destpair[0],destpair[1])
else:
self.__httptunnel = False
elif self.__proxy[0] == None:
_orgsocket.connect(self, (destpair[0], destpair[1]))
else:
raise GeneralProxyError((4, _generalerrors[4]))
| zzangtest123-google-drive-sdk-samples | python/lib/httplib2/socks.py | Python | asf20 | 18,456 |
import Cookie
import datetime
import time
import email.utils
import calendar
import base64
import hashlib
import hmac
import re
import logging
# Ripped from the Tornado Framework's web.py
# http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09
#
# Tornado is licensed under the Apache Licence, Version 2.0
# (http://www.apache.org/licenses/LICENSE-2.0.html).
#
# Example:
# from vendor.prayls.lilcookies import LilCookies
# cookieutil = LilCookies(self, application_settings['cookie_secret'])
# cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100)
# cookieutil.get_secure_cookie(name = 'mykey')
class LilCookies:
@staticmethod
def _utf8(s):
if isinstance(s, unicode):
return s.encode("utf-8")
assert isinstance(s, str)
return s
@staticmethod
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
@staticmethod
def _signature_from_secret(cookie_secret, *parts):
""" Takes a secret salt value to create a signature for values in the `parts` param."""
hash = hmac.new(cookie_secret, digestmod=hashlib.sha1)
for part in parts: hash.update(part)
return hash.hexdigest()
@staticmethod
def _signed_cookie_value(cookie_secret, name, value):
""" Returns a signed value for use in a cookie.
This is helpful to have in its own method if you need to re-use this function for other needs. """
timestamp = str(int(time.time()))
value = base64.b64encode(value)
signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp)
return "|".join([value, timestamp, signature])
@staticmethod
def _verified_cookie_value(cookie_secret, name, signed_value):
"""Returns the un-encrypted value given the signed value if it validates, or None."""
value = signed_value
if not value: return None
parts = value.split("|")
if len(parts) != 3: return None
signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1])
if not LilCookies._time_independent_equals(parts[2], signature):
logging.warning("Invalid cookie signature %r", value)
return None
timestamp = int(parts[1])
if timestamp < time.time() - 31 * 86400:
logging.warning("Expired cookie %r", value)
return None
try:
return base64.b64decode(parts[0])
except:
return None
def __init__(self, handler, cookie_secret):
"""You must specify the cookie_secret to use any of the secure methods.
It should be a long, random sequence of bytes to be used as the HMAC
secret for the signature.
"""
if len(cookie_secret) < 45:
raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret)
self.handler = handler
self.request = handler.request
self.response = handler.response
self.cookie_secret = cookie_secret
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
if not hasattr(self, "_cookies"):
self._cookies = Cookie.BaseCookie()
if "Cookie" in self.request.headers:
try:
self._cookies.load(self.request.headers["Cookie"])
except:
self.clear_all_cookies()
return self._cookies
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if name in self.cookies():
return self._cookies[name].value
return default
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
name = LilCookies._utf8(name)
value = LilCookies._utf8(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookies"):
self._new_cookies = []
new_cookie = Cookie.BaseCookie()
self._new_cookies.append(new_cookie)
new_cookie[name] = value
if domain:
new_cookie[name]["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
if expires:
timestamp = calendar.timegm(expires.utctimetuple())
new_cookie[name]["expires"] = email.utils.formatdate(
timestamp, localtime=False, usegmt=True)
if path:
new_cookie[name]["path"] = path
for k, v in kwargs.iteritems():
new_cookie[name][k] = v
# The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush.
for vals in new_cookie.values():
self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None)))
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
self.set_cookie(name, value="", path=path, expires=expires,
domain=domain)
def clear_all_cookies(self):
"""Deletes all the cookies the user sent with this request."""
for name in self.cookies().iterkeys():
self.clear_cookie(name)
def set_secure_cookie(self, name, value, expires_days=30, **kwargs):
"""Signs and timestamps a cookie so it cannot be forged.
To read a cookie set with this method, use get_secure_cookie().
"""
value = LilCookies._signed_cookie_value(self.cookie_secret, name, value)
self.set_cookie(name, value, expires_days=expires_days, **kwargs)
def get_secure_cookie(self, name, value=None):
"""Returns the given signed cookie if it validates, or None."""
if value is None: value = self.get_cookie(name)
return LilCookies._verified_cookie_value(self.cookie_secret, name, value)
def _cookie_signature(self, *parts):
return LilCookies._signature_from_secret(self.cookie_secret)
| zzangtest123-google-drive-sdk-samples | python/lib/sessions.py | Python | asf20 | 6,238 |
# This is the version of this source code.
manual_verstr = "1.5"
auto_build_num = "211"
verstr = manual_verstr + "." + auto_build_num
try:
from pyutil.version_class import Version as pyutil_Version
__version__ = pyutil_Version(verstr)
except (ImportError, ValueError):
# Maybe there is no pyutil installed.
from distutils.version import LooseVersion as distutils_Version
__version__ = distutils_Version(verstr)
| zzangtest123-google-drive-sdk-samples | python/lib/oauth2/_version.py | Python | asf20 | 438 |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import smtplib
import base64
class SMTP(smtplib.SMTP):
"""SMTP wrapper for smtplib.SMTP that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
self.docmd('AUTH', 'XOAUTH %s' % \
base64.b64encode(oauth2.build_xoauth_string(url, consumer, token)))
| zzangtest123-google-drive-sdk-samples | python/lib/oauth2/clients/smtp.py | Python | asf20 | 1,680 |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import oauth2
import imaplib
class IMAP4_SSL(imaplib.IMAP4_SSL):
"""IMAP wrapper for imaplib.IMAP4_SSL that implements XOAUTH."""
def authenticate(self, url, consumer, token):
if consumer is not None and not isinstance(consumer, oauth2.Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, oauth2.Token):
raise ValueError("Invalid token.")
imaplib.IMAP4_SSL.authenticate(self, 'XOAUTH',
lambda x: oauth2.build_xoauth_string(url, consumer, token))
| zzangtest123-google-drive-sdk-samples | python/lib/oauth2/clients/imap.py | Python | asf20 | 1,685 |
"""
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import base64
import urllib
import time
import random
import urlparse
import hmac
import binascii
import httplib2
try:
from urlparse import parse_qs
parse_qs # placate pyflakes
except ImportError:
# fall back for Python 2.5
from cgi import parse_qs
try:
from hashlib import sha1
sha = sha1
except ImportError:
# hashlib was added in Python 2.5
import sha
import _version
__version__ = _version.__version__
OAUTH_VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class Error(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occurred.'):
self._message = message
@property
def message(self):
"""A hack to get around the deprecation errors in 2.6."""
return self._message
def __str__(self):
return self._message
class MissingSignature(Error):
pass
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def build_xoauth_string(url, consumer, token=None):
"""Build an XOAUTH string for use in SMTP/IMPA authentication."""
request = Request.from_consumer_and_token(consumer, token,
"GET", url)
signing_method = SignatureMethod_HMAC_SHA1()
request.sign_request(signing_method, consumer, token)
params = []
for k, v in sorted(request.iteritems()):
if v is not None:
params.append('%s="%s"' % (k, escape(v)))
return "%s %s %s" % ("GET", url, ','.join(params))
def to_unicode(s):
""" Convert to unicode, raise exception with instructive error
message if s is not unicode, ascii, or utf-8. """
if not isinstance(s, unicode):
if not isinstance(s, str):
raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s))
try:
s = s.decode('utf-8')
except UnicodeDecodeError, le:
raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,))
return s
def to_utf8(s):
return to_unicode(s).encode('utf-8')
def to_unicode_if_string(s):
if isinstance(s, basestring):
return to_unicode(s)
else:
return s
def to_utf8_if_string(s):
if isinstance(s, basestring):
return to_utf8(s)
else:
return s
def to_unicode_optional_iterator(x):
"""
Raise TypeError if x is a str containing non-utf8 bytes or if x is
an iterable which contains such a str.
"""
if isinstance(x, basestring):
return to_unicode(x)
try:
l = list(x)
except TypeError, e:
assert 'is not iterable' in str(e)
return x
else:
return [ to_unicode(e) for e in l ]
def to_utf8_optional_iterator(x):
"""
Raise TypeError if x is a str or if x is an iterable which
contains a str.
"""
if isinstance(x, basestring):
return to_utf8(x)
try:
l = list(x)
except TypeError, e:
assert 'is not iterable' in str(e)
return x
else:
return [ to_utf8_if_string(e) for e in l ]
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s.encode('utf-8'), safe='~')
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class Consumer(object):
"""A consumer of OAuth-protected services.
The OAuth consumer is a "third-party" service that wants to access
protected resources from an OAuth service provider on behalf of an end
user. It's kind of the OAuth client.
Usually a consumer must be registered with the service provider by the
developer of the consumer software. As part of that process, the service
provider gives the consumer a *key* and a *secret* with which the consumer
software can identify itself to the service. The consumer will include its
key in each request to identify itself, but will use its secret only when
signing requests, to prove that the request is from that particular
registered consumer.
Once registered, the consumer can then use its consumer credentials to ask
the service provider for a request token, kicking off the OAuth
authorization process.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def __str__(self):
data = {'oauth_consumer_key': self.key,
'oauth_consumer_secret': self.secret}
return urllib.urlencode(data)
class Token(object):
"""An OAuth credential used to request authorization or a protected
resource.
Tokens in OAuth comprise a *key* and a *secret*. The key is included in
requests to identify the token being used, but the secret is used only in
the signature, to prove that the requester is who the server gave the
token to.
When first negotiating the authorization, the consumer asks for a *request
token* that the live user authorizes with the service provider. The
consumer then exchanges the request token for an *access token* that can
be used to access protected resources.
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
"""Returns this token as a plain string, suitable for storage.
The resulting string includes the token's secret, so you should never
send or store this string where a third party can read it.
"""
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
@staticmethod
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(s, keep_blank_values=False)
if not len(params):
raise ValueError("Invalid parameter string.")
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_token' not found in OAuth request.")
try:
secret = params['oauth_token_secret'][0]
except Exception:
raise ValueError("'oauth_token_secret' not found in "
"OAuth request.")
token = Token(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
def __str__(self):
return self.to_string()
def setter(attr):
name = attr.__name__
def getter(self):
try:
return self.__dict__[name]
except KeyError:
raise AttributeError(name)
def deleter(self):
del self.__dict__[name]
return property(getter, attr, deleter)
class Request(dict):
"""The parameters and information for an HTTP request, suitable for
authorizing with OAuth credentials.
When a consumer wants to access a service's protected resources, it does
so using a signed HTTP request identifying itself (the consumer) with its
key, and providing an access token authorized by the end user to access
those resources.
"""
version = OAUTH_VERSION
def __init__(self, method=HTTP_METHOD, url=None, parameters=None,
body='', is_form_encoded=False):
if url is not None:
self.url = to_unicode(url)
self.method = method
if parameters is not None:
for k, v in parameters.iteritems():
k = to_unicode(k)
v = to_unicode_optional_iterator(v)
self[k] = v
self.body = body
self.is_form_encoded = is_form_encoded
@setter
def url(self, value):
self.__dict__['url'] = value
if value is not None:
scheme, netloc, path, params, query, fragment = urlparse.urlparse(value)
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
if scheme not in ('http', 'https'):
raise ValueError("Unsupported URL %s (%s)." % (value, scheme))
# Normalized URL excludes params, query, and fragment.
self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None))
else:
self.normalized_url = None
self.__dict__['url'] = None
@setter
def method(self, value):
self.__dict__['method'] = value.upper()
def _get_timestamp_nonce(self):
return self['oauth_timestamp'], self['oauth_nonce']
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
return dict([(k, v) for k, v in self.iteritems()
if not k.startswith('oauth_')])
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
oauth_params = ((k, v) for k, v in self.items()
if k.startswith('oauth_'))
stringy_params = ((k, escape(str(v))) for k, v in oauth_params)
header_params = ('%s="%s"' % (k, v) for k, v in stringy_params)
params_header = ', '.join(header_params)
auth_header = 'OAuth realm="%s"' % realm
if params_header:
auth_header = "%s, %s" % (auth_header, params_header)
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
d = {}
for k, v in self.iteritems():
d[k.encode('utf-8')] = to_utf8_optional_iterator(v)
# tell urlencode to deal with sequence values and map them correctly
# to resulting querystring. for example self["k"] = ["v1", "v2"] will
# result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
return urllib.urlencode(d, True).replace('+', '%20')
def to_url(self):
"""Serialize as a URL for a GET request."""
base_url = urlparse.urlparse(self.url)
try:
query = base_url.query
except AttributeError:
# must be python <2.5
query = base_url[4]
query = parse_qs(query)
for k, v in self.items():
query.setdefault(k, []).append(v)
try:
scheme = base_url.scheme
netloc = base_url.netloc
path = base_url.path
params = base_url.params
fragment = base_url.fragment
except AttributeError:
# must be python <2.5
scheme = base_url[0]
netloc = base_url[1]
path = base_url[2]
params = base_url[3]
fragment = base_url[5]
url = (scheme, netloc, path, params,
urllib.urlencode(query, True), fragment)
return urlparse.urlunparse(url)
def get_parameter(self, parameter):
ret = self.get(parameter)
if ret is None:
raise Error('Parameter not found: %s' % parameter)
return ret
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
items = []
for key, value in self.iteritems():
if key == 'oauth_signature':
continue
# 1.0a/9.1.1 states that kvp must be sorted by key, then by value,
# so we unpack sequence values into multiple items for sorting.
if isinstance(value, basestring):
items.append((to_utf8_if_string(key), to_utf8(value)))
else:
try:
value = list(value)
except TypeError, e:
assert 'is not iterable' in str(e)
items.append((to_utf8_if_string(key), to_utf8_if_string(value)))
else:
items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value)
# Include any query string parameters from the provided URL
query = urlparse.urlparse(self.url)[4]
url_items = self._split_url_string(query).items()
url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ]
items.extend(url_items)
items.sort()
encoded_str = urllib.urlencode(items)
# Encode signature parameters per Oauth Core 1.0 protocol
# spec draft 7, section 3.6
# (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6)
# Spaces must be encoded with "%20" instead of "+"
return encoded_str.replace('+', '%20').replace('%7E', '~')
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of sign."""
if not self.is_form_encoded:
# according to
# http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html
# section 4.1.1 "OAuth Consumers MUST NOT include an
# oauth_body_hash parameter on requests with form-encoded
# request bodies."
self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest())
if 'oauth_consumer_key' not in self:
self['oauth_consumer_key'] = consumer.key
if token and 'oauth_token' not in self:
self['oauth_token'] = token.key
self['oauth_signature_method'] = signature_method.name
self['oauth_signature'] = signature_method.sign(self, consumer, token)
@classmethod
def make_timestamp(cls):
"""Get seconds since epoch (UTC)."""
return str(int(time.time()))
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = cls._split_header(auth_header)
parameters.update(header_params)
except:
raise Error('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = cls._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = cls._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return cls(http_method, http_url, parameters)
return None
@classmethod
def from_consumer_and_token(cls, consumer, token=None,
http_method=HTTP_METHOD, http_url=None, parameters=None,
body='', is_form_encoded=False):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': consumer.key,
'oauth_timestamp': cls.make_timestamp(),
'oauth_nonce': cls.make_nonce(),
'oauth_version': cls.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.verifier:
parameters['oauth_verifier'] = token.verifier
return Request(http_method, http_url, parameters, body=body,
is_form_encoded=is_form_encoded)
@classmethod
def from_token_and_callback(cls, token, callback=None,
http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return cls(http_method, http_url, parameters)
@staticmethod
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
@staticmethod
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
class Client(httplib2.Http):
"""OAuthClient is a worker to attempt to execute a request."""
def __init__(self, consumer, token=None, cache=None, timeout=None,
proxy_info=None):
if consumer is not None and not isinstance(consumer, Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, Token):
raise ValueError("Invalid token.")
self.consumer = consumer
self.token = token
self.method = SignatureMethod_HMAC_SHA1()
httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info)
def set_signature_method(self, method):
if not isinstance(method, SignatureMethod):
raise ValueError("Invalid signature method.")
self.method = method
def request(self, uri, method="GET", body='', headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded'
if not isinstance(headers, dict):
headers = {}
if method == "POST":
headers['Content-Type'] = headers.get('Content-Type',
DEFAULT_POST_CONTENT_TYPE)
is_form_encoded = \
headers.get('Content-Type') == 'application/x-www-form-urlencoded'
if is_form_encoded and body:
parameters = parse_qs(body)
else:
parameters = None
req = Request.from_consumer_and_token(self.consumer,
token=self.token, http_method=method, http_url=uri,
parameters=parameters, body=body, is_form_encoded=is_form_encoded)
req.sign_request(self.method, self.consumer, self.token)
schema, rest = urllib.splittype(uri)
if rest.startswith('//'):
hierpart = '//'
else:
hierpart = ''
host, rest = urllib.splithost(rest)
realm = schema + ':' + hierpart + host
if is_form_encoded:
body = req.to_postdata()
elif method == "GET":
uri = req.to_url()
else:
headers.update(req.to_header(realm=realm))
return httplib2.Http.request(self, uri, method=method, body=body,
headers=headers, redirections=redirections,
connection_type=connection_type)
class Server(object):
"""A skeletal implementation of a service provider, providing protected
resources to requests from authorized consumers.
This class implements the logic to check requests for authorization. You
can use it with your web server or web framework to protect certain
resources with OAuth.
"""
timestamp_threshold = 300 # In seconds, five minutes.
version = OAUTH_VERSION
signature_methods = None
def __init__(self, signature_methods=None):
self.signature_methods = signature_methods or {}
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.name] = signature_method
return self.signature_methods
def verify_request(self, request, consumer, token):
"""Verifies an api call and checks all the parameters."""
self._check_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _check_version(self, request):
"""Verify the correct version of the request for this server."""
version = self._get_version(request)
if version and version != self.version:
raise Error('OAuth version %s not supported.' % str(version))
def _get_version(self, request):
"""Return the version of the request for this server."""
try:
version = request.get_parameter('oauth_version')
except:
version = OAUTH_VERSION
return version
def _get_signature_method(self, request):
"""Figure out the signature with some defaults."""
try:
signature_method = request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_verifier(self, request):
return request.get_parameter('oauth_verifier')
def _check_signature(self, request, consumer, token):
timestamp, nonce = request._get_timestamp_nonce()
self._check_timestamp(timestamp)
signature_method = self._get_signature_method(request)
try:
signature = request.get_parameter('oauth_signature')
except:
raise MissingSignature('Missing oauth_signature.')
# Validate the signature.
valid = signature_method.check(request, consumer, token, signature)
if not valid:
key, base = signature_method.signing_base(request, consumer, token)
raise Error('Invalid signature. Expected signature base '
'string: %s' % base)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' % (timestamp, now,
self.timestamp_threshold))
class SignatureMethod(object):
"""A way of signing requests.
The OAuth protocol lets consumers and service providers pick a way to sign
requests. This interface shows the methods expected by the other `oauth`
modules for signing requests. Subclass it and implement its methods to
provide a new way to sign requests.
"""
def signing_base(self, request, consumer, token):
"""Calculates the string that needs to be signed.
This method returns a 2-tuple containing the starting key for the
signing and the message to be signed. The latter may be used in error
messages to help clients debug their software.
"""
raise NotImplementedError
def sign(self, request, consumer, token):
"""Returns the signature for the given request, based on the consumer
and token also provided.
You should use your implementation of `signing_base()` to build the
message to sign. Otherwise it may be less useful for debugging.
"""
raise NotImplementedError
def check(self, request, consumer, token, signature):
"""Returns whether the given signature is the correct signature for
the given consumer and token signing the given request."""
built = self.sign(request, consumer, token)
return built == signature
class SignatureMethod_HMAC_SHA1(SignatureMethod):
name = 'HMAC-SHA1'
def signing_base(self, request, consumer, token):
if not hasattr(request, 'normalized_url') or request.normalized_url is None:
raise ValueError("Base URL for request is not set.")
sig = (
escape(request.method),
escape(request.normalized_url),
escape(request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
raw = '&'.join(sig)
return key, raw
def sign(self, request, consumer, token):
"""Builds the base signature string."""
key, raw = self.signing_base(request, consumer, token)
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class SignatureMethod_PLAINTEXT(SignatureMethod):
name = 'PLAINTEXT'
def signing_base(self, request, consumer, token):
"""Concatenates the consumer key and secret with the token's
secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def sign(self, request, consumer, token):
key, raw = self.signing_base(request, consumer, token)
return raw
| zzangtest123-google-drive-sdk-samples | python/lib/oauth2/__init__.py | Python | asf20 | 29,044 |
# Early, and incomplete implementation of -04.
#
import re
import urllib
RESERVED = ":/?#[]@!$&'()*+,;="
OPERATOR = "+./;?|!@"
EXPLODE = "*+"
MODIFIER = ":^"
TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE)
VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE)
def _tostring(varname, value, explode, operator, safe=""):
if type(value) == type([]):
if explode == "+":
return ",".join([varname + "." + urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
if type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return urllib.quote(value, safe)
def _tostring_path(varname, value, explode, operator, safe=""):
joiner = operator
if type(value) == type([]):
if explode == "+":
return joiner.join([varname + "." + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return urllib.quote(value, safe)
else:
return ""
def _tostring_query(varname, value, explode, operator, safe=""):
joiner = operator
varprefix = ""
if operator == "?":
joiner = "&"
varprefix = varname + "="
if type(value) == type([]):
if 0 == len(value):
return ""
if explode == "+":
return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return varprefix + ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
if 0 == len(value):
return ""
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
else:
return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return varname + "=" + urllib.quote(value, safe)
else:
return varname
TOSTRING = {
"" : _tostring,
"+": _tostring,
";": _tostring_query,
"?": _tostring_query,
"/": _tostring_path,
".": _tostring_path,
}
def expand(template, vars):
def _sub(match):
groupdict = match.groupdict()
operator = groupdict.get('operator')
if operator is None:
operator = ''
varlist = groupdict.get('varlist')
safe = "@"
if operator == '+':
safe = RESERVED
varspecs = varlist.split(",")
varnames = []
defaults = {}
for varspec in varspecs:
m = VAR.search(varspec)
groupdict = m.groupdict()
varname = groupdict.get('varname')
explode = groupdict.get('explode')
partial = groupdict.get('partial')
default = groupdict.get('default')
if default:
defaults[varname] = default
varnames.append((varname, explode, partial))
retval = []
joiner = operator
prefix = operator
if operator == "+":
prefix = ""
joiner = ","
if operator == "?":
joiner = "&"
if operator == "":
joiner = ","
for varname, explode, partial in varnames:
if varname in vars:
value = vars[varname]
#if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults:
if not value and value != "" and varname in defaults:
value = defaults[varname]
elif varname in defaults:
value = defaults[varname]
else:
continue
retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe))
if "".join(retval):
return prefix + joiner.join(retval)
else:
return ""
return TEMPLATE.sub(_sub, template)
| zzangtest123-google-drive-sdk-samples | python/lib/uritemplate/__init__.py | Python | asf20 | 4,780 |
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'sinatra'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'logger'
require 'multi_json'
require 'data_mapper'
enable :sessions
SCOPES = [
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'
]
##
# Datastore entity for storing OAuth 2.0 credentials.
class User
include DataMapper::Resource
property :id, Serial
property :email, String, :length => 255
property :refresh_token, String, :length => 255
end
##
# Set up
configure do
db_url = Addressable::URI.parse(ENV['DATABASE_URL'] || "sqlite://#{Dir.pwd}/user.db")
DataMapper.setup(:default, db_url)
User.auto_migrate!
# App identity
set :credentials, Google::APIClient::ClientSecrets.load
set :app_id, settings.credentials.client_id.sub(/[.-].*/,'')
# Preload API definitions
client = Google::APIClient.new
set :drive, client.discovered_api('drive', 'v1')
set :oauth2, client.discovered_api('oauth2', 'v2')
end
helpers do
##
# Render json data in a response
def json(data)
content_type :json
[200, data.to_json]
end
##
# Get an API client instance
def api_client
@client ||= (begin
client = Google::APIClient.new
client.authorization.client_id = settings.credentials.client_id
client.authorization.client_secret = settings.credentials.client_secret
client.authorization.redirect_uri = settings.credentials.redirect_uris.first
client.authorization.scope = SCOPES
client
end)
end
def current_user
if session[:user_id]
@user ||= User.get(session[:user_id])
end
end
def authorized?
return api_client.authorization.refresh_token && api_client.authorization.access_token
end
end
before do
# Make sure access token is up to date for each request
api_client.authorization.update_token!(session)
if api_client.authorization.refresh_token && api_client.authorization.expired?
api_client.authorization.fetch_access_token!
end
end
after do
# Serialize the access/refresh token to the session
session[:access_token] = api_client.authorization.access_token
session[:refresh_token] = api_client.authorization.refresh_token
session[:expires_in] = api_client.authorization.expires_in
session[:issued_at] = api_client.authorization.issued_at
end
##
# Upgrade our authorization code when a user launches the app from Drive &
# ensures saved refresh token is up to date
def authorize_code(authorization_code)
api_client.authorization.code = authorization_code
api_client.authorization.fetch_access_token!
result = api_client.execute!(:api_method => settings.oauth2.userinfo.get)
user = User.first_or_create(:email => result.data.email)
api_client.authorization.refresh_token = (api_client.authorization.refresh_token || user.refresh_token)
if user.refresh_token != api_client.authorization.refresh_token
user.refresh_token = api_client.authorization.refresh_token
user.save
end
session[:user_id] = user.id
end
def auth_url(state = '')
user_email = current_user ? current_user.email : ''
return api_client.authorization.authorization_uri(
:state => state,
:approval_prompt => :force,
:access_type => :offline,
:user_id => user_email
).to_s
end
##
# Prepare request data for upload
def prepare_data(body)
data = MultiJson.decode(body)
content = StringIO.new(data['content'])
resource_id = data['resource_id']
data.keep_if { |k,v| %w{title description mimeType}.include? k}
file_content = Google::APIClient::UploadIO.new(content, data['mimeType'])
[resource_id, data, file_content]
end
##
# Main entry point for the app. Ensures the user is authorized & inits the editor
# for either edit of the opened files or creating a new file.
get '/' do
state = params[:state] || '{}'
if params[:code]
authorize_code(params[:code])
redirect to("/?state=#{Addressable::URI.encode(state)}")
elsif params[:error] # User denied the oauth grant
halt 403
end
redirect auth_url(state) unless authorized?
state = MultiJson.decode(state)
@state = state
@file_ids = (state['ids'] || [''])
@app_id = settings.app_id
erb :index
end
###
# Load content
#
get '/svc' do
result = api_client.execute!(
:api_method => settings.drive.files.get,
:parameters => { 'id' => params['file_id'] })
file = result.data.to_hash
result = api_client.execute!(:uri => result.data.download_url)
file['content'] = result.body
json file
end
##
# Save a new file
post '/svc' do
_, file, content = prepare_data(request.body)
result = api_client.execute!(
:api_method => settings.drive.files.insert,
:body_object => file,
:media => content,
:parameters => {
'uploadType' => 'multipart',
'alt' => 'json'})
json result.data.id
end
##
# Update existing file
put '/svc' do
resource_id, file, content = prepare_data(request.body)
result = api_client.execute!(
:api_method => settings.drive.files.update,
:body_object => file,
:media => content,
:parameters => {
'id' => resource_id,
'newRevision' => "true",
'uploadType' => 'multipart',
'alt' => 'json'})
json result.data.id
end
##
# For /svc methods, assume client errors are due to auth failures
# and return a redirect (via JSON)
error Google::APIClient::ClientError do
response = {
'redirect' => auth_url('{}')
}
json response
end
##
# Oh noes!
error Google::APIClient::ServerError do
halt 500
end
| zzangtest123-google-drive-sdk-samples | ruby/main.rb | Ruby | asf20 | 6,125 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Namespace for DrEdit user interface.
* @type {object}
*/
var dredit = dredit || {};
dredit.main_view = null;
dredit.new_file_counter = 0;
/**
* User interface controller class.
* @constructor
*/
dredit.View = function(config) {
this.config = config || {};
this.current_page = null;
this.editor_id = 'editor';
this.pages = {};
};
/**
* Creates the user interface of the view.
*/
dredit.View.prototype.CreateUi = function() {
this.CreateNavs();
this.CreateEditor();
this.saver = new dredit.SaveNotification();
$('#edit').click($.proxy(this.Edit, this));
$('#save').click($.proxy(this.Save, this));
$('#create').click($.proxy(this.Create, this));
$('#open').click($.proxy(this.CreatePicker, this));
}
/**
* Creates the list that will hold the file navigation elements.
*/
dredit.View.prototype.CreateNavs = function() {
$('#nav-pane').append(
$('<ul></ul>')
.attr('id', 'editor-navs')
.attr('class', 'nav nav-pills'));
}
/**
* Creates the element that will hold the text editor.
*/
dredit.View.prototype.CreateEditor = function() {
$('#editor-pane').append(
$('<div></div>')
.attr('id', 'editor-holder')
.append(
$('<div></div>')
.attr('class', 'editor')
.attr('id', this.editor_id)));
this.editor = ace.edit(this.editor_id);
var mode = require('ace/mode/html').Mode;
this.editor.getSession().setMode(new mode());
}
/**
* Creates a page for a file ID.
* @param {string} File's ID or an empty string for a new file.
*/
dredit.View.prototype.CreatePage = function(file_id) {
var page = new dredit.Page(this);
page.Load(file_id);
this.pages[page.tab_id] = page;
}
dredit.View.prototype.PickerSelected = function(data) {
if (data.action == 'picked') {
for (i in data.docs) {
this.CreatePage(data.docs[i].id);
}
}
}
dredit.View.prototype.CreatePicker = function() {
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes('text/plain,text/html');
picker = new google.picker.PickerBuilder().
setAppId(dredit.APP_ID).
addView(view).
setCallback($.proxy(this.PickerSelected, this)).
build();
picker.setVisible(true);
}
/**
* Sets a tab id as the active page.
* @param {string} tab_id Tab's ID.
*/
dredit.View.prototype.SetTab = function(tab_id) {
this.SetPage(this.pages[tab_id]);
}
/**
* Sets a page as the active page.
* @param {dredit.Page} page Page to activate.
*/
dredit.View.prototype.SetPage = function(page) {
this.current_page = page;
$('#editor-navs > li').removeClass('active');
page.label_holder.addClass('active');
this.editor.setSession(page.session);
}
/**
* Performs an appropriate XHR to save the current file.
*/
dredit.View.prototype.Save = function() {
if (!dredit.blocked) {
this.current_page.Save();
}
else {
// console.log('Blocked on another operation.');
}
};
dredit.View.prototype.Edit = function() {
this.current_page.title_changer.Pop();
};
dredit.View.prototype.Create = function() {
this.CreatePage();
};
/**
* Model for an individual file.
* @constructor
*/
dredit.Page = function(view) {
this.file_id = null;
this.title = null;
this.description = null;
this.content = null;
this.position = null;
this.view = view;
}
/**
* Create the navigation label for this page.
*/
dredit.Page.prototype.CreateLabel = function() {
this.label_holder = $('<li></li>');
var tab_id = this.tab_id;
var view = this.view;
var _OnFileClicked = function() {
view.SetTab(tab_id);
}
this.label_text = $('<a>Loading</a>')
.attr('href', '#' + this.tab_id)
.click(_OnFileClicked);
this.label_holder.append(this.label_text);
$('#editor-navs').append(this.label_holder);
}
/**
* Load a file from the server.
* @param {string} file ID to load or an empty string for a new file.
*/
dredit.Page.prototype.Load = function(file_id) {
this.title_changer = new dredit.TitleChanger(this);
if (!file_id) {
this.tab_id = dredit.new_file_counter++ + "";
this.title_changer.Pop();
this.CreateLabel();
this.Empty();
}
else {
this.file_id = file_id;
this.tab_id = file_id;
this.CreateLabel();
this.Get();
}
}
dredit.Page.prototype.Empty = function(file_id) {
this.GetSuccess({
'title': 'untitled.html',
'content': '',
'mimeType': 'text/html',
'description': '',
});
}
dredit.Page.prototype.GetSuccess = function(data, result, xhr) {
if (data.redirect) {
window.location.href = data.redirect;
}
else {
this.title = data['title'];
this.UpdateTitle(this.title);
this.content = data['content'];
this.mimetype = data['mimeType'];
this.description = data['description'];
var EditSession = require('ace/edit_session').EditSession;
this.session = new EditSession(this.content);
this.view.SetPage(this);
}
}
dredit.Page.prototype.ServiceError = function(xhr, text_status, error) {
console.log(error);
}
dredit.Page.prototype.Get = function() {
$.ajax({
url: '/svc?file_id=' + this.file_id,
success: this.GetSuccess,
error: this.ServiceError,
context: this
});
}
dredit.Page.prototype.SaveSuccess = function(data, result, xhr) {
if (data.redirect) {
window.location.href = data.redirect;
}
else {
this.file_id = data;
}
}
dredit.Page.prototype.Save = function() {
this.content = this.session.getValue();
$.ajax({
url: '/svc',
type: 'PUT',
type: this.IsNew() ? 'POST' : 'PUT',
success: this.SaveSuccess,
error: this.ServiceError,
data: JSON.stringify(this.Read()),
dataType: 'json',
contentType: 'application/json',
context: this
});
}
dredit.Page.prototype.Read = function() {
return {
'content': this.content,
'title': this.title,
'description': this.description,
'mimeType': this.mimetype,
'resource_id': this.file_id
};
}
dredit.Page.prototype.IsNew = function() {
return (this.file_id == null);
}
dredit.Page.prototype.UpdateTitle = function(title) {
this.title = title;
this.label_text.text(title);
}
dredit.Editor = function(editor_id) {
this.id = editor_id;
this.editor = ace.edit(this.id);
}
dredit.Editor.prototype.SetMode = function(filetype) {
var mode = require('ace/mode/' + filetype).Mode;
this.editor.getSession().setMode(new mode());
}
dredit.SaveNotification = function() {
$('#saving')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
//$('#save').hide();
dredit.blocked = true;
})
.ajaxStop(function() {
$(this).hide();
dredit.blocked = false;
});
}
dredit.TitleChanger = function(page) {
this.page = page;
this.title = null;
this.CreateUi(page.title);
}
dredit.TitleChanger.prototype.Pop = function() {
this.title.val(this.page.title || 'untitled.txt');
this.description.val(this.page.description);
this.modal.modal('show');
this.title.focus().select();
}
dredit.TitleChanger.prototype.Save = function() {
this.page.UpdateTitle(this.title.val());
this.page.description = this.description.val();
this.modal.modal('hide');
this.page.Save();
}
dredit.TitleChanger.prototype.CreateField = function(field, label) {
return $('<div class="control-group"></div>')
.append($('<label class="control-label"></label').text(label))
.append($('<div class="controls"></div>')
.append(field));
}
dredit.TitleChanger.prototype.CreateUi = function() {
this.title = $('<input type="text" placeholder="Enter filename" name="title">');
this.description = $('<textarea placeholder="Enter description"></textarea>');
this.saver = $('<a href="#" class="btn btn-primary">Done</a>');
this.modal = $('<div class="modal"></div>')
.append(
$('<div class="modal-header"></div>')
.append($('<a class="close" data-dismiss="modal">close</a>'))
.append($('<h3>Edit details</h3>')))
.append(
$('<div class="modal-body"></div>')
.append($('<form class="form-horizontal">')
.append(this.CreateField(this.title, 'Title'))
.append(this.CreateField(this.description, 'Description'))))
.append(
$('<div class="modal-footer"></div>')
.append(this.saver))
this.saver.click($.proxy(this.Save, this));
}
function DrEdit() {
this.view = new dredit.View();
this.view.CreateUi();
for (i in dredit.FILE_IDS) {
this.view.CreatePage(dredit.FILE_IDS[i]);
}
}
$(document).ready(function() {
dredit.main = new DrEdit();
});
| zzangtest123-google-drive-sdk-samples | ruby/public/dredit.js | JavaScript | asf20 | 9,186 |
/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
body {
margin: 10px;
}
div#main {
width: 720px;
margin: auto;
}
#title_changer {
display: none;
margin-top: -100px;
}
.editor {
position: relative;
width: 720px;
height: 480px;
}
#editor-pane {
margin-top: 10px;
}
#saving {
}
.tab-content > .active {
}
| zzangtest123-google-drive-sdk-samples | ruby/public/dredit.css | CSS | asf20 | 868 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Define a module along with a payload
* @param module a name for the payload
* @param payload a function to call with (require, exports, module) params
*/
(function() {
var global = (function() {
return this;
})();
// if we find an existing require function use it.
if (global.require && global.define) {
require.packaged = true;
return;
}
var _define = function(module, deps, payload) {
if (typeof module !== 'string') {
if (_define.original)
_define.original.apply(window, arguments);
else {
console.error('dropping module because define wasn\'t a string.');
console.trace();
}
return;
}
if (arguments.length == 2)
payload = deps;
if (!define.modules)
define.modules = {};
define.modules[module] = payload;
};
if (global.define)
_define.original = global.define;
global.define = _define;
/**
* Get at functionality define()ed using the function above
*/
var _require = function(module, callback) {
if (Object.prototype.toString.call(module) === "[object Array]") {
var params = [];
for (var i = 0, l = module.length; i < l; ++i) {
var dep = lookup(module[i]);
if (!dep && _require.original)
return _require.original.apply(window, arguments);
params.push(dep);
}
if (callback) {
callback.apply(null, params);
}
}
else if (typeof module === 'string') {
var payload = lookup(module);
if (!payload && _require.original)
return _require.original.apply(window, arguments);
if (callback) {
callback();
}
return payload;
}
else {
if (_require.original)
return _require.original.apply(window, arguments);
}
};
if (global.require)
_require.original = global.require;
global.require = _require;
require.packaged = true;
/**
* Internal function to lookup moduleNames and resolve them by calling the
* definition function if needed.
*/
var lookup = function(moduleName) {
var module = define.modules[moduleName];
if (module == null) {
console.error('Missing module: ' + moduleName);
return null;
}
if (typeof module === 'function') {
var exports = {};
module(require, exports, { id: moduleName, uri: '' });
// cache the resulting module object for next time
define.modules[moduleName] = exports;
return exports;
}
return module;
};
})();// vim:set ts=4 sts=4 sw=4 st:
// -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project)
// -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified
// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
// -- Irakli Gozalishvili Copyright (C) 2010 MIT License
/*!
Copyright (c) 2009, 280 North Inc. http://280north.com/
MIT License. http://github.com/280north/narwhal/blob/master/README.md
*/
define('pilot/fixoldbrowsers', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* ES5 Draft
* http://www.ecma-international.org/publications/files/drafts/tc39-2009-050.pdf
*
* NOTE: this is a draft, and as such, the URL is subject to change. If the
* link is broken, check in the parent directory for the latest TC39 PDF.
* http://www.ecma-international.org/publications/files/drafts/
*
* Previous ES5 Draft
* http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf
* This is a broken link to the previous draft of ES5 on which most of the
* numbered specification references and quotes herein were taken. Updating
* these references and quotes to reflect the new document would be a welcome
* volunteer project.
*
* @module
*/
/*whatsupdoc*/
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf
if (!Function.prototype.bind) {
var slice = Array.prototype.slice;
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
// XXX this gets pretty close, for all intents and purposes, letting
// some duck-types slide
if (typeof target.apply !== "function" || typeof target.call !== "function")
return new TypeError();
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
var args = slice.call(arguments);
// 4. Let F be a new native ECMAScript object.
// 9. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 10. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 11. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 12. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
// 13. The [[Scope]] internal property of F is unused and need not
// exist.
var bound = function bound() {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
var self = Object.create(target.prototype);
target.apply(self, args.concat(slice.call(arguments)));
return self;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the list
// boundArgs in the same order followed by the same values as
// the list ExtraArgs in the same order. 5. Return the
// result of calling the [[Call]] internal method of target
// providing boundThis as the this value and providing args
// as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.call.apply(
target,
args.concat(slice.call(arguments))
);
}
};
bound.length = (
// 14. If the [[Class]] internal property of Target is "Function", then
typeof target === "function" ?
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is larger.
Math.max(target.length - args.length, 0) :
// 15. Else set the length own property of F to 0.
0
)
// 16. The length own property of F is given attributes as specified in
// 15.3.5.1.
// TODO
// 17. Set the [[Extensible]] internal property of F to true.
// TODO
// 18. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Value]]: null,
// [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]:
// false}, and false.
// TODO
// 19. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Value]]: null,
// [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]:
// false}, and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property.
// XXX can't delete it in pure-js.
return bound;
};
}
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var owns = call.bind(prototypeOfObject.hasOwnProperty);
var defineGetter, defineSetter, lookupGetter, lookupSetter, supportsAccessors;
// If JS engine supports accessors creating shortcuts.
if ((supportsAccessors = owns(prototypeOfObject, '__defineGetter__'))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.3.2
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
}
// ES5 15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(block, thisObject) {
var len = +this.length;
for (var i = 0; i < len; i++) {
if (i in this) {
block.call(thisObject, this[i], i, this);
}
}
};
}
// ES5 15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
// ES5 15.4.4.20
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(block /*, thisp */) {
var values = [];
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (block.call(thisp, this[i]))
values.push(this[i]);
return values;
};
}
// ES5 15.4.4.16
if (!Array.prototype.every) {
Array.prototype.every = function every(block /*, thisp */) {
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (!block.call(thisp, this[i]))
return false;
return true;
};
}
// ES5 15.4.4.17
if (!Array.prototype.some) {
Array.prototype.some = function some(block /*, thisp */) {
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (block.call(thisp, this[i]))
return true;
return false;
};
}
// ES5 15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len === 0 && arguments.length === 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
} while (true);
}
for (; i < len; i++) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
// ES5 15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
// no value to return if no initial value, empty array
if (len === 0 && arguments.length === 1)
throw new TypeError();
var i = len - 1;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0)
throw new TypeError();
} while (true);
}
for (; i >= 0; i--) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
// ES5 15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(value /*, fromIndex */ ) {
var length = this.length;
if (!length)
return -1;
var i = arguments[1] || 0;
if (i >= length)
return -1;
if (i < 0)
i += length;
for (; i < length; i++) {
if (!owns(this, i))
continue;
if (value === this[i])
return i;
}
return -1;
};
}
// ES5 15.4.4.15
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function lastIndexOf(value /*, fromIndex */) {
var length = this.length;
if (!length)
return -1;
var i = arguments[1] || length;
if (i < 0)
i += length;
i = Math.min(i, length - 1);
for (; i >= 0; i--) {
if (!owns(this, i))
continue;
if (value === this[i])
return i;
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.2
if (!Object.getPrototypeOf) {
// https://github.com/kriskowal/es5-shim/issues#issue/2
// http://ejohn.org/blog/objectgetprototypeof/
// recommended by fschaefer on github
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || object.constructor.prototype;
// or undefined if not available in this engine
};
}
// ES5 15.2.3.3
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
"non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object !== "object" && typeof object !== "function") || object === null)
throw new TypeError(ERR_NON_OBJECT + object);
// If object does not owns property return undefined immediately.
if (!owns(object, property))
return undefined;
var despriptor, getter, setter;
// If object has a property then it's for sure both `enumerable` and
// `configurable`.
despriptor = { enumerable: true, configurable: true };
// If JS engine supports accessor properties then property may be a
// getter or setter.
if (supportsAccessors) {
// Unfortunately `__lookupGetter__` will return a getter even
// if object has own non getter property along with a same named
// inherited getter. To avoid misbehavior we temporary remove
// `__proto__` so that `__lookupGetter__` will return getter only
// if it's owned by an object.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
// Once we have getter and setter we can put values back.
object.__proto__ = prototype;
if (getter || setter) {
if (getter) descriptor.get = getter;
if (setter) descriptor.set = setter;
// If it was accessor property we're done and return here
// in order to avoid adding `value` to the descriptor.
return descriptor;
}
}
// If we got this far we know that object has an own property that is
// not an accessor so we set it as a value and return descriptor.
descriptor.value = object[property];
return descriptor;
};
}
// ES5 15.2.3.4
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
// ES5 15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype !== "object")
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
var Type = function () {};
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (typeof properties !== "undefined")
Object.defineProperties(object, properties);
return object;
};
}
// ES5 15.2.3.6
if (!Object.defineProperty) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if (typeof object !== "object" && typeof object !== "function")
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
if (typeof object !== "object" || object === null)
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors)
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get"))
defineGetter(object, property, descriptor.get);
if (owns(descriptor, "set"))
defineSetter(object, property, descriptor.set);
}
return object;
};
}
// ES5 15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property))
Object.defineProperty(object, property, properties[property]);
}
return object;
};
}
// ES5 15.2.3.8
if (!Object.seal) {
Object.seal = function seal(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.9
if (!Object.freeze) {
Object.freeze = function freeze(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// detect a Rhino bug and patch it
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object === "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
// ES5 15.2.3.10
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.11
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
// ES5 15.2.3.12
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
// ES5 15.2.3.13
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
return true;
};
}
// ES5 15.2.3.14
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
if (!Object.keys) {
var hasDontEnumBug = true,
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null})
hasDontEnumBug = false;
Object.keys = function keys(object) {
if (
typeof object !== "object" && typeof object !== "function"
|| object === null
)
throw new TypeError("Object.keys called on a non-object");
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// Format a Date object as a string according to a subset of the ISO-8601 standard.
// Useful in Atom, among other things.
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function toISOString() {
return (
this.getUTCFullYear() + "-" +
(this.getUTCMonth() + 1) + "-" +
this.getUTCDate() + "T" +
this.getUTCHours() + ":" +
this.getUTCMinutes() + ":" +
this.getUTCSeconds() + "Z"
);
}
}
// ES5 15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
// ES5 15.9.5.44
if (!Date.prototype.toJSON) {
Date.prototype.toJSON = function toJSON(key) {
// This function provides a String representation of a Date object for
// use by JSON.stringify (15.12.3). When the toJSON method is called
// with argument key, the following steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be ToPrimitive(O, hint Number).
// 3. If tv is a Number and is not finite, return null.
// XXX
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (typeof this.toISOString !== "function")
throw new TypeError();
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return this.toISOString();
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// 15.9.4.2 Date.parse (string)
// 15.9.1.15 Date Time String Format
// Date.parse
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
if (isNaN(Date.parse("T00:00"))) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function(NativeDate) {
// Date.length === 7
var Date = function(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length === 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(Date.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = Date;
return date;
}
return NativeDate.apply(this, arguments);
};
// 15.9.1.15 Date Time String Format
var isoDateExpression = new RegExp("^" +
"(?:" + // optional year-month-day
"(" + // year capture
"(?:[+-]\\d\\d)?" + // 15.9.1.15.1 Extended years
"\\d\\d\\d\\d" + // four-digit year
")" +
"(?:-" + // optional month-day
"(\\d\\d)" + // month capture
"(?:-" + // optional day
"(\\d\\d)" + // day capture
")?" +
")?" +
")?" +
"(?:T" + // hour:minute:second.subsecond
"(\\d\\d)" + // hour capture
":(\\d\\d)" + // minute capture
"(?::" + // optional :second.subsecond
"(\\d\\d)" + // second capture
"(?:\\.(\\d\\d\\d))?" + // milisecond capture
")?" +
")?" +
"(?:" + // time zone
"Z|" + // UTC capture
"([+-])(\\d\\d):(\\d\\d)" + // timezone offset
// capture sign, hour, minute
")?" +
"$");
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate)
Date[key] = NativeDate[key];
// Copy "native" methods explicitly; they may be non-enumerable
Date.now = NativeDate.now;
Date.UTC = NativeDate.UTC;
Date.prototype = NativeDate.prototype;
Date.prototype.constructor = Date;
// Upgrade Date.parse to handle the ISO dates we use
// TODO review specification to ascertain whether it is
// necessary to implement partial ISO date strings.
Date.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
match.shift(); // kill match[0], the full match
// recognize times without dates before normalizing the
// numeric values, for later use
var timeOnly = match[0] === undefined;
// parse numerics
for (var i = 0; i < 10; i++) {
// skip + or - for the timezone offset
if (i === 7)
continue;
// Note: parseInt would read 0-prefix numbers as
// octal. Number constructor or unary + work better
// here:
match[i] = +(match[i] || (i < 3 ? 1 : 0));
// match[1] is the month. Months are 0-11 in JavaScript
// Date objects, but 1-12 in ISO notation, so we
// decrement.
if (i === 1)
match[i]--;
}
// if no year-month-date is provided, return a milisecond
// quantity instead of a UTC date number value.
if (timeOnly)
return ((match[3] * 60 + match[4]) * 60 + match[5]) * 1000 + match[6];
// account for an explicit time zone offset if provided
var offset = (match[8] * 60 + match[9]) * 60 * 1000;
if (match[6] === "-")
offset = -offset;
return NativeDate.UTC.apply(this, match.slice(0, 7)) + offset;
}
return NativeDate.parse.apply(this, arguments);
};
return Date;
})(Date);
}
//
// String
// ======
//
// ES5 15.5.4.20
if (!String.prototype.trim) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
String.prototype.trim = function trim() {
return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
};
}
});/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/ace', ['require', 'exports', 'module' , 'pilot/index', 'pilot/fixoldbrowsers', 'pilot/plugin_manager', 'pilot/dom', 'pilot/event', 'ace/editor', 'ace/edit_session', 'ace/undomanager', 'ace/virtual_renderer', 'ace/theme/textmate', 'pilot/environment'], function(require, exports, module) {
require("pilot/index");
require("pilot/fixoldbrowsers");
var catalog = require("pilot/plugin_manager").catalog;
catalog.registerPlugins([ "pilot/index" ]);
var Dom = require("pilot/dom");
var Event = require("pilot/event");
var Editor = require("ace/editor").Editor;
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
var Renderer = require("ace/virtual_renderer").VirtualRenderer;
exports.edit = function(el) {
if (typeof(el) == "string") {
el = document.getElementById(el);
}
var doc = new EditSession(Dom.getInnerText(el));
doc.setUndoManager(new UndoManager());
el.innerHTML = '';
var editor = new Editor(new Renderer(el, require("ace/theme/textmate")));
editor.setSession(doc);
var env = require("pilot/environment").create();
catalog.startupPlugins({ env: env }).then(function() {
env.document = doc;
env.editor = editor;
editor.resize();
Event.addListener(window, "resize", function() {
editor.resize();
});
el.env = env;
});
// Store env on editor such that it can be accessed later on from
// the returned object.
editor.env = env;
return editor;
};
});/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/index', ['require', 'exports', 'module' , 'pilot/fixoldbrowsers', 'pilot/types/basic', 'pilot/types/command', 'pilot/types/settings', 'pilot/commands/settings', 'pilot/commands/basic', 'pilot/settings/canon', 'pilot/canon'], function(require, exports, module) {
exports.startup = function(data, reason) {
require('pilot/fixoldbrowsers');
require('pilot/types/basic').startup(data, reason);
require('pilot/types/command').startup(data, reason);
require('pilot/types/settings').startup(data, reason);
require('pilot/commands/settings').startup(data, reason);
require('pilot/commands/basic').startup(data, reason);
// require('pilot/commands/history').startup(data, reason);
require('pilot/settings/canon').startup(data, reason);
require('pilot/canon').startup(data, reason);
};
exports.shutdown = function(data, reason) {
require('pilot/types/basic').shutdown(data, reason);
require('pilot/types/command').shutdown(data, reason);
require('pilot/types/settings').shutdown(data, reason);
require('pilot/commands/settings').shutdown(data, reason);
require('pilot/commands/basic').shutdown(data, reason);
// require('pilot/commands/history').shutdown(data, reason);
require('pilot/settings/canon').shutdown(data, reason);
require('pilot/canon').shutdown(data, reason);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/types/basic', ['require', 'exports', 'module' , 'pilot/types'], function(require, exports, module) {
var types = require("pilot/types");
var Type = types.Type;
var Conversion = types.Conversion;
var Status = types.Status;
/**
* These are the basic types that we accept. They are vaguely based on the
* Jetpack settings system (https://wiki.mozilla.org/Labs/Jetpack/JEP/24)
* although clearly more restricted.
*
* <p>In addition to these types, Jetpack also accepts range, member, password
* that we are thinking of adding.
*
* <p>This module probably should not be accessed directly, but instead used
* through types.js
*/
/**
* 'text' is the default if no type is given.
*/
var text = new Type();
text.stringify = function(value) {
return value;
};
text.parse = function(value) {
if (typeof value != 'string') {
throw new Error('non-string passed to text.parse()');
}
return new Conversion(value);
};
text.name = 'text';
/**
* We don't currently plan to distinguish between integers and floats
*/
var number = new Type();
number.stringify = function(value) {
if (!value) {
return null;
}
return '' + value;
};
number.parse = function(value) {
if (typeof value != 'string') {
throw new Error('non-string passed to number.parse()');
}
if (value.replace(/\s/g, '').length === 0) {
return new Conversion(null, Status.INCOMPLETE, '');
}
var reply = new Conversion(parseInt(value, 10));
if (isNaN(reply.value)) {
reply.status = Status.INVALID;
reply.message = 'Can\'t convert "' + value + '" to a number.';
}
return reply;
};
number.decrement = function(value) {
return value - 1;
};
number.increment = function(value) {
return value + 1;
};
number.name = 'number';
/**
* One of a known set of options
*/
function SelectionType(typeSpec) {
if (!Array.isArray(typeSpec.data) && typeof typeSpec.data !== 'function') {
throw new Error('instances of SelectionType need typeSpec.data to be an array or function that returns an array:' + JSON.stringify(typeSpec));
}
Object.keys(typeSpec).forEach(function(key) {
this[key] = typeSpec[key];
}, this);
};
SelectionType.prototype = new Type();
SelectionType.prototype.stringify = function(value) {
return value;
};
SelectionType.prototype.parse = function(str) {
if (typeof str != 'string') {
throw new Error('non-string passed to parse()');
}
if (!this.data) {
throw new Error('Missing data on selection type extension.');
}
var data = (typeof(this.data) === 'function') ? this.data() : this.data;
// The matchedValue could be the boolean value false
var hasMatched = false;
var matchedValue;
var completions = [];
data.forEach(function(option) {
if (str == option) {
matchedValue = this.fromString(option);
hasMatched = true;
}
else if (option.indexOf(str) === 0) {
completions.push(this.fromString(option));
}
}, this);
if (hasMatched) {
return new Conversion(matchedValue);
}
else {
// This is something of a hack it basically allows us to tell the
// setting type to forget its last setting hack.
if (this.noMatch) {
this.noMatch();
}
if (completions.length > 0) {
var msg = 'Possibilities' +
(str.length === 0 ? '' : ' for \'' + str + '\'');
return new Conversion(null, Status.INCOMPLETE, msg, completions);
}
else {
var msg = 'Can\'t use \'' + str + '\'.';
return new Conversion(null, Status.INVALID, msg, completions);
}
}
};
SelectionType.prototype.fromString = function(str) {
return str;
};
SelectionType.prototype.decrement = function(value) {
var data = (typeof this.data === 'function') ? this.data() : this.data;
var index;
if (value == null) {
index = data.length - 1;
}
else {
var name = this.stringify(value);
var index = data.indexOf(name);
index = (index === 0 ? data.length - 1 : index - 1);
}
return this.fromString(data[index]);
};
SelectionType.prototype.increment = function(value) {
var data = (typeof this.data === 'function') ? this.data() : this.data;
var index;
if (value == null) {
index = 0;
}
else {
var name = this.stringify(value);
var index = data.indexOf(name);
index = (index === data.length - 1 ? 0 : index + 1);
}
return this.fromString(data[index]);
};
SelectionType.prototype.name = 'selection';
/**
* SelectionType is a base class for other types
*/
exports.SelectionType = SelectionType;
/**
* true/false values
*/
var bool = new SelectionType({
name: 'bool',
data: [ 'true', 'false' ],
stringify: function(value) {
return '' + value;
},
fromString: function(str) {
return str === 'true' ? true : false;
}
});
/**
* A we don't know right now, but hope to soon.
*/
function DeferredType(typeSpec) {
if (typeof typeSpec.defer !== 'function') {
throw new Error('Instances of DeferredType need typeSpec.defer to be a function that returns a type');
}
Object.keys(typeSpec).forEach(function(key) {
this[key] = typeSpec[key];
}, this);
};
DeferredType.prototype = new Type();
DeferredType.prototype.stringify = function(value) {
return this.defer().stringify(value);
};
DeferredType.prototype.parse = function(value) {
return this.defer().parse(value);
};
DeferredType.prototype.decrement = function(value) {
var deferred = this.defer();
return (deferred.decrement ? deferred.decrement(value) : undefined);
};
DeferredType.prototype.increment = function(value) {
var deferred = this.defer();
return (deferred.increment ? deferred.increment(value) : undefined);
};
DeferredType.prototype.name = 'deferred';
/**
* DeferredType is a base class for other types
*/
exports.DeferredType = DeferredType;
/**
* A set of objects of the same type
*/
function ArrayType(typeSpec) {
if (typeSpec instanceof Type) {
this.subtype = typeSpec;
}
else if (typeof typeSpec === 'string') {
this.subtype = types.getType(typeSpec);
if (this.subtype == null) {
throw new Error('Unknown array subtype: ' + typeSpec);
}
}
else {
throw new Error('Can\' handle array subtype');
}
};
ArrayType.prototype = new Type();
ArrayType.prototype.stringify = function(values) {
// TODO: Check for strings with spaces and add quotes
return values.join(' ');
};
ArrayType.prototype.parse = function(value) {
return this.defer().parse(value);
};
ArrayType.prototype.name = 'array';
/**
* Registration and de-registration.
*/
var isStarted = false;
exports.startup = function() {
if (isStarted) {
return;
}
isStarted = true;
types.registerType(text);
types.registerType(number);
types.registerType(bool);
types.registerType(SelectionType);
types.registerType(DeferredType);
types.registerType(ArrayType);
};
exports.shutdown = function() {
isStarted = false;
types.unregisterType(text);
types.unregisterType(number);
types.unregisterType(bool);
types.unregisterType(SelectionType);
types.unregisterType(DeferredType);
types.unregisterType(ArrayType);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/types', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* Some types can detect validity, that is to say they can distinguish between
* valid and invalid values.
* TODO: Change these constants to be numbers for more performance?
*/
var Status = {
/**
* The conversion process worked without any problem, and the value is
* valid. There are a number of failure states, so the best way to check
* for failure is (x !== Status.VALID)
*/
VALID: {
toString: function() { return 'VALID'; },
valueOf: function() { return 0; }
},
/**
* A conversion process failed, however it was noted that the string
* provided to 'parse()' could be VALID by the addition of more characters,
* so the typing may not be actually incorrect yet, just unfinished.
* @see Status.INVALID
*/
INCOMPLETE: {
toString: function() { return 'INCOMPLETE'; },
valueOf: function() { return 1; }
},
/**
* The conversion process did not work, the value should be null and a
* reason for failure should have been provided. In addition some completion
* values may be available.
* @see Status.INCOMPLETE
*/
INVALID: {
toString: function() { return 'INVALID'; },
valueOf: function() { return 2; }
},
/**
* A combined status is the worser of the provided statuses
*/
combine: function(statuses) {
var combined = Status.VALID;
for (var i = 0; i < statuses.length; i++) {
if (statuses[i].valueOf() > combined.valueOf()) {
combined = statuses[i];
}
}
return combined;
}
};
exports.Status = Status;
/**
* The type.parse() method returns a Conversion to inform the user about not
* only the result of a Conversion but also about what went wrong.
* We could use an exception, and throw if the conversion failed, but that
* seems to violate the idea that exceptions should be exceptional. Typos are
* not. Also in order to store both a status and a message we'd still need
* some sort of exception type...
*/
function Conversion(value, status, message, predictions) {
/**
* The result of the conversion process. Will be null if status != VALID
*/
this.value = value;
/**
* The status of the conversion.
* @see Status
*/
this.status = status || Status.VALID;
/**
* A message to go with the conversion. This could be present for any status
* including VALID in the case where we want to note a warning for example.
* I18N: On the one hand this nasty and un-internationalized, however with
* a command line it is hard to know where to start.
*/
this.message = message;
/**
* A array of strings which are the systems best guess at better inputs than
* the one presented.
* We generally expect there to be about 7 predictions (to match human list
* comprehension ability) however it is valid to provide up to about 20,
* or less. It is the job of the predictor to decide a smart cut-off.
* For example if there are 4 very good matches and 4 very poor ones,
* probably only the 4 very good matches should be presented.
*/
this.predictions = predictions || [];
}
exports.Conversion = Conversion;
/**
* Most of our types are 'static' e.g. there is only one type of 'text', however
* some types like 'selection' and 'deferred' are customizable. The basic
* Type type isn't useful, but does provide documentation about what types do.
*/
function Type() {
};
Type.prototype = {
/**
* Convert the given <tt>value</tt> to a string representation.
* Where possible, there should be round-tripping between values and their
* string representations.
*/
stringify: function(value) { throw new Error("not implemented"); },
/**
* Convert the given <tt>str</tt> to an instance of this type.
* Where possible, there should be round-tripping between values and their
* string representations.
* @return Conversion
*/
parse: function(str) { throw new Error("not implemented"); },
/**
* The plug-in system, and other things need to know what this type is
* called. The name alone is not enough to fully specify a type. Types like
* 'selection' and 'deferred' need extra data, however this function returns
* only the name, not the extra data.
* <p>In old bespin, equality was based on the name. This may turn out to be
* important in Ace too.
*/
name: undefined,
/**
* If there is some concept of a higher value, return it,
* otherwise return undefined.
*/
increment: function(value) {
return undefined;
},
/**
* If there is some concept of a lower value, return it,
* otherwise return undefined.
*/
decrement: function(value) {
return undefined;
},
/**
* There is interesting information (like predictions) in a conversion of
* nothing, the output of this can sometimes be customized.
* @return Conversion
*/
getDefault: function() {
return this.parse('');
}
};
exports.Type = Type;
/**
* Private registry of types
* Invariant: types[name] = type.name
*/
var types = {};
/**
* Add a new type to the list available to the system.
* You can pass 2 things to this function - either an instance of Type, in
* which case we return this instance when #getType() is called with a 'name'
* that matches type.name.
* Also you can pass in a constructor (i.e. function) in which case when
* #getType() is called with a 'name' that matches Type.prototype.name we will
* pass the typeSpec into this constructor. See #reconstituteType().
*/
exports.registerType = function(type) {
if (typeof type === 'object') {
if (type instanceof Type) {
if (!type.name) {
throw new Error('All registered types must have a name');
}
types[type.name] = type;
}
else {
throw new Error('Can\'t registerType using: ' + type);
}
}
else if (typeof type === 'function') {
if (!type.prototype.name) {
throw new Error('All registered types must have a name');
}
types[type.prototype.name] = type;
}
else {
throw new Error('Unknown type: ' + type);
}
};
exports.registerTypes = function registerTypes(types) {
Object.keys(types).forEach(function (name) {
var type = types[name];
type.name = name;
exports.registerType(type);
});
};
/**
* Remove a type from the list available to the system
*/
exports.deregisterType = function(type) {
delete types[type.name];
};
/**
* See description of #exports.registerType()
*/
function reconstituteType(name, typeSpec) {
if (name.substr(-2) === '[]') { // i.e. endsWith('[]')
var subtypeName = name.slice(0, -2);
return new types['array'](subtypeName);
}
var type = types[name];
if (typeof type === 'function') {
type = new type(typeSpec);
}
return type;
}
/**
* Find a type, previously registered using #registerType()
*/
exports.getType = function(typeSpec) {
if (typeof typeSpec === 'string') {
return reconstituteType(typeSpec);
}
if (typeof typeSpec === 'object') {
if (!typeSpec.name) {
throw new Error('Missing \'name\' member to typeSpec');
}
return reconstituteType(typeSpec.name, typeSpec);
}
throw new Error('Can\'t extract type from ' + typeSpec);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/types/command', ['require', 'exports', 'module' , 'pilot/canon', 'pilot/types/basic', 'pilot/types'], function(require, exports, module) {
var canon = require("pilot/canon");
var SelectionType = require("pilot/types/basic").SelectionType;
var types = require("pilot/types");
/**
* Select from the available commands
*/
var command = new SelectionType({
name: 'command',
data: function() {
return canon.getCommandNames();
},
stringify: function(command) {
return command.name;
},
fromString: function(str) {
return canon.getCommand(str);
}
});
/**
* Registration and de-registration.
*/
exports.startup = function() {
types.registerType(command);
};
exports.shutdown = function() {
types.unregisterType(command);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/canon', ['require', 'exports', 'module' , 'pilot/console', 'pilot/stacktrace', 'pilot/oop', 'pilot/useragent', 'pilot/keys', 'pilot/event_emitter', 'pilot/typecheck', 'pilot/catalog', 'pilot/types', 'pilot/lang'], function(require, exports, module) {
var console = require('pilot/console');
var Trace = require('pilot/stacktrace').Trace;
var oop = require('pilot/oop');
var useragent = require('pilot/useragent');
var keyUtil = require('pilot/keys');
var EventEmitter = require('pilot/event_emitter').EventEmitter;
var typecheck = require('pilot/typecheck');
var catalog = require('pilot/catalog');
var Status = require('pilot/types').Status;
var types = require('pilot/types');
var lang = require('pilot/lang');
/*
// TODO: this doesn't belong here - or maybe anywhere?
var dimensionsChangedExtensionSpec = {
name: 'dimensionsChanged',
description: 'A dimensionsChanged is a way to be notified of ' +
'changes to the dimension of Skywriter'
};
exports.startup = function(data, reason) {
catalog.addExtensionSpec(commandExtensionSpec);
};
exports.shutdown = function(data, reason) {
catalog.removeExtensionSpec(commandExtensionSpec);
};
*/
var commandExtensionSpec = {
name: 'command',
description: 'A command is a bit of functionality with optional ' +
'typed arguments which can do something small like moving ' +
'the cursor around the screen, or large like cloning a ' +
'project from VCS.',
indexOn: 'name'
};
exports.startup = function(data, reason) {
// TODO: this is probably all kinds of evil, but we need something working
catalog.addExtensionSpec(commandExtensionSpec);
};
exports.shutdown = function(data, reason) {
catalog.removeExtensionSpec(commandExtensionSpec);
};
/**
* Manage a list of commands in the current canon
*/
/**
* A Command is a discrete action optionally with a set of ways to customize
* how it happens. This is here for documentation purposes.
* TODO: Document better
*/
var thingCommand = {
name: 'thing',
description: 'thing is an example command',
params: [{
name: 'param1',
description: 'an example parameter',
type: 'text',
defaultValue: null
}],
exec: function(env, args, request) {
thing();
}
};
/**
* A lookup hash of our registered commands
*/
var commands = {};
/**
* A lookup has for command key bindings that use a string as sender.
*/
var commmandKeyBinding = {};
/**
* Array with command key bindings that use a function to determ the sender.
*/
var commandKeyBindingFunc = { };
function splitSafe(s, separator, limit, bLowerCase) {
return (bLowerCase && s.toLowerCase() || s)
.replace(/(?:^\s+|\n|\s+$)/g, "")
.split(new RegExp("[\\s ]*" + separator + "[\\s ]*", "g"), limit || 999);
}
function parseKeys(keys, val, ret) {
var key,
hashId = 0,
parts = splitSafe(keys, "\\-", null, true),
i = 0,
l = parts.length;
for (; i < l; ++i) {
if (keyUtil.KEY_MODS[parts[i]])
hashId = hashId | keyUtil.KEY_MODS[parts[i]];
else
key = parts[i] || "-"; //when empty, the splitSafe removed a '-'
}
if (ret == null) {
return {
key: key,
hashId: hashId
}
} else {
(ret[hashId] || (ret[hashId] = {}))[key] = val;
}
}
var platform = useragent.isMac ? "mac" : "win";
function buildKeyHash(command) {
var binding = command.bindKey,
key = binding[platform],
ckb = commmandKeyBinding,
ckbf = commandKeyBindingFunc
if (!binding.sender) {
throw new Error('All key bindings must have a sender');
}
if (!binding.mac && binding.mac !== null) {
throw new Error('All key bindings must have a mac key binding');
}
if (!binding.win && binding.win !== null) {
throw new Error('All key bindings must have a windows key binding');
}
if(!binding[platform]) {
// No keymapping for this platform.
return;
}
if (typeof binding.sender == 'string') {
var targets = splitSafe(binding.sender, "\\|", null, true);
targets.forEach(function(target) {
if (!ckb[target]) {
ckb[target] = { };
}
key.split("|").forEach(function(keyPart) {
parseKeys(keyPart, command, ckb[target]);
});
});
} else if (typecheck.isFunction(binding.sender)) {
var val = {
command: command,
sender: binding.sender
};
keyData = parseKeys(key);
if (!ckbf[keyData.hashId]) {
ckbf[keyData.hashId] = { };
}
if (!ckbf[keyData.hashId][keyData.key]) {
ckbf[keyData.hashId][keyData.key] = [ val ];
} else {
ckbf[keyData.hashId][keyData.key].push(val);
}
} else {
throw new Error('Key binding must have a sender that is a string or function');
}
}
function findKeyCommand(env, sender, hashId, textOrKey) {
// Convert keyCode to the string representation.
if (typecheck.isNumber(textOrKey)) {
textOrKey = keyUtil.keyCodeToString(textOrKey);
}
// Check bindings with functions as sender first.
var bindFuncs = (commandKeyBindingFunc[hashId] || {})[textOrKey] || [];
for (var i = 0; i < bindFuncs.length; i++) {
if (bindFuncs[i].sender(env, sender, hashId, textOrKey)) {
return bindFuncs[i].command;
}
}
var ckbr = commmandKeyBinding[sender];
return ckbr && ckbr[hashId] && ckbr[hashId][textOrKey];
}
function execKeyCommand(env, sender, hashId, textOrKey) {
var command = findKeyCommand(env, sender, hashId, textOrKey);
if (command) {
return exec(command, env, sender, { });
} else {
return false;
}
}
/**
* A sorted list of command names, we regularly want them in order, so pre-sort
*/
var commandNames = [];
/**
* This registration method isn't like other Ace registration methods because
* it doesn't return a decorated command because there is no functional
* decoration to be done.
* TODO: Are we sure that in the future there will be no such decoration?
*/
function addCommand(command) {
if (!command.name) {
throw new Error('All registered commands must have a name');
}
if (command.params == null) {
command.params = [];
}
if (!Array.isArray(command.params)) {
throw new Error('command.params must be an array in ' + command.name);
}
// Replace the type
command.params.forEach(function(param) {
if (!param.name) {
throw new Error('In ' + command.name + ': all params must have a name');
}
upgradeType(command.name, param);
}, this);
commands[command.name] = command;
if (command.bindKey) {
buildKeyHash(command);
}
commandNames.push(command.name);
commandNames.sort();
};
function upgradeType(name, param) {
var lookup = param.type;
param.type = types.getType(lookup);
if (param.type == null) {
throw new Error('In ' + name + '/' + param.name +
': can\'t find type for: ' + JSON.stringify(lookup));
}
}
function removeCommand(command) {
var name = (typeof command === 'string' ? command : command.name);
command = commands[name];
delete commands[name];
lang.arrayRemove(commandNames, name);
// exaustive search is a little bit brute force but since removeCommand is
// not a performance critical operation this should be OK
var ckb = commmandKeyBinding;
for (var k1 in ckb) {
for (var k2 in ckb[k1]) {
for (var k3 in ckb[k1][k2]) {
if (ckb[k1][k2][k3] == command)
delete ckb[k1][k2][k3];
}
}
}
var ckbf = commandKeyBindingFunc;
for (var k1 in ckbf) {
for (var k2 in ckbf[k1]) {
ckbf[k1][k2].forEach(function(cmd, i) {
if (cmd.command == command) {
ckbf[k1][k2].splice(i, 1);
}
})
}
}
};
function getCommand(name) {
return commands[name];
};
function getCommandNames() {
return commandNames;
};
/**
* Default ArgumentProvider that is used if no ArgumentProvider is provided
* by the command's sender.
*/
function defaultArgsProvider(request, callback) {
var args = request.args,
params = request.command.params;
for (var i = 0; i < params.length; i++) {
var param = params[i];
// If the parameter is already valid, then don't ask for it anymore.
if (request.getParamStatus(param) != Status.VALID ||
// Ask for optional parameters as well.
param.defaultValue === null)
{
var paramPrompt = param.description;
if (param.defaultValue === null) {
paramPrompt += " (optional)";
}
var value = prompt(paramPrompt, param.defaultValue || "");
// No value but required -> nope.
if (!value) {
callback();
return;
} else {
args[param.name] = value;
}
}
}
callback();
}
/**
* Entry point for keyboard accelerators or anything else that wants to execute
* a command. A new request object is created and a check performed, if the
* passed in arguments are VALID/INVALID or INCOMPLETE. If they are INCOMPLETE
* the ArgumentProvider on the sender is called or otherwise the default
* ArgumentProvider to get the still required arguments.
* If they are valid (or valid after the ArgumentProvider is done), the command
* is executed.
*
* @param command Either a command, or the name of one
* @param env Current environment to execute the command in
* @param sender String that should be the same as the senderObject stored on
* the environment in env[sender]
* @param args Arguments for the command
* @param typed (Optional)
*/
function exec(command, env, sender, args, typed) {
if (typeof command === 'string') {
command = commands[command];
}
if (!command) {
// TODO: Should we complain more than returning false?
return false;
}
var request = new Request({
sender: sender,
command: command,
args: args || {},
typed: typed
});
/**
* Executes the command and ensures request.done is called on the request in
* case it's not marked to be done already or async.
*/
function execute() {
command.exec(env, request.args, request);
// If the request isn't asnync and isn't done, then make it done.
if (!request.isAsync && !request.isDone) {
request.done();
}
}
if (request.getStatus() == Status.INVALID) {
console.error("Canon.exec: Invalid parameter(s) passed to " +
command.name);
return false;
}
// If the request isn't complete yet, try to complete it.
else if (request.getStatus() == Status.INCOMPLETE) {
// Check if the sender has a ArgsProvider, otherwise use the default
// build in one.
var argsProvider;
var senderObj = env[sender];
if (!senderObj || !senderObj.getArgsProvider ||
!(argsProvider = senderObj.getArgsProvider()))
{
argsProvider = defaultArgsProvider;
}
// Ask the paramProvider to complete the request.
argsProvider(request, function() {
if (request.getStatus() == Status.VALID) {
execute();
}
});
return true;
} else {
execute();
return true;
}
};
exports.removeCommand = removeCommand;
exports.addCommand = addCommand;
exports.getCommand = getCommand;
exports.getCommandNames = getCommandNames;
exports.findKeyCommand = findKeyCommand;
exports.exec = exec;
exports.execKeyCommand = execKeyCommand;
exports.upgradeType = upgradeType;
/**
* We publish a 'output' event whenever new command begins output
* TODO: make this more obvious
*/
oop.implement(exports, EventEmitter);
/**
* Current requirements are around displaying the command line, and provision
* of a 'history' command and cursor up|down navigation of history.
* <p>Future requirements could include:
* <ul>
* <li>Multiple command lines
* <li>The ability to recall key presses (i.e. requests with no output) which
* will likely be needed for macro recording or similar
* <li>The ability to store the command history either on the server or in the
* browser local storage.
* </ul>
* <p>The execute() command doesn't really live here, except as part of that
* last future requirement, and because it doesn't really have anywhere else to
* live.
*/
/**
* The array of requests that wish to announce their presence
*/
var requests = [];
/**
* How many requests do we store?
*/
var maxRequestLength = 100;
/**
* To create an invocation, you need to do something like this (all the ctor
* args are optional):
* <pre>
* var request = new Request({
* command: command,
* args: args,
* typed: typed
* });
* </pre>
* @constructor
*/
function Request(options) {
options = options || {};
// Will be used in the keyboard case and the cli case
this.command = options.command;
// Will be used only in the cli case
this.args = options.args;
this.typed = options.typed;
// Have we been initialized?
this._begunOutput = false;
this.start = new Date();
this.end = null;
this.completed = false;
this.error = false;
};
oop.implement(Request.prototype, EventEmitter);
/**
* Return the status of a parameter on the request object.
*/
Request.prototype.getParamStatus = function(param) {
var args = this.args || {};
// Check if there is already a value for this parameter.
if (param.name in args) {
// If there is no value set and then the value is VALID if it's not
// required or INCOMPLETE if not set yet.
if (args[param.name] == null) {
if (param.defaultValue === null) {
return Status.VALID;
} else {
return Status.INCOMPLETE;
}
}
// Check if the parameter value is valid.
var reply,
// The passed in value when parsing a type is a string.
argsValue = args[param.name].toString();
// Type.parse can throw errors.
try {
reply = param.type.parse(argsValue);
} catch (e) {
return Status.INVALID;
}
if (reply.status != Status.VALID) {
return reply.status;
}
}
// Check if the param is marked as required.
else if (param.defaultValue === undefined) {
// The parameter is not set on the args object but it's required,
// which means, things are invalid.
return Status.INCOMPLETE;
}
return Status.VALID;
}
/**
* Return the status of a parameter name on the request object.
*/
Request.prototype.getParamNameStatus = function(paramName) {
var params = this.command.params || [];
for (var i = 0; i < params.length; i++) {
if (params[i].name == paramName) {
return this.getParamStatus(params[i]);
}
}
throw "Parameter '" + paramName +
"' not defined on command '" + this.command.name + "'";
}
/**
* Checks if all required arguments are set on the request such that it can
* get executed.
*/
Request.prototype.getStatus = function() {
var args = this.args || {},
params = this.command.params;
// If there are not parameters, then it's valid.
if (!params || params.length == 0) {
return Status.VALID;
}
var status = [];
for (var i = 0; i < params.length; i++) {
status.push(this.getParamStatus(params[i]));
}
return Status.combine(status);
}
/**
* Lazy init to register with the history should only be done on output.
* init() is expensive, and won't be used in the majority of cases
*/
Request.prototype._beginOutput = function() {
this._begunOutput = true;
this.outputs = [];
requests.push(this);
// This could probably be optimized with some maths, but 99.99% of the
// time we will only be off by one, and I'm feeling lazy.
while (requests.length > maxRequestLength) {
requests.shiftObject();
}
exports._dispatchEvent('output', { requests: requests, request: this });
};
/**
* Sugar for:
* <pre>request.error = true; request.done(output);</pre>
*/
Request.prototype.doneWithError = function(content) {
this.error = true;
this.done(content);
};
/**
* Declares that this function will not be automatically done when
* the command exits
*/
Request.prototype.async = function() {
this.isAsync = true;
if (!this._begunOutput) {
this._beginOutput();
}
};
/**
* Complete the currently executing command with successful output.
* @param output Either DOM node, an SproutCore element or something that
* can be used in the content of a DIV to create a DOM node.
*/
Request.prototype.output = function(content) {
if (!this._begunOutput) {
this._beginOutput();
}
if (typeof content !== 'string' && !(content instanceof Node)) {
content = content.toString();
}
this.outputs.push(content);
this.isDone = true;
this._dispatchEvent('output', {});
return this;
};
/**
* All commands that do output must call this to indicate that the command
* has finished execution.
*/
Request.prototype.done = function(content) {
this.completed = true;
this.end = new Date();
this.duration = this.end.getTime() - this.start.getTime();
if (content) {
this.output(content);
}
// Ensure to finish the request only once.
if (!this.isDone) {
this.isDone = true;
this._dispatchEvent('output', {});
}
};
exports.Request = Request;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Patrick Walton (pwalton@mozilla.com)
* Julian Viereck (jviereck@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/console', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* This object represents a "safe console" object that forwards debugging
* messages appropriately without creating a dependency on Firebug in Firefox.
*/
var noop = function() {};
// These are the functions that are available in Chrome 4/5, Safari 4
// and Firefox 3.6. Don't add to this list without checking browser support
var NAMES = [
"assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd",
"info", "log", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"
];
if (typeof(window) === 'undefined') {
// We're in a web worker. Forward to the main thread so the messages
// will show up.
NAMES.forEach(function(name) {
exports[name] = function() {
var args = Array.prototype.slice.call(arguments);
var msg = { op: 'log', method: name, args: args };
postMessage(JSON.stringify(msg));
};
});
} else {
// For each of the console functions, copy them if they exist, stub if not
NAMES.forEach(function(name) {
if (window.console && window.console[name]) {
exports[name] = Function.prototype.bind.call(window.console[name], window.console);
} else {
exports[name] = noop;
}
});
}
});
define('pilot/stacktrace', ['require', 'exports', 'module' , 'pilot/useragent', 'pilot/console'], function(require, exports, module) {
var ua = require("pilot/useragent");
var console = require('pilot/console');
// Changed to suit the specific needs of running within Skywriter
// Domain Public by Eric Wendelin http://eriwen.com/ (2008)
// Luke Smith http://lucassmith.name/ (2008)
// Loic Dachary <loic@dachary.org> (2008)
// Johan Euphrosine <proppy@aminche.com> (2008)
// Øyvind Sean Kinsey http://kinsey.no/blog
//
// Information and discussions
// http://jspoker.pokersource.info/skin/test-printstacktrace.html
// http://eriwen.com/javascript/js-stack-trace/
// http://eriwen.com/javascript/stacktrace-update/
// http://pastie.org/253058
// http://browsershots.org/http://jspoker.pokersource.info/skin/test-printstacktrace.html
//
//
// guessFunctionNameFromLines comes from firebug
//
// Software License Agreement (BSD License)
//
// Copyright (c) 2007, Parakey Inc.
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the
// following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// * Neither the name of Parakey Inc. nor the names of its
// contributors may be used to endorse or promote products
// derived from this software without specific prior
// written permission of Parakey Inc.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Different browsers create stack traces in different ways.
* <strike>Feature</strike> Browser detection baby ;).
*/
var mode = (function() {
// We use SC's browser detection here to avoid the "break on error"
// functionality provided by Firebug. Firebug tries to do the right
// thing here and break, but it happens every time you load the page.
// bug 554105
if (ua.isGecko) {
return 'firefox';
} else if (ua.isOpera) {
return 'opera';
} else {
return 'other';
}
// SC doesn't do any detection of Chrome at this time.
// this is the original feature detection code that is used as a
// fallback.
try {
(0)();
} catch (e) {
if (e.arguments) {
return 'chrome';
}
if (e.stack) {
return 'firefox';
}
if (window.opera && !('stacktrace' in e)) { //Opera 9-
return 'opera';
}
}
return 'other';
})();
/**
*
*/
function stringifyArguments(args) {
for (var i = 0; i < args.length; ++i) {
var argument = args[i];
if (typeof argument == 'object') {
args[i] = '#object';
} else if (typeof argument == 'function') {
args[i] = '#function';
} else if (typeof argument == 'string') {
args[i] = '"' + argument + '"';
}
}
return args.join(',');
}
/**
* Extract a stack trace from the format emitted by each browser.
*/
var decoders = {
chrome: function(e) {
var stack = e.stack;
if (!stack) {
console.log(e);
return [];
}
return stack.replace(/^.*?\n/, '').
replace(/^.*?\n/, '').
replace(/^.*?\n/, '').
replace(/^[^\(]+?[\n$]/gm, '').
replace(/^\s+at\s+/gm, '').
replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@').
split('\n');
},
firefox: function(e) {
var stack = e.stack;
if (!stack) {
console.log(e);
return [];
}
// stack = stack.replace(/^.*?\n/, '');
stack = stack.replace(/(?:\n@:0)?\s+$/m, '');
stack = stack.replace(/^\(/gm, '{anonymous}(');
return stack.split('\n');
},
// Opera 7.x and 8.x only!
opera: function(e) {
var lines = e.message.split('\n'), ANON = '{anonymous}',
lineRE = /Line\s+(\d+).*?script\s+(http\S+)(?:.*?in\s+function\s+(\S+))?/i, i, j, len;
for (i = 4, j = 0, len = lines.length; i < len; i += 2) {
if (lineRE.test(lines[i])) {
lines[j++] = (RegExp.$3 ? RegExp.$3 + '()@' + RegExp.$2 + RegExp.$1 : ANON + '()@' + RegExp.$2 + ':' + RegExp.$1) +
' -- ' +
lines[i + 1].replace(/^\s+/, '');
}
}
lines.splice(j, lines.length - j);
return lines;
},
// Safari, Opera 9+, IE, and others
other: function(curr) {
var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], j = 0, fn, args;
var maxStackSize = 10;
while (curr && stack.length < maxStackSize) {
fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;
args = Array.prototype.slice.call(curr['arguments']);
stack[j++] = fn + '(' + stringifyArguments(args) + ')';
//Opera bug: if curr.caller does not exist, Opera returns curr (WTF)
if (curr === curr.caller && window.opera) {
//TODO: check for same arguments if possible
break;
}
curr = curr.caller;
}
return stack;
}
};
/**
*
*/
function NameGuesser() {
}
NameGuesser.prototype = {
sourceCache: {},
ajax: function(url) {
var req = this.createXMLHTTPObject();
if (!req) {
return;
}
req.open('GET', url, false);
req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
req.send('');
return req.responseText;
},
createXMLHTTPObject: function() {
// Try XHR methods in order and store XHR factory
var xmlhttp, XMLHttpFactories = [
function() {
return new XMLHttpRequest();
}, function() {
return new ActiveXObject('Msxml2.XMLHTTP');
}, function() {
return new ActiveXObject('Msxml3.XMLHTTP');
}, function() {
return new ActiveXObject('Microsoft.XMLHTTP');
}
];
for (var i = 0; i < XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
// Use memoization to cache the factory
this.createXMLHTTPObject = XMLHttpFactories[i];
return xmlhttp;
} catch (e) {}
}
},
getSource: function(url) {
if (!(url in this.sourceCache)) {
this.sourceCache[url] = this.ajax(url).split('\n');
}
return this.sourceCache[url];
},
guessFunctions: function(stack) {
for (var i = 0; i < stack.length; ++i) {
var reStack = /{anonymous}\(.*\)@(\w+:\/\/([-\w\.]+)+(:\d+)?[^:]+):(\d+):?(\d+)?/;
var frame = stack[i], m = reStack.exec(frame);
if (m) {
var file = m[1], lineno = m[4]; //m[7] is character position in Chrome
if (file && lineno) {
var functionName = this.guessFunctionName(file, lineno);
stack[i] = frame.replace('{anonymous}', functionName);
}
}
}
return stack;
},
guessFunctionName: function(url, lineNo) {
try {
return this.guessFunctionNameFromLines(lineNo, this.getSource(url));
} catch (e) {
return 'getSource failed with url: ' + url + ', exception: ' + e.toString();
}
},
guessFunctionNameFromLines: function(lineNo, source) {
var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/;
var reGuessFunction = /['"]?([0-9A-Za-z_]+)['"]?\s*[:=]\s*(function|eval|new Function)/;
// Walk backwards from the first line in the function until we find the line which
// matches the pattern above, which is the function definition
var line = '', maxLines = 10;
for (var i = 0; i < maxLines; ++i) {
line = source[lineNo - i] + line;
if (line !== undefined) {
var m = reGuessFunction.exec(line);
if (m) {
return m[1];
}
else {
m = reFunctionArgNames.exec(line);
}
if (m && m[1]) {
return m[1];
}
}
}
return '(?)';
}
};
var guesser = new NameGuesser();
var frameIgnorePatterns = [
/http:\/\/localhost:4020\/sproutcore.js:/
];
exports.ignoreFramesMatching = function(regex) {
frameIgnorePatterns.push(regex);
};
/**
* Create a stack trace from an exception
* @param ex {Error} The error to create a stacktrace from (optional)
* @param guess {Boolean} If we should try to resolve the names of anonymous functions
*/
exports.Trace = function Trace(ex, guess) {
this._ex = ex;
this._stack = decoders[mode](ex);
if (guess) {
this._stack = guesser.guessFunctions(this._stack);
}
};
/**
* Log to the console a number of lines (default all of them)
* @param lines {number} Maximum number of lines to wrote to console
*/
exports.Trace.prototype.log = function(lines) {
if (lines <= 0) {
// You aren't going to have more lines in your stack trace than this
// and it still fits in a 32bit integer
lines = 999999999;
}
var printed = 0;
for (var i = 0; i < this._stack.length && printed < lines; i++) {
var frame = this._stack[i];
var display = true;
frameIgnorePatterns.forEach(function(regex) {
if (regex.test(frame)) {
display = false;
}
});
if (display) {
console.debug(frame);
printed++;
}
}
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/useragent', ['require', 'exports', 'module' ], function(require, exports, module) {
var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase();
var ua = navigator.userAgent;
var av = navigator.appVersion;
/** Is the user using a browser that identifies itself as Windows */
exports.isWin = (os == "win");
/** Is the user using a browser that identifies itself as Mac OS */
exports.isMac = (os == "mac");
/** Is the user using a browser that identifies itself as Linux */
exports.isLinux = (os == "linux");
exports.isIE = ! + "\v1";
/** Is this Firefox or related? */
exports.isGecko = exports.isMozilla = window.controllers && window.navigator.product === "Gecko";
/** oldGecko == rev < 2.0 **/
exports.isOldGecko = exports.isGecko && /rv\:1/.test(navigator.userAgent);
/** Is this Opera */
exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]";
/** Is the user using a browser that identifies itself as WebKit */
exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined;
exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined;
exports.isAIR = ua.indexOf("AdobeAIR") >= 0;
exports.isIPad = ua.indexOf("iPad") >= 0;
/**
* I hate doing this, but we need some way to determine if the user is on a Mac
* The reason is that users have different expectations of their key combinations.
*
* Take copy as an example, Mac people expect to use CMD or APPLE + C
* Windows folks expect to use CTRL + C
*/
exports.OS = {
LINUX: 'LINUX',
MAC: 'MAC',
WINDOWS: 'WINDOWS'
};
/**
* Return an exports.OS constant
*/
exports.getOS = function() {
if (exports.isMac) {
return exports.OS['MAC'];
} else if (exports.isLinux) {
return exports.OS['LINUX'];
} else {
return exports.OS['WINDOWS'];
}
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/oop', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.inherits = (function() {
var tempCtor = function() {};
return function(ctor, superCtor) {
tempCtor.prototype = superCtor.prototype;
ctor.super_ = superCtor.prototype;
ctor.prototype = new tempCtor();
ctor.prototype.constructor = ctor;
}
}());
exports.mixin = function(obj, mixin) {
for (var key in mixin) {
obj[key] = mixin[key];
}
};
exports.implement = function(proto, mixin) {
exports.mixin(proto, mixin);
};
});
/*! @license
==========================================================================
SproutCore -- JavaScript Application Framework
copyright 2006-2009, Sprout Systems Inc., Apple Inc. and contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
SproutCore and the SproutCore logo are trademarks of Sprout Systems, Inc.
For more information about SproutCore, visit http://www.sproutcore.com
==========================================================================
@license */
// Most of the following code is taken from SproutCore with a few changes.
define('pilot/keys', ['require', 'exports', 'module' , 'pilot/oop'], function(require, exports, module) {
var oop = require("pilot/oop");
/**
* Helper functions and hashes for key handling.
*/
var Keys = (function() {
var ret = {
MODIFIER_KEYS: {
16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta'
},
KEY_MODS: {
"ctrl": 1, "alt": 2, "option" : 2,
"shift": 4, "meta": 8, "command": 8
},
FUNCTION_KEYS : {
8 : "Backspace",
9 : "Tab",
13 : "Return",
19 : "Pause",
27 : "Esc",
32 : "Space",
33 : "PageUp",
34 : "PageDown",
35 : "End",
36 : "Home",
37 : "Left",
38 : "Up",
39 : "Right",
40 : "Down",
44 : "Print",
45 : "Insert",
46 : "Delete",
112: "F1",
113: "F2",
114: "F3",
115: "F4",
116: "F5",
117: "F6",
118: "F7",
119: "F8",
120: "F9",
121: "F10",
122: "F11",
123: "F12",
144: "Numlock",
145: "Scrolllock"
},
PRINTABLE_KEYS: {
32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5',
54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a',
66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h',
73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o',
80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v',
87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.',
188: ',', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\',
221: ']', 222: '\"'
}
};
// A reverse map of FUNCTION_KEYS
for (i in ret.FUNCTION_KEYS) {
var name = ret.FUNCTION_KEYS[i].toUpperCase();
ret[name] = parseInt(i, 10);
}
// Add the MODIFIER_KEYS, FUNCTION_KEYS and PRINTABLE_KEYS to the KEY
// variables as well.
oop.mixin(ret, ret.MODIFIER_KEYS);
oop.mixin(ret, ret.PRINTABLE_KEYS);
oop.mixin(ret, ret.FUNCTION_KEYS);
return ret;
})();
oop.mixin(exports, Keys);
exports.keyCodeToString = function(keyCode) {
return (Keys[keyCode] || String.fromCharCode(keyCode)).toLowerCase();
}
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) {
var EventEmitter = {};
EventEmitter._emit =
EventEmitter._dispatchEvent = function(eventName, e) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners || !listeners.length) return;
var e = e || {};
e.type = eventName;
for (var i=0; i<listeners.length; i++) {
listeners[i](e);
}
};
EventEmitter.on =
EventEmitter.addEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners) {
var listeners = this._eventRegistry[eventName] = [];
}
if (listeners.indexOf(callback) == -1) {
listeners.push(callback);
}
};
EventEmitter.removeListener =
EventEmitter.removeEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners) {
return;
}
var index = listeners.indexOf(callback);
if (index !== -1) {
listeners.splice(index, 1);
}
};
EventEmitter.removeAllListeners = function(eventName) {
if (this._eventRegistry) this._eventRegistry[eventName] = [];
}
exports.EventEmitter = EventEmitter;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/typecheck', ['require', 'exports', 'module' ], function(require, exports, module) {
var objectToString = Object.prototype.toString;
/**
* Return true if it is a String
*/
exports.isString = function(it) {
return it && objectToString.call(it) === "[object String]";
};
/**
* Returns true if it is a Boolean.
*/
exports.isBoolean = function(it) {
return it && objectToString.call(it) === "[object Boolean]";
};
/**
* Returns true if it is a Number.
*/
exports.isNumber = function(it) {
return it && objectToString.call(it) === "[object Number]" && isFinite(it);
};
/**
* Hack copied from dojo.
*/
exports.isObject = function(it) {
return it !== undefined &&
(it === null || typeof it == "object" ||
Array.isArray(it) || exports.isFunction(it));
};
/**
* Is the passed object a function?
* From dojo.isFunction()
*/
exports.isFunction = function(it) {
return it && objectToString.call(it) === "[object Function]";
};
});/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Julian Viereck (jviereck@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/catalog', ['require', 'exports', 'module' ], function(require, exports, module) {
var extensionSpecs = {};
exports.addExtensionSpec = function(extensionSpec) {
extensionSpecs[extensionSpec.name] = extensionSpec;
};
exports.removeExtensionSpec = function(extensionSpec) {
if (typeof extensionSpec === "string") {
delete extensionSpecs[extensionSpec];
}
else {
delete extensionSpecs[extensionSpec.name];
}
};
exports.getExtensionSpec = function(name) {
return extensionSpecs[name];
};
exports.getExtensionSpecs = function() {
return Object.keys(extensionSpecs);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/lang', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.stringReverse = function(string) {
return string.split("").reverse().join("");
};
exports.stringRepeat = function (string, count) {
return new Array(count + 1).join(string);
};
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
exports.stringTrimLeft = function (string) {
return string.replace(trimBeginRegexp, '')
};
exports.stringTrimRight = function (string) {
return string.replace(trimEndRegexp, '');
};
exports.copyObject = function(obj) {
var copy = {};
for (var key in obj) {
copy[key] = obj[key];
}
return copy;
};
exports.copyArray = function(array){
var copy = [];
for (i=0, l=array.length; i<l; i++) {
if (array[i] && typeof array[i] == "object")
copy[i] = this.copyObject( array[i] );
else
copy[i] = array[i]
}
return copy;
};
exports.deepCopy = function (obj) {
if (typeof obj != "object") {
return obj;
}
var copy = obj.constructor();
for (var key in obj) {
if (typeof obj[key] == "object") {
copy[key] = this.deepCopy(obj[key]);
} else {
copy[key] = obj[key];
}
}
return copy;
}
exports.arrayToMap = function(arr) {
var map = {};
for (var i=0; i<arr.length; i++) {
map[arr[i]] = 1;
}
return map;
};
/**
* splice out of 'array' anything that === 'value'
*/
exports.arrayRemove = function(array, value) {
for (var i = 0; i <= array.length; i++) {
if (value === array[i]) {
array.splice(i, 1);
}
}
};
exports.escapeRegExp = function(str) {
return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
};
exports.deferredCall = function(fcn) {
var timer = null;
var callback = function() {
timer = null;
fcn();
};
var deferred = function(timeout) {
if (!timer) {
timer = setTimeout(callback, timeout || 0);
}
return deferred;
}
deferred.schedule = deferred;
deferred.call = function() {
this.cancel();
fcn();
return deferred;
};
deferred.cancel = function() {
clearTimeout(timer);
timer = null;
return deferred;
};
return deferred;
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/types/settings', ['require', 'exports', 'module' , 'pilot/types/basic', 'pilot/types', 'pilot/settings'], function(require, exports, module) {
var SelectionType = require('pilot/types/basic').SelectionType;
var DeferredType = require('pilot/types/basic').DeferredType;
var types = require('pilot/types');
var settings = require('pilot/settings').settings;
/**
* EVIL: This relies on us using settingValue in the same event as setting
* The alternative is to have some central place where we store the current
* command line, but this might be a lesser evil for now.
*/
var lastSetting;
/**
* Select from the available settings
*/
var setting = new SelectionType({
name: 'setting',
data: function() {
return env.settings.getSettingNames();
},
stringify: function(setting) {
lastSetting = setting;
return setting.name;
},
fromString: function(str) {
lastSetting = settings.getSetting(str);
return lastSetting;
},
noMatch: function() {
lastSetting = null;
}
});
/**
* Something of a hack to allow the set command to give a clearer definition
* of the type to the command line.
*/
var settingValue = new DeferredType({
name: 'settingValue',
defer: function() {
if (lastSetting) {
return lastSetting.type;
}
else {
return types.getType('text');
}
},
/**
* Promote the current value in any list of predictions, and add it if
* there are none.
*/
getDefault: function() {
var conversion = this.parse('');
if (lastSetting) {
var current = lastSetting.get();
if (conversion.predictions.length === 0) {
conversion.predictions.push(current);
}
else {
// Remove current from predictions
var removed = false;
while (true) {
var index = conversion.predictions.indexOf(current);
if (index === -1) {
break;
}
conversion.predictions.splice(index, 1);
removed = true;
}
// If the current value wasn't something we would predict, leave it
if (removed) {
conversion.predictions.push(current);
}
}
}
return conversion;
}
});
var env;
/**
* Registration and de-registration.
*/
exports.startup = function(data, reason) {
// TODO: this is probably all kinds of evil, but we need something working
env = data.env;
types.registerType(setting);
types.registerType(settingValue);
};
exports.shutdown = function(data, reason) {
types.unregisterType(setting);
types.unregisterType(settingValue);
};
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Julian Viereck (jviereck@mozilla.com)
* Kevin Dangoor (kdangoor@mozilla.com)
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/settings', ['require', 'exports', 'module' , 'pilot/console', 'pilot/oop', 'pilot/types', 'pilot/event_emitter', 'pilot/catalog'], function(require, exports, module) {
/**
* This plug-in manages settings.
*/
var console = require('pilot/console');
var oop = require('pilot/oop');
var types = require('pilot/types');
var EventEmitter = require('pilot/event_emitter').EventEmitter;
var catalog = require('pilot/catalog');
var settingExtensionSpec = {
name: 'setting',
description: 'A setting is something that the application offers as a ' +
'way to customize how it works',
register: 'env.settings.addSetting',
indexOn: 'name'
};
exports.startup = function(data, reason) {
catalog.addExtensionSpec(settingExtensionSpec);
};
exports.shutdown = function(data, reason) {
catalog.removeExtensionSpec(settingExtensionSpec);
};
/**
* Create a new setting.
* @param settingSpec An object literal that looks like this:
* {
* name: 'thing',
* description: 'Thing is an example setting',
* type: 'string',
* defaultValue: 'something'
* }
*/
function Setting(settingSpec, settings) {
this._settings = settings;
Object.keys(settingSpec).forEach(function(key) {
this[key] = settingSpec[key];
}, this);
this.type = types.getType(this.type);
if (this.type == null) {
throw new Error('In ' + this.name +
': can\'t find type for: ' + JSON.stringify(settingSpec.type));
}
if (!this.name) {
throw new Error('Setting.name == undefined. Ignoring.', this);
}
if (!this.defaultValue === undefined) {
throw new Error('Setting.defaultValue == undefined', this);
}
if (this.onChange) {
this.on('change', this.onChange.bind(this))
}
this.set(this.defaultValue);
}
Setting.prototype = {
get: function() {
return this.value;
},
set: function(value) {
if (this.value === value) {
return;
}
this.value = value;
if (this._settings.persister) {
this._settings.persister.persistValue(this._settings, this.name, value);
}
this._dispatchEvent('change', { setting: this, value: value });
},
/**
* Reset the value of the <code>key</code> setting to it's default
*/
resetValue: function() {
this.set(this.defaultValue);
},
toString: function () {
return this.name;
}
};
oop.implement(Setting.prototype, EventEmitter);
/**
* A base class for all the various methods of storing settings.
* <p>Usage:
* <pre>
* // Create manually, or require 'settings' from the container.
* // This is the manual version:
* var settings = plugins.catalog.getObject('settings');
* // Add a new setting
* settings.addSetting({ name:'foo', ... });
* // Display the default value
* alert(settings.get('foo'));
* // Alter the value, which also publishes the change etc.
* settings.set('foo', 'bar');
* // Reset the value to the default
* settings.resetValue('foo');
* </pre>
* @constructor
*/
function Settings(persister) {
// Storage for deactivated values
this._deactivated = {};
// Storage for the active settings
this._settings = {};
// We often want sorted setting names. Cache
this._settingNames = [];
if (persister) {
this.setPersister(persister);
}
};
Settings.prototype = {
/**
* Function to add to the list of available settings.
* <p>Example usage:
* <pre>
* var settings = plugins.catalog.getObject('settings');
* settings.addSetting({
* name: 'tabsize', // For use in settings.get('X')
* type: 'number', // To allow value checking.
* defaultValue: 4 // Default value for use when none is directly set
* });
* </pre>
* @param {object} settingSpec Object containing name/type/defaultValue members.
*/
addSetting: function(settingSpec) {
var setting = new Setting(settingSpec, this);
this._settings[setting.name] = setting;
this._settingNames.push(setting.name);
this._settingNames.sort();
},
addSettings: function addSettings(settings) {
Object.keys(settings).forEach(function (name) {
var setting = settings[name];
if (!('name' in setting)) setting.name = name;
this.addSetting(setting);
}, this);
},
removeSetting: function(setting) {
var name = (typeof setting === 'string' ? setting : setting.name);
setting = this._settings[name];
delete this._settings[name];
util.arrayRemove(this._settingNames, name);
settings.removeAllListeners('change');
},
removeSettings: function removeSettings(settings) {
Object.keys(settings).forEach(function(name) {
var setting = settings[name];
if (!('name' in setting)) setting.name = name;
this.removeSettings(setting);
}, this);
},
getSettingNames: function() {
return this._settingNames;
},
getSetting: function(name) {
return this._settings[name];
},
/**
* A Persister is able to store settings. It is an object that defines
* two functions:
* loadInitialValues(settings) and persistValue(settings, key, value).
*/
setPersister: function(persister) {
this._persister = persister;
if (persister) {
persister.loadInitialValues(this);
}
},
resetAll: function() {
this.getSettingNames().forEach(function(key) {
this.resetValue(key);
}, this);
},
/**
* Retrieve a list of the known settings and their values
*/
_list: function() {
var reply = [];
this.getSettingNames().forEach(function(setting) {
reply.push({
'key': setting,
'value': this.getSetting(setting).get()
});
}, this);
return reply;
},
/**
* Prime the local cache with the defaults.
*/
_loadDefaultValues: function() {
this._loadFromObject(this._getDefaultValues());
},
/**
* Utility to load settings from an object
*/
_loadFromObject: function(data) {
// We iterate over data rather than keys so we don't forget values
// which don't have a setting yet.
for (var key in data) {
if (data.hasOwnProperty(key)) {
var setting = this._settings[key];
if (setting) {
var value = setting.type.parse(data[key]);
this.set(key, value);
} else {
this.set(key, data[key]);
}
}
}
},
/**
* Utility to grab all the settings and export them into an object
*/
_saveToObject: function() {
return this.getSettingNames().map(function(key) {
return this._settings[key].type.stringify(this.get(key));
}.bind(this));
},
/**
* The default initial settings
*/
_getDefaultValues: function() {
return this.getSettingNames().map(function(key) {
return this._settings[key].spec.defaultValue;
}.bind(this));
}
};
exports.settings = new Settings();
/**
* Save the settings in a cookie
* This code has not been tested since reboot
* @constructor
*/
function CookiePersister() {
};
CookiePersister.prototype = {
loadInitialValues: function(settings) {
settings._loadDefaultValues();
var data = cookie.get('settings');
settings._loadFromObject(JSON.parse(data));
},
persistValue: function(settings, key, value) {
try {
var stringData = JSON.stringify(settings._saveToObject());
cookie.set('settings', stringData);
} catch (ex) {
console.error('Unable to JSONify the settings! ' + ex);
return;
}
}
};
exports.CookiePersister = CookiePersister;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Skywriter Team (skywriter@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/commands/settings', ['require', 'exports', 'module' , 'pilot/canon'], function(require, exports, module) {
var setCommandSpec = {
name: 'set',
params: [
{
name: 'setting',
type: 'setting',
description: 'The name of the setting to display or alter',
defaultValue: null
},
{
name: 'value',
type: 'settingValue',
description: 'The new value for the chosen setting',
defaultValue: null
}
],
description: 'define and show settings',
exec: function(env, args, request) {
var html;
if (!args.setting) {
// 'set' by itself lists all the settings
var names = env.settings.getSettingNames();
html = '';
// first sort the settingsList based on the name
names.sort(function(name1, name2) {
return name1.localeCompare(name2);
});
names.forEach(function(name) {
var setting = env.settings.getSetting(name);
var url = 'https://wiki.mozilla.org/Labs/Skywriter/Settings#' +
setting.name;
html += '<a class="setting" href="' + url +
'" title="View external documentation on setting: ' +
setting.name +
'" target="_blank">' +
setting.name +
'</a> = ' +
setting.value +
'<br/>';
});
} else {
// set with only a setting, shows the value for that setting
if (args.value === undefined) {
html = '<strong>' + setting.name + '</strong> = ' +
setting.get();
} else {
// Actually change the setting
args.setting.set(args.value);
html = 'Setting: <strong>' + args.setting.name + '</strong> = ' +
args.setting.get();
}
}
request.done(html);
}
};
var unsetCommandSpec = {
name: 'unset',
params: [
{
name: 'setting',
type: 'setting',
description: 'The name of the setting to return to defaults'
}
],
description: 'unset a setting entirely',
exec: function(env, args, request) {
var setting = env.settings.get(args.setting);
if (!setting) {
request.doneWithError('No setting with the name <strong>' +
args.setting + '</strong>.');
return;
}
setting.reset();
request.done('Reset ' + setting.name + ' to default: ' +
env.settings.get(args.setting));
}
};
var canon = require('pilot/canon');
exports.startup = function(data, reason) {
canon.addCommand(setCommandSpec);
canon.addCommand(unsetCommandSpec);
};
exports.shutdown = function(data, reason) {
canon.removeCommand(setCommandSpec);
canon.removeCommand(unsetCommandSpec);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Skywriter Team (skywriter@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/commands/basic', ['require', 'exports', 'module' , 'pilot/typecheck', 'pilot/canon'], function(require, exports, module) {
var checks = require("pilot/typecheck");
var canon = require('pilot/canon');
/**
* 'help' command
*/
var helpCommandSpec = {
name: 'help',
params: [
{
name: 'search',
type: 'text',
description: 'Search string to narrow the output.',
defaultValue: null
}
],
description: 'Get help on the available commands.',
exec: function(env, args, request) {
var output = [];
var command = canon.getCommand(args.search);
if (command && command.exec) {
// caught a real command
output.push(command.description ?
command.description :
'No description for ' + args.search);
} else {
var showHidden = false;
if (command) {
// We must be looking at sub-commands
output.push('<h2>Sub-Commands of ' + command.name + '</h2>');
output.push('<p>' + command.description + '</p>');
}
else if (args.search) {
if (args.search == 'hidden') { // sneaky, sneaky.
args.search = '';
showHidden = true;
}
output.push('<h2>Commands starting with \'' + args.search + '\':</h2>');
}
else {
output.push('<h2>Available Commands:</h2>');
}
var commandNames = canon.getCommandNames();
commandNames.sort();
output.push('<table>');
for (var i = 0; i < commandNames.length; i++) {
command = canon.getCommand(commandNames[i]);
if (!showHidden && command.hidden) {
continue;
}
if (command.description === undefined) {
// Ignore editor actions
continue;
}
if (args.search && command.name.indexOf(args.search) !== 0) {
// Filtered out by the user
continue;
}
if (!args.search && command.name.indexOf(' ') != -1) {
// sub command
continue;
}
if (command && command.name == args.search) {
// sub command, and we've already given that help
continue;
}
// todo add back a column with parameter information, perhaps?
output.push('<tr>');
output.push('<th class="right">' + command.name + '</th>');
output.push('<td>' + command.description + '</td>');
output.push('</tr>');
}
output.push('</table>');
}
request.done(output.join(''));
}
};
/**
* 'eval' command
*/
var evalCommandSpec = {
name: 'eval',
params: [
{
name: 'javascript',
type: 'text',
description: 'The JavaScript to evaluate'
}
],
description: 'evals given js code and show the result',
hidden: true,
exec: function(env, args, request) {
var result;
var javascript = args.javascript;
try {
result = eval(javascript);
} catch (e) {
result = '<b>Error: ' + e.message + '</b>';
}
var msg = '';
var type = '';
var x;
if (checks.isFunction(result)) {
// converts the function to a well formated string
msg = (result + '').replace(/\n/g, '<br>').replace(/ /g, ' ');
type = 'function';
} else if (checks.isObject(result)) {
if (Array.isArray(result)) {
type = 'array';
} else {
type = 'object';
}
var items = [];
var value;
for (x in result) {
if (result.hasOwnProperty(x)) {
if (checks.isFunction(result[x])) {
value = '[function]';
} else if (checks.isObject(result[x])) {
value = '[object]';
} else {
value = result[x];
}
items.push({name: x, value: value});
}
}
items.sort(function(a,b) {
return (a.name.toLowerCase() < b.name.toLowerCase()) ? -1 : 1;
});
for (x = 0; x < items.length; x++) {
msg += '<b>' + items[x].name + '</b>: ' + items[x].value + '<br>';
}
} else {
msg = result;
type = typeof result;
}
request.done('Result for eval <b>\'' + javascript + '\'</b>' +
' (type: '+ type+'): <br><br>'+ msg);
}
};
var canon = require('pilot/canon');
exports.startup = function(data, reason) {
canon.addCommand(helpCommandSpec);
canon.addCommand(evalCommandSpec);
};
exports.shutdown = function(data, reason) {
canon.removeCommand(helpCommandSpec);
canon.removeCommand(evalCommandSpec);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/settings/canon', ['require', 'exports', 'module' ], function(require, exports, module) {
var historyLengthSetting = {
name: "historyLength",
description: "How many typed commands do we recall for reference?",
type: "number",
defaultValue: 50
};
exports.startup = function(data, reason) {
data.env.settings.addSetting(historyLengthSetting);
};
exports.shutdown = function(data, reason) {
data.env.settings.removeSetting(historyLengthSetting);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/plugin_manager', ['require', 'exports', 'module' , 'pilot/promise'], function(require, exports, module) {
var Promise = require("pilot/promise").Promise;
exports.REASONS = {
APP_STARTUP: 1,
APP_SHUTDOWN: 2,
PLUGIN_ENABLE: 3,
PLUGIN_DISABLE: 4,
PLUGIN_INSTALL: 5,
PLUGIN_UNINSTALL: 6,
PLUGIN_UPGRADE: 7,
PLUGIN_DOWNGRADE: 8
};
exports.Plugin = function(name) {
this.name = name;
this.status = this.INSTALLED;
};
exports.Plugin.prototype = {
/**
* constants for the state
*/
NEW: 0,
INSTALLED: 1,
REGISTERED: 2,
STARTED: 3,
UNREGISTERED: 4,
SHUTDOWN: 5,
install: function(data, reason) {
var pr = new Promise();
if (this.status > this.NEW) {
pr.resolve(this);
return pr;
}
require([this.name], function(pluginModule) {
if (pluginModule.install) {
pluginModule.install(data, reason);
}
this.status = this.INSTALLED;
pr.resolve(this);
}.bind(this));
return pr;
},
register: function(data, reason) {
var pr = new Promise();
if (this.status != this.INSTALLED) {
pr.resolve(this);
return pr;
}
require([this.name], function(pluginModule) {
if (pluginModule.register) {
pluginModule.register(data, reason);
}
this.status = this.REGISTERED;
pr.resolve(this);
}.bind(this));
return pr;
},
startup: function(data, reason) {
reason = reason || exports.REASONS.APP_STARTUP;
var pr = new Promise();
if (this.status != this.REGISTERED) {
pr.resolve(this);
return pr;
}
require([this.name], function(pluginModule) {
if (pluginModule.startup) {
pluginModule.startup(data, reason);
}
this.status = this.STARTED;
pr.resolve(this);
}.bind(this));
return pr;
},
shutdown: function(data, reason) {
if (this.status != this.STARTED) {
return;
}
pluginModule = require(this.name);
if (pluginModule.shutdown) {
pluginModule.shutdown(data, reason);
}
}
};
exports.PluginCatalog = function() {
this.plugins = {};
};
exports.PluginCatalog.prototype = {
registerPlugins: function(pluginList, data, reason) {
var registrationPromises = [];
pluginList.forEach(function(pluginName) {
var plugin = this.plugins[pluginName];
if (plugin === undefined) {
plugin = new exports.Plugin(pluginName);
this.plugins[pluginName] = plugin;
registrationPromises.push(plugin.register(data, reason));
}
}.bind(this));
return Promise.group(registrationPromises);
},
startupPlugins: function(data, reason) {
var startupPromises = [];
for (var pluginName in this.plugins) {
var plugin = this.plugins[pluginName];
startupPromises.push(plugin.startup(data, reason));
}
return Promise.group(startupPromises);
}
};
exports.catalog = new exports.PluginCatalog();
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/promise', ['require', 'exports', 'module' , 'pilot/console', 'pilot/stacktrace'], function(require, exports, module) {
var console = require("pilot/console");
var Trace = require('pilot/stacktrace').Trace;
/**
* A promise can be in one of 2 states.
* The ERROR and SUCCESS states are terminal, the PENDING state is the only
* start state.
*/
var ERROR = -1;
var PENDING = 0;
var SUCCESS = 1;
/**
* We give promises and ID so we can track which are outstanding
*/
var _nextId = 0;
/**
* Debugging help if 2 things try to complete the same promise.
* This can be slow (especially on chrome due to the stack trace unwinding) so
* we should leave this turned off in normal use.
*/
var _traceCompletion = false;
/**
* Outstanding promises. Handy list for debugging only.
*/
var _outstanding = [];
/**
* Recently resolved promises. Also for debugging only.
*/
var _recent = [];
/**
* Create an unfulfilled promise
*/
Promise = function () {
this._status = PENDING;
this._value = undefined;
this._onSuccessHandlers = [];
this._onErrorHandlers = [];
// Debugging help
this._id = _nextId++;
//this._createTrace = new Trace(new Error());
_outstanding[this._id] = this;
};
/**
* Yeay for RTTI.
*/
Promise.prototype.isPromise = true;
/**
* Have we either been resolve()ed or reject()ed?
*/
Promise.prototype.isComplete = function() {
return this._status != PENDING;
};
/**
* Have we resolve()ed?
*/
Promise.prototype.isResolved = function() {
return this._status == SUCCESS;
};
/**
* Have we reject()ed?
*/
Promise.prototype.isRejected = function() {
return this._status == ERROR;
};
/**
* Take the specified action of fulfillment of a promise, and (optionally)
* a different action on promise rejection.
*/
Promise.prototype.then = function(onSuccess, onError) {
if (typeof onSuccess === 'function') {
if (this._status === SUCCESS) {
onSuccess.call(null, this._value);
} else if (this._status === PENDING) {
this._onSuccessHandlers.push(onSuccess);
}
}
if (typeof onError === 'function') {
if (this._status === ERROR) {
onError.call(null, this._value);
} else if (this._status === PENDING) {
this._onErrorHandlers.push(onError);
}
}
return this;
};
/**
* Like then() except that rather than returning <tt>this</tt> we return
* a promise which
*/
Promise.prototype.chainPromise = function(onSuccess) {
var chain = new Promise();
chain._chainedFrom = this;
this.then(function(data) {
try {
chain.resolve(onSuccess(data));
} catch (ex) {
chain.reject(ex);
}
}, function(ex) {
chain.reject(ex);
});
return chain;
};
/**
* Supply the fulfillment of a promise
*/
Promise.prototype.resolve = function(data) {
return this._complete(this._onSuccessHandlers, SUCCESS, data, 'resolve');
};
/**
* Renege on a promise
*/
Promise.prototype.reject = function(data) {
return this._complete(this._onErrorHandlers, ERROR, data, 'reject');
};
/**
* Internal method to be called on resolve() or reject().
* @private
*/
Promise.prototype._complete = function(list, status, data, name) {
// Complain if we've already been completed
if (this._status != PENDING) {
console.group('Promise already closed');
console.error('Attempted ' + name + '() with ', data);
console.error('Previous status = ', this._status,
', previous value = ', this._value);
console.trace();
if (this._completeTrace) {
console.error('Trace of previous completion:');
this._completeTrace.log(5);
}
console.groupEnd();
return this;
}
if (_traceCompletion) {
this._completeTrace = new Trace(new Error());
}
this._status = status;
this._value = data;
// Call all the handlers, and then delete them
list.forEach(function(handler) {
handler.call(null, this._value);
}, this);
this._onSuccessHandlers.length = 0;
this._onErrorHandlers.length = 0;
// Remove the given {promise} from the _outstanding list, and add it to the
// _recent list, pruning more than 20 recent promises from that list.
delete _outstanding[this._id];
_recent.push(this);
while (_recent.length > 20) {
_recent.shift();
}
return this;
};
/**
* Takes an array of promises and returns a promise that that is fulfilled once
* all the promises in the array are fulfilled
* @param group The array of promises
* @return the promise that is fulfilled when all the array is fulfilled
*/
Promise.group = function(promiseList) {
if (!(promiseList instanceof Array)) {
promiseList = Array.prototype.slice.call(arguments);
}
// If the original array has nothing in it, return now to avoid waiting
if (promiseList.length === 0) {
return new Promise().resolve([]);
}
var groupPromise = new Promise();
var results = [];
var fulfilled = 0;
var onSuccessFactory = function(index) {
return function(data) {
results[index] = data;
fulfilled++;
// If the group has already failed, silently drop extra results
if (groupPromise._status !== ERROR) {
if (fulfilled === promiseList.length) {
groupPromise.resolve(results);
}
}
};
};
promiseList.forEach(function(promise, index) {
var onSuccess = onSuccessFactory(index);
var onError = groupPromise.reject.bind(groupPromise);
promise.then(onSuccess, onError);
});
return groupPromise;
};
exports.Promise = Promise;
exports._outstanding = _outstanding;
exports._recent = _recent;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai AT sucan AT gmail ODT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/dom', ['require', 'exports', 'module' ], function(require, exports, module) {
var XHTML_NS = "http://www.w3.org/1999/xhtml";
exports.createElement = function(tag, ns) {
return document.createElementNS ?
document.createElementNS(ns || XHTML_NS, tag) :
document.createElement(tag);
};
exports.setText = function(elem, text) {
if (elem.innerText !== undefined) {
elem.innerText = text;
}
if (elem.textContent !== undefined) {
elem.textContent = text;
}
};
if (!document.documentElement.classList) {
exports.hasCssClass = function(el, name) {
var classes = el.className.split(/\s+/g);
return classes.indexOf(name) !== -1;
};
/**
* Add a CSS class to the list of classes on the given node
*/
exports.addCssClass = function(el, name) {
if (!exports.hasCssClass(el, name)) {
el.className += " " + name;
}
};
/**
* Remove a CSS class from the list of classes on the given node
*/
exports.removeCssClass = function(el, name) {
var classes = el.className.split(/\s+/g);
while (true) {
var index = classes.indexOf(name);
if (index == -1) {
break;
}
classes.splice(index, 1);
}
el.className = classes.join(" ");
};
exports.toggleCssClass = function(el, name) {
var classes = el.className.split(/\s+/g), add = true;
while (true) {
var index = classes.indexOf(name);
if (index == -1) {
break;
}
add = false;
classes.splice(index, 1);
}
if(add)
classes.push(name);
el.className = classes.join(" ");
return add;
};
} else {
exports.hasCssClass = function(el, name) {
return el.classList.contains(name);
};
exports.addCssClass = function(el, name) {
el.classList.add(name);
};
exports.removeCssClass = function(el, name) {
el.classList.remove(name);
};
exports.toggleCssClass = function(el, name) {
return el.classList.toggle(name);
};
}
/**
* Add or remove a CSS class from the list of classes on the given node
* depending on the value of <tt>include</tt>
*/
exports.setCssClass = function(node, className, include) {
if (include) {
exports.addCssClass(node, className);
} else {
exports.removeCssClass(node, className);
}
};
exports.importCssString = function(cssText, doc){
doc = doc || document;
if (doc.createStyleSheet) {
var sheet = doc.createStyleSheet();
sheet.cssText = cssText;
}
else {
var style = doc.createElementNS ?
doc.createElementNS(XHTML_NS, "style") :
doc.createElement("style");
style.appendChild(doc.createTextNode(cssText));
var head = doc.getElementsByTagName("head")[0] || doc.documentElement;
head.appendChild(style);
}
};
exports.getInnerWidth = function(element) {
return (parseInt(exports.computedStyle(element, "paddingLeft"))
+ parseInt(exports.computedStyle(element, "paddingRight")) + element.clientWidth);
};
exports.getInnerHeight = function(element) {
return (parseInt(exports.computedStyle(element, "paddingTop"))
+ parseInt(exports.computedStyle(element, "paddingBottom")) + element.clientHeight);
};
if (window.pageYOffset !== undefined) {
exports.getPageScrollTop = function() {
return window.pageYOffset;
};
exports.getPageScrollLeft = function() {
return window.pageXOffset;
};
}
else {
exports.getPageScrollTop = function() {
return document.body.scrollTop;
};
exports.getPageScrollLeft = function() {
return document.body.scrollLeft;
};
}
if (window.getComputedStyle)
exports.computedStyle = function(element, style) {
if (style)
return (window.getComputedStyle(element, "") || {})[style] || "";
return window.getComputedStyle(element, "") || {}
};
else
exports.computedStyle = function(element, style) {
if (style)
return element.currentStyle[style];
return element.currentStyle
};
exports.scrollbarWidth = function() {
var inner = exports.createElement("p");
inner.style.width = "100%";
inner.style.minWidth = "0px";
inner.style.height = "200px";
var outer = exports.createElement("div");
var style = outer.style;
style.position = "absolute";
style.left = "-10000px";
style.overflow = "hidden";
style.width = "200px";
style.minWidth = "0px";
style.height = "150px";
outer.appendChild(inner);
var body = document.body || document.documentElement;
body.appendChild(outer);
var noScrollbar = inner.offsetWidth;
style.overflow = "scroll";
var withScrollbar = inner.offsetWidth;
if (noScrollbar == withScrollbar) {
withScrollbar = outer.clientWidth;
}
body.removeChild(outer);
return noScrollbar-withScrollbar;
};
/**
* Optimized set innerHTML. This is faster than plain innerHTML if the element
* already contains a lot of child elements.
*
* See http://blog.stevenlevithan.com/archives/faster-than-innerhtml for details
*/
exports.setInnerHtml = function(el, innerHtml) {
var element = el.cloneNode(false);//document.createElement("div");
element.innerHTML = innerHtml;
el.parentNode.replaceChild(element, el);
return element;
};
exports.setInnerText = function(el, innerText) {
if (document.body && "textContent" in document.body)
el.textContent = innerText;
else
el.innerText = innerText;
};
exports.getInnerText = function(el) {
if (document.body && "textContent" in document.body)
return el.textContent;
else
return el.innerText || el.textContent || "";
};
exports.getParentWindow = function(document) {
return document.defaultView || document.parentWindow;
};
exports.getSelectionStart = function(textarea) {
// TODO IE
var start;
try {
start = textarea.selectionStart || 0;
} catch (e) {
start = 0;
}
return start;
};
exports.setSelectionStart = function(textarea, start) {
// TODO IE
return textarea.selectionStart = start;
};
exports.getSelectionEnd = function(textarea) {
// TODO IE
var end;
try {
end = textarea.selectionEnd || 0;
} catch (e) {
end = 0;
}
return end;
};
exports.setSelectionEnd = function(textarea, end) {
// TODO IE
return textarea.selectionEnd = end;
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/event', ['require', 'exports', 'module' , 'pilot/keys', 'pilot/useragent', 'pilot/dom'], function(require, exports, module) {
var keys = require("pilot/keys");
var useragent = require("pilot/useragent");
var dom = require("pilot/dom");
exports.addListener = function(elem, type, callback) {
if (elem.addEventListener) {
return elem.addEventListener(type, callback, false);
}
if (elem.attachEvent) {
var wrapper = function() {
callback(window.event);
};
callback._wrapper = wrapper;
elem.attachEvent("on" + type, wrapper);
}
};
exports.removeListener = function(elem, type, callback) {
if (elem.removeEventListener) {
return elem.removeEventListener(type, callback, false);
}
if (elem.detachEvent) {
elem.detachEvent("on" + type, callback._wrapper || callback);
}
};
/**
* Prevents propagation and clobbers the default action of the passed event
*/
exports.stopEvent = function(e) {
exports.stopPropagation(e);
exports.preventDefault(e);
return false;
};
exports.stopPropagation = function(e) {
if (e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
};
exports.preventDefault = function(e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
};
exports.getDocumentX = function(e) {
if (e.clientX) {
return e.clientX + dom.getPageScrollLeft();
} else {
return e.pageX;
}
};
exports.getDocumentY = function(e) {
if (e.clientY) {
return e.clientY + dom.getPageScrollTop();
} else {
return e.pageY;
}
};
/**
* @return {Number} 0 for left button, 1 for middle button, 2 for right button
*/
exports.getButton = function(e) {
if (e.type == "dblclick")
return 0;
else if (e.type == "contextmenu")
return 2;
// DOM Event
if (e.preventDefault) {
return e.button;
}
// old IE
else {
return {1:0, 2:2, 4:1}[e.button];
}
};
if (document.documentElement.setCapture) {
exports.capture = function(el, eventHandler, releaseCaptureHandler) {
function onMouseMove(e) {
eventHandler(e);
return exports.stopPropagation(e);
}
function onReleaseCapture(e) {
eventHandler && eventHandler(e);
releaseCaptureHandler && releaseCaptureHandler();
exports.removeListener(el, "mousemove", eventHandler);
exports.removeListener(el, "mouseup", onReleaseCapture);
exports.removeListener(el, "losecapture", onReleaseCapture);
el.releaseCapture();
}
exports.addListener(el, "mousemove", eventHandler);
exports.addListener(el, "mouseup", onReleaseCapture);
exports.addListener(el, "losecapture", onReleaseCapture);
el.setCapture();
};
}
else {
exports.capture = function(el, eventHandler, releaseCaptureHandler) {
function onMouseMove(e) {
eventHandler(e);
e.stopPropagation();
}
function onMouseUp(e) {
eventHandler && eventHandler(e);
releaseCaptureHandler && releaseCaptureHandler();
document.removeEventListener("mousemove", onMouseMove, true);
document.removeEventListener("mouseup", onMouseUp, true);
e.stopPropagation();
}
document.addEventListener("mousemove", onMouseMove, true);
document.addEventListener("mouseup", onMouseUp, true);
};
}
exports.addMouseWheelListener = function(el, callback) {
var listener = function(e) {
if (e.wheelDelta !== undefined) {
if (e.wheelDeltaX !== undefined) {
e.wheelX = -e.wheelDeltaX / 8;
e.wheelY = -e.wheelDeltaY / 8;
} else {
e.wheelX = 0;
e.wheelY = -e.wheelDelta / 8;
}
}
else {
if (e.axis && e.axis == e.HORIZONTAL_AXIS) {
e.wheelX = (e.detail || 0) * 5;
e.wheelY = 0;
} else {
e.wheelX = 0;
e.wheelY = (e.detail || 0) * 5;
}
}
callback(e);
};
exports.addListener(el, "DOMMouseScroll", listener);
exports.addListener(el, "mousewheel", listener);
};
exports.addMultiMouseDownListener = function(el, button, count, timeout, callback) {
var clicks = 0;
var startX, startY;
var listener = function(e) {
clicks += 1;
if (clicks == 1) {
startX = e.clientX;
startY = e.clientY;
setTimeout(function() {
clicks = 0;
}, timeout || 600);
}
var isButton = exports.getButton(e) == button;
if (!isButton || Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5)
clicks = 0;
if (clicks == count) {
clicks = 0;
callback(e);
}
if (isButton)
return exports.preventDefault(e);
};
exports.addListener(el, "mousedown", listener);
useragent.isIE && exports.addListener(el, "dblclick", listener);
};
function normalizeCommandKeys(callback, e, keyCode) {
var hashId = 0;
if (useragent.isOpera && useragent.isMac) {
hashId = 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0)
| (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0);
} else {
hashId = 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0)
| (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0);
}
if (keyCode in keys.MODIFIER_KEYS) {
switch (keys.MODIFIER_KEYS[keyCode]) {
case "Alt":
hashId = 2;
break;
case "Shift":
hashId = 4;
break
case "Ctrl":
hashId = 1;
break;
default:
hashId = 8;
break;
}
keyCode = 0;
}
if (hashId & 8 && (keyCode == 91 || keyCode == 93)) {
keyCode = 0;
}
// If there is no hashID and the keyCode is not a function key, then
// we don't call the callback as we don't handle a command key here
// (it's a normal key/character input).
if (hashId == 0 && !(keyCode in keys.FUNCTION_KEYS)) {
return false;
}
return callback(e, hashId, keyCode);
}
exports.addCommandKeyListener = function(el, callback) {
var addListener = exports.addListener;
if (useragent.isOldGecko) {
// Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown
// event if the user pressed the key for a longer time. Instead, the
// keydown event was fired once and later on only the keypress event.
// To emulate the 'right' keydown behavior, the keyCode of the initial
// keyDown event is stored and in the following keypress events the
// stores keyCode is used to emulate a keyDown event.
var lastKeyDownKeyCode = null;
addListener(el, "keydown", function(e) {
lastKeyDownKeyCode = e.keyCode;
});
addListener(el, "keypress", function(e) {
return normalizeCommandKeys(callback, e, lastKeyDownKeyCode);
});
} else {
var lastDown = null;
addListener(el, "keydown", function(e) {
lastDown = e.keyIdentifier || e.keyCode;
return normalizeCommandKeys(callback, e, e.keyCode);
});
// repeated keys are fired as keypress and not keydown events
if (useragent.isMac && useragent.isOpera) {
addListener(el, "keypress", function(e) {
var keyId = e.keyIdentifier || e.keyCode;
if (lastDown !== keyId) {
return normalizeCommandKeys(callback, e, e.keyCode);
} else {
lastDown = null;
}
});
}
}
};
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/editor', ['require', 'exports', 'module' , 'pilot/fixoldbrowsers', 'pilot/oop', 'pilot/event', 'pilot/lang', 'pilot/useragent', 'ace/keyboard/textinput', 'ace/mouse_handler', 'ace/keyboard/keybinding', 'ace/edit_session', 'ace/search', 'ace/range', 'pilot/event_emitter'], function(require, exports, module) {
require("pilot/fixoldbrowsers");
var oop = require("pilot/oop");
var event = require("pilot/event");
var lang = require("pilot/lang");
var useragent = require("pilot/useragent");
var TextInput = require("ace/keyboard/textinput").TextInput;
var MouseHandler = require("ace/mouse_handler").MouseHandler;
//var TouchHandler = require("ace/touch_handler").TouchHandler;
var KeyBinding = require("ace/keyboard/keybinding").KeyBinding;
var EditSession = require("ace/edit_session").EditSession;
var Search = require("ace/search").Search;
var Range = require("ace/range").Range;
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Editor =function(renderer, session) {
var container = renderer.getContainerElement();
this.container = container;
this.renderer = renderer;
this.textInput = new TextInput(renderer.getTextAreaContainer(), this);
this.keyBinding = new KeyBinding(this);
// TODO detect touch event support
if (useragent.isIPad) {
//this.$mouseHandler = new TouchHandler(this);
} else {
this.$mouseHandler = new MouseHandler(this);
}
this.$blockScrolling = 0;
this.$search = new Search().set({
wrap: true
});
this.setSession(session || new EditSession(""));
};
(function(){
oop.implement(this, EventEmitter);
this.$forwardEvents = {
gutterclick: 1,
gutterdblclick: 1
};
this.$originalAddEventListener = this.addEventListener;
this.$originalRemoveEventListener = this.removeEventListener;
this.addEventListener = function(eventName, callback) {
if (this.$forwardEvents[eventName]) {
return this.renderer.addEventListener(eventName, callback);
} else {
return this.$originalAddEventListener(eventName, callback);
}
};
this.removeEventListener = function(eventName, callback) {
if (this.$forwardEvents[eventName]) {
return this.renderer.removeEventListener(eventName, callback);
} else {
return this.$originalRemoveEventListener(eventName, callback);
}
};
this.setKeyboardHandler = function(keyboardHandler) {
this.keyBinding.setKeyboardHandler(keyboardHandler);
};
this.getKeyboardHandler = function() {
return this.keyBinding.getKeyboardHandler();
};
this.setSession = function(session) {
if (this.session == session)
return;
if (this.session) {
var oldSession = this.session;
this.session.removeEventListener("change", this.$onDocumentChange);
this.session.removeEventListener("changeMode", this.$onChangeMode);
this.session.removeEventListener("tokenizerUpdate", this.$onTokenizerUpdate);
this.session.removeEventListener("changeTabSize", this.$onChangeTabSize);
this.session.removeEventListener("changeWrapLimit", this.$onChangeWrapLimit);
this.session.removeEventListener("changeWrapMode", this.$onChangeWrapMode);
this.session.removeEventListener("onChangeFold", this.$onChangeFold);
this.session.removeEventListener("changeFrontMarker", this.$onChangeFrontMarker);
this.session.removeEventListener("changeBackMarker", this.$onChangeBackMarker);
this.session.removeEventListener("changeBreakpoint", this.$onChangeBreakpoint);
this.session.removeEventListener("changeAnnotation", this.$onChangeAnnotation);
this.session.removeEventListener("changeOverwrite", this.$onCursorChange);
var selection = this.session.getSelection();
selection.removeEventListener("changeCursor", this.$onCursorChange);
selection.removeEventListener("changeSelection", this.$onSelectionChange);
this.session.setScrollTopRow(this.renderer.getScrollTopRow());
}
this.session = session;
this.$onDocumentChange = this.onDocumentChange.bind(this);
session.addEventListener("change", this.$onDocumentChange);
this.renderer.setSession(session);
this.$onChangeMode = this.onChangeMode.bind(this);
session.addEventListener("changeMode", this.$onChangeMode);
this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
session.addEventListener("tokenizerUpdate", this.$onTokenizerUpdate);
this.$onChangeTabSize = this.renderer.updateText.bind(this.renderer);
session.addEventListener("changeTabSize", this.$onChangeTabSize);
this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
session.addEventListener("changeWrapLimit", this.$onChangeWrapLimit);
this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
session.addEventListener("changeWrapMode", this.$onChangeWrapMode);
this.$onChangeFold = this.onChangeFold.bind(this);
session.addEventListener("changeFold", this.$onChangeFold);
this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
this.session.addEventListener("changeFrontMarker", this.$onChangeFrontMarker);
this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
this.session.addEventListener("changeBackMarker", this.$onChangeBackMarker);
this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
this.session.addEventListener("changeBreakpoint", this.$onChangeBreakpoint);
this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
this.session.addEventListener("changeAnnotation", this.$onChangeAnnotation);
this.$onCursorChange = this.onCursorChange.bind(this);
this.session.addEventListener("changeOverwrite", this.$onCursorChange);
this.selection = session.getSelection();
this.selection.addEventListener("changeCursor", this.$onCursorChange);
this.$onSelectionChange = this.onSelectionChange.bind(this);
this.selection.addEventListener("changeSelection", this.$onSelectionChange);
this.onChangeMode();
this.onCursorChange();
this.onSelectionChange();
this.onChangeFrontMarker();
this.onChangeBackMarker();
this.onChangeBreakpoint();
this.onChangeAnnotation();
this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
this.renderer.scrollToRow(session.getScrollTopRow());
this.renderer.updateFull();
this._dispatchEvent("changeSession", {
session: session,
oldSession: oldSession
});
};
this.getSession = function() {
return this.session;
};
this.getSelection = function() {
return this.selection;
};
this.resize = function() {
this.renderer.onResize();
};
this.setTheme = function(theme) {
this.renderer.setTheme(theme);
};
this.getTheme = function() {
return this.renderer.getTheme();
};
this.setStyle = function(style) {
this.renderer.setStyle(style);
};
this.unsetStyle = function(style) {
this.renderer.unsetStyle(style);
};
this.setFontSize = function(size) {
this.container.style.fontSize = size;
};
this.$highlightBrackets = function() {
if (this.session.$bracketHighlight) {
this.session.removeMarker(this.session.$bracketHighlight);
this.session.$bracketHighlight = null;
}
if (this.$highlightPending) {
return;
}
// perform highlight async to not block the browser during navigation
var self = this;
this.$highlightPending = true;
setTimeout(function() {
self.$highlightPending = false;
var pos = self.session.findMatchingBracket(self.getCursorPosition());
if (pos) {
var range = new Range(pos.row, pos.column, pos.row, pos.column+1);
self.session.$bracketHighlight = self.session.addMarker(range, "ace_bracket", "text");
}
}, 10);
};
this.focus = function() {
// Safari needs the timeout
// iOS and Firefox need it called immediately
// to be on the save side we do both
// except for IE
var _self = this;
if (!useragent.isIE) {
setTimeout(function() {
_self.textInput.focus();
});
}
this.textInput.focus();
};
this.isFocused = function() {
return this.textInput.isFocused();
};
this.blur = function() {
this.textInput.blur();
};
this.onFocus = function() {
this.renderer.showCursor();
this.renderer.visualizeFocus();
this._dispatchEvent("focus");
};
this.onBlur = function() {
this.renderer.hideCursor();
this.renderer.visualizeBlur();
this._dispatchEvent("blur");
};
this.onDocumentChange = function(e) {
var delta = e.data;
var range = delta.range;
if (range.start.row == range.end.row && delta.action != "insertLines" && delta.action != "removeLines")
var lastRow = range.end.row;
else
lastRow = Infinity;
this.renderer.updateLines(range.start.row, lastRow);
// update cursor because tab characters can influence the cursor position
this.renderer.updateCursor();
};
this.onTokenizerUpdate = function(e) {
var rows = e.data;
this.renderer.updateLines(rows.first, rows.last);
};
this.onCursorChange = function(e) {
this.renderer.updateCursor();
if (!this.$blockScrolling) {
this.renderer.scrollCursorIntoView();
}
// move text input over the cursor
// this is required for iOS and IME
this.renderer.moveTextAreaToCursor(this.textInput.getElement());
this.$highlightBrackets();
this.$updateHighlightActiveLine();
};
this.$updateHighlightActiveLine = function() {
var session = this.getSession();
if (session.$highlightLineMarker) {
session.removeMarker(session.$highlightLineMarker);
}
session.$highlightLineMarker = null;
if (this.getHighlightActiveLine() && (this.getSelectionStyle() != "line" || !this.selection.isMultiLine())) {
var cursor = this.getCursorPosition(),
foldLine = this.session.getFoldLine(cursor.row);
var range;
if (foldLine) {
range = new Range(foldLine.start.row, 0, foldLine.end.row + 1, 0);
} else {
range = new Range(cursor.row, 0, cursor.row+1, 0);
}
session.$highlightLineMarker = session.addMarker(range, "ace_active_line", "background");
}
};
this.onSelectionChange = function(e) {
var session = this.getSession();
if (session.$selectionMarker) {
session.removeMarker(session.$selectionMarker);
}
session.$selectionMarker = null;
if (!this.selection.isEmpty()) {
var range = this.selection.getRange();
var style = this.getSelectionStyle();
session.$selectionMarker = session.addMarker(range, "ace_selection", style);
} else {
this.$updateHighlightActiveLine();
}
if (this.$highlightSelectedWord)
this.session.getMode().highlightSelection(this);
};
this.onChangeFrontMarker = function() {
this.renderer.updateFrontMarkers();
};
this.onChangeBackMarker = function() {
this.renderer.updateBackMarkers();
};
this.onChangeBreakpoint = function() {
this.renderer.setBreakpoints(this.session.getBreakpoints());
};
this.onChangeAnnotation = function() {
this.renderer.setAnnotations(this.session.getAnnotations());
};
this.onChangeMode = function() {
this.renderer.updateText()
};
this.onChangeWrapLimit = function() {
this.renderer.updateFull();
};
this.onChangeWrapMode = function() {
this.renderer.onResize(true);
};
this.onChangeFold = function() {
// Update the active line marker as due to folding changes the current
// line range on the screen might have changed.
this.$updateHighlightActiveLine();
// TODO: This might be too much updating. Okay for now.
this.renderer.updateFull();
};
this.getCopyText = function() {
if (!this.selection.isEmpty()) {
return this.session.getTextRange(this.getSelectionRange());
}
else {
return "";
}
};
this.onCut = function() {
if (this.$readOnly)
return;
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange())
this.clearSelection();
}
};
this.insert = function(text) {
if (this.$readOnly)
return;
var session = this.session;
var mode = session.getMode();
var cursor = this.getCursorPosition();
if (this.getBehavioursEnabled()) {
// Get a transform if the current mode wants one.
var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
if (transform)
text = transform.text;
}
text = text.replace("\t", this.session.getTabString());
// remove selected text
if (!this.selection.isEmpty()) {
var cursor = this.session.remove(this.getSelectionRange());
this.clearSelection();
}
else if (this.session.getOverwrite()) {
var range = new Range.fromPoints(cursor, cursor);
range.end.column += text.length;
this.session.remove(range);
}
this.clearSelection();
var start = cursor.column;
var lineState = session.getState(cursor.row);
var shouldOutdent = mode.checkOutdent(lineState, session.getLine(cursor.row), text);
var line = session.getLine(cursor.row);
var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
var end = session.insert(cursor, text);
if (transform && transform.selection) {
if (transform.selection.length == 2) { // Transform relative to the current column
this.selection.setSelectionRange(
new Range(cursor.row, start + transform.selection[0],
cursor.row, start + transform.selection[1]));
} else { // Transform relative to the current row.
this.selection.setSelectionRange(
new Range(cursor.row + transform.selection[0],
transform.selection[1],
cursor.row + transform.selection[2],
transform.selection[3]));
}
}
var lineState = session.getState(cursor.row);
// TODO disabled multiline auto indent
// possibly doing the indent before inserting the text
// if (cursor.row !== end.row) {
if (session.getDocument().isNewLine(text)) {
this.moveCursorTo(cursor.row+1, 0);
var size = session.getTabSize();
var minIndent = Number.MAX_VALUE;
for (var row = cursor.row + 1; row <= end.row; ++row) {
var indent = 0;
line = session.getLine(row);
for (var i = 0; i < line.length; ++i)
if (line.charAt(i) == '\t')
indent += size;
else if (line.charAt(i) == ' ')
indent += 1;
else
break;
if (/[^\s]/.test(line))
minIndent = Math.min(indent, minIndent);
}
for (var row = cursor.row + 1; row <= end.row; ++row) {
var outdent = minIndent;
line = session.getLine(row);
for (var i = 0; i < line.length && outdent > 0; ++i)
if (line.charAt(i) == '\t')
outdent -= size;
else if (line.charAt(i) == ' ')
outdent -= 1;
session.remove(new Range(row, 0, row, i));
}
session.indentRows(cursor.row + 1, end.row, lineIndent);
} else {
if (shouldOutdent) {
mode.autoOutdent(lineState, session, cursor.row);
}
}
};
this.onTextInput = function(text, notPasted) {
// In case the text was not pasted and we got only one character, then
// handel it as a command key stroke.
if (notPasted && text.length == 1) {
// Note: The `null` as `keyCode` is important here, as there are
// some checks in the code for `keyCode == 0` meaning the text comes
// from the keyBinding.onTextInput code path.
var handled = this.keyBinding.onCommandKey({}, 0, null, text);
// Check if the text was handled. If not, then handled it as "normal"
// text and insert it to the editor directly. This shouldn't be done
// using the this.keyBinding.onTextInput(text) function, as it would
// make the `text` get sent to the keyboardHandler twice, which might
// turn out to be a bad thing in case there is a custome keyboard
// handler like the StateHandler.
if (!handled) {
this.insert(text);
}
} else {
this.keyBinding.onTextInput(text);
}
};
this.onCommandKey = function(e, hashId, keyCode) {
this.keyBinding.onCommandKey(e, hashId, keyCode);
};
this.setOverwrite = function(overwrite) {
this.session.setOverwrite(overwrite);
};
this.getOverwrite = function() {
return this.session.getOverwrite();
};
this.toggleOverwrite = function() {
this.session.toggleOverwrite();
};
this.setScrollSpeed = function(speed) {
this.$mouseHandler.setScrollSpeed(speed);
};
this.getScrollSpeed = function() {
return this.$mouseHandler.getScrollSpeed()
};
this.$selectionStyle = "line";
this.setSelectionStyle = function(style) {
if (this.$selectionStyle == style) return;
this.$selectionStyle = style;
this.onSelectionChange();
this._dispatchEvent("changeSelectionStyle", {data: style});
};
this.getSelectionStyle = function() {
return this.$selectionStyle;
};
this.$highlightActiveLine = true;
this.setHighlightActiveLine = function(shouldHighlight) {
if (this.$highlightActiveLine == shouldHighlight) return;
this.$highlightActiveLine = shouldHighlight;
this.$updateHighlightActiveLine();
};
this.getHighlightActiveLine = function() {
return this.$highlightActiveLine;
};
this.$highlightSelectedWord = true;
this.setHighlightSelectedWord = function(shouldHighlight) {
if (this.$highlightSelectedWord == shouldHighlight)
return;
this.$highlightSelectedWord = shouldHighlight;
if (shouldHighlight)
this.session.getMode().highlightSelection(this);
else
this.session.getMode().clearSelectionHighlight(this);
};
this.getHighlightSelectedWord = function() {
return this.$highlightSelectedWord;
};
this.setShowInvisibles = function(showInvisibles) {
if (this.getShowInvisibles() == showInvisibles)
return;
this.renderer.setShowInvisibles(showInvisibles);
};
this.getShowInvisibles = function() {
return this.renderer.getShowInvisibles();
};
this.setShowPrintMargin = function(showPrintMargin) {
this.renderer.setShowPrintMargin(showPrintMargin);
};
this.getShowPrintMargin = function() {
return this.renderer.getShowPrintMargin();
};
this.setPrintMarginColumn = function(showPrintMargin) {
this.renderer.setPrintMarginColumn(showPrintMargin);
};
this.getPrintMarginColumn = function() {
return this.renderer.getPrintMarginColumn();
};
this.$readOnly = false;
this.setReadOnly = function(readOnly) {
this.$readOnly = readOnly;
};
this.getReadOnly = function() {
return this.$readOnly;
};
this.$modeBehaviours = true;
this.setBehavioursEnabled = function (enabled) {
this.$modeBehaviours = enabled;
}
this.getBehavioursEnabled = function () {
return this.$modeBehaviours;
}
this.removeRight = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty()) {
this.selection.selectRight();
}
this.session.remove(this.getSelectionRange())
this.clearSelection();
};
this.removeLeft = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectLeft();
var range = this.getSelectionRange();
if (this.getBehavioursEnabled()) {
var session = this.session;
var state = session.getState(range.start.row);
var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
if (new_range !== false) {
range = new_range;
}
}
this.session.remove(range);
this.clearSelection();
};
this.removeWordRight = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectWordRight();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeWordLeft = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectWordLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeToLineStart = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectLineStart();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeToLineEnd = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectLineEnd();
var range = this.getSelectionRange();
if (range.start.column == range.end.column && range.start.row == range.end.row) {
range.end.column = 0;
range.end.row++;
}
this.session.remove(range);
this.clearSelection();
};
this.splitLine = function() {
if (this.$readOnly)
return;
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
var cursor = this.getCursorPosition();
this.insert("\n");
this.moveCursorToPosition(cursor);
};
this.transposeLetters = function() {
if (this.$readOnly)
return;
if (!this.selection.isEmpty()) {
return;
}
var cursor = this.getCursorPosition();
var column = cursor.column;
if (column == 0)
return;
var line = this.session.getLine(cursor.row);
if (column < line.length) {
var swap = line.charAt(column) + line.charAt(column-1);
var range = new Range(cursor.row, column-1, cursor.row, column+1)
}
else {
var swap = line.charAt(column-1) + line.charAt(column-2);
var range = new Range(cursor.row, column-2, cursor.row, column)
}
this.session.replace(range, swap);
};
this.indent = function() {
if (this.$readOnly)
return;
var session = this.session;
var range = this.getSelectionRange();
if (range.start.row < range.end.row || range.start.column < range.end.column) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
} else {
var indentString;
if (this.session.getUseSoftTabs()) {
var size = session.getTabSize(),
position = this.getCursorPosition(),
column = session.documentToScreenColumn(position.row, position.column),
count = (size - column % size);
indentString = lang.stringRepeat(" ", count);
} else
indentString = "\t";
return this.onTextInput(indentString);
}
};
this.blockOutdent = function() {
if (this.$readOnly)
return;
var selection = this.session.getSelection();
this.session.outdentRows(selection.getRange());
};
this.toggleCommentLines = function() {
if (this.$readOnly)
return;
var state = this.session.getState(this.getCursorPosition().row);
var rows = this.$getSelectedRows()
this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
};
this.removeLines = function() {
if (this.$readOnly)
return;
var rows = this.$getSelectedRows();
if (rows.last == 0 || rows.last+1 < this.session.getLength())
var range = new Range(rows.first, 0, rows.last+1, 0)
else
var range = new Range(
rows.first-1, this.session.getLine(rows.first).length,
rows.last, this.session.getLine(rows.last).length
);
this.session.remove(range);
this.clearSelection();
};
this.moveLinesDown = function() {
if (this.$readOnly)
return;
this.$moveLines(function(firstRow, lastRow) {
return this.session.moveLinesDown(firstRow, lastRow);
});
};
this.moveLinesUp = function() {
if (this.$readOnly)
return;
this.$moveLines(function(firstRow, lastRow) {
return this.session.moveLinesUp(firstRow, lastRow);
});
};
this.moveText = function(range, toPosition) {
if (this.$readOnly)
return null;
return this.session.moveText(range, toPosition);
};
this.copyLinesUp = function() {
if (this.$readOnly)
return;
this.$moveLines(function(firstRow, lastRow) {
this.session.duplicateLines(firstRow, lastRow);
return 0;
});
};
this.copyLinesDown = function() {
if (this.$readOnly)
return;
this.$moveLines(function(firstRow, lastRow) {
return this.session.duplicateLines(firstRow, lastRow);
});
};
this.$moveLines = function(mover) {
var rows = this.$getSelectedRows();
var linesMoved = mover.call(this, rows.first, rows.last);
var selection = this.selection;
selection.setSelectionAnchor(rows.last+linesMoved+1, 0);
selection.$moveSelection(function() {
selection.moveCursorTo(rows.first+linesMoved, 0);
});
};
this.$getSelectedRows = function() {
var range = this.getSelectionRange().collapseRows();
return {
first: range.start.row,
last: range.end.row
};
};
this.onCompositionStart = function(text) {
this.renderer.showComposition(this.getCursorPosition());
};
this.onCompositionUpdate = function(text) {
this.renderer.setCompositionText(text);
};
this.onCompositionEnd = function() {
this.renderer.hideComposition();
};
this.getFirstVisibleRow = function() {
return this.renderer.getFirstVisibleRow();
};
this.getLastVisibleRow = function() {
return this.renderer.getLastVisibleRow();
};
this.isRowVisible = function(row) {
return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow());
};
this.$getVisibleRowCount = function() {
return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1;
};
this.$getPageDownRow = function() {
return this.renderer.getScrollBottomRow();
};
this.$getPageUpRow = function() {
var firstRow = this.renderer.getScrollTopRow();
var lastRow = this.renderer.getScrollBottomRow();
return firstRow - (lastRow - firstRow);
};
this.selectPageDown = function() {
var row = this.$getPageDownRow() + Math.floor(this.$getVisibleRowCount() / 2);
this.scrollPageDown();
var selection = this.getSelection();
var leadScreenPos = this.session.documentToScreenPosition(selection.getSelectionLead());
var dest = this.session.screenToDocumentPosition(row, leadScreenPos.column);
selection.selectTo(dest.row, dest.column);
};
this.selectPageUp = function() {
var visibleRows = this.renderer.getScrollTopRow() - this.renderer.getScrollBottomRow();
var row = this.$getPageUpRow() + Math.round(visibleRows / 2);
this.scrollPageUp();
var selection = this.getSelection();
var leadScreenPos = this.session.documentToScreenPosition(selection.getSelectionLead());
var dest = this.session.screenToDocumentPosition(row, leadScreenPos.column);
selection.selectTo(dest.row, dest.column);
};
this.gotoPageDown = function() {
var row = this.$getPageDownRow();
var column = this.getCursorPositionScreen().column;
this.scrollToRow(row);
this.getSelection().moveCursorToScreen(row, column);
};
this.gotoPageUp = function() {
var row = this.$getPageUpRow();
var column = this.getCursorPositionScreen().column;
this.scrollToRow(row);
this.getSelection().moveCursorToScreen(row, column);
};
this.scrollPageDown = function() {
this.scrollToRow(this.$getPageDownRow());
};
this.scrollPageUp = function() {
this.renderer.scrollToRow(this.$getPageUpRow());
};
this.scrollToRow = function(row) {
this.renderer.scrollToRow(row);
};
this.scrollToLine = function(line, center) {
this.renderer.scrollToLine(line, center);
};
this.centerSelection = function() {
var range = this.getSelectionRange();
var line = Math.floor(range.start.row + (range.end.row - range.start.row) / 2);
this.renderer.scrollToLine(line, true);
};
this.getCursorPosition = function() {
return this.selection.getCursor();
};
this.getCursorPositionScreen = function() {
return this.session.documentToScreenPosition(this.getCursorPosition());
};
this.getSelectionRange = function() {
return this.selection.getRange();
};
this.selectAll = function() {
this.$blockScrolling += 1;
this.selection.selectAll();
this.$blockScrolling -= 1;
};
this.clearSelection = function() {
this.selection.clearSelection();
};
this.moveCursorTo = function(row, column) {
this.selection.moveCursorTo(row, column);
};
this.moveCursorToPosition = function(pos) {
this.selection.moveCursorToPosition(pos);
};
this.gotoLine = function(lineNumber, column) {
this.selection.clearSelection();
this.$blockScrolling += 1;
this.moveCursorTo(lineNumber-1, column || 0);
this.$blockScrolling -= 1;
if (!this.isRowVisible(this.getCursorPosition().row)) {
this.scrollToLine(lineNumber, true);
}
},
this.navigateTo = function(row, column) {
this.clearSelection();
this.moveCursorTo(row, column);
};
this.navigateUp = function(times) {
this.selection.clearSelection();
times = times || 1;
this.selection.moveCursorBy(-times, 0);
};
this.navigateDown = function(times) {
this.selection.clearSelection();
times = times || 1;
this.selection.moveCursorBy(times, 0);
};
this.navigateLeft = function(times) {
if (!this.selection.isEmpty()) {
var selectionStart = this.getSelectionRange().start;
this.moveCursorToPosition(selectionStart);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorLeft();
}
}
this.clearSelection();
};
this.navigateRight = function(times) {
if (!this.selection.isEmpty()) {
var selectionEnd = this.getSelectionRange().end;
this.moveCursorToPosition(selectionEnd);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorRight();
}
}
this.clearSelection();
};
this.navigateLineStart = function() {
this.selection.moveCursorLineStart();
this.clearSelection();
};
this.navigateLineEnd = function() {
this.selection.moveCursorLineEnd();
this.clearSelection();
};
this.navigateFileEnd = function() {
this.selection.moveCursorFileEnd();
this.clearSelection();
};
this.navigateFileStart = function() {
this.selection.moveCursorFileStart();
this.clearSelection();
};
this.navigateWordRight = function() {
this.selection.moveCursorWordRight();
this.clearSelection();
};
this.navigateWordLeft = function() {
this.selection.moveCursorWordLeft();
this.clearSelection();
};
this.replace = function(replacement, options) {
if (options)
this.$search.set(options);
var range = this.$search.find(this.session);
if (!range)
return;
this.$tryReplace(range, replacement);
if (range !== null)
this.selection.setSelectionRange(range);
},
this.replaceAll = function(replacement, options) {
if (options) {
this.$search.set(options);
}
var ranges = this.$search.findAll(this.session);
if (!ranges.length)
return;
var selection = this.getSelectionRange();
this.clearSelection();
this.selection.moveCursorTo(0, 0);
this.$blockScrolling += 1;
for (var i = ranges.length - 1; i >= 0; --i)
this.$tryReplace(ranges[i], replacement);
this.selection.setSelectionRange(selection);
this.$blockScrolling -= 1;
},
this.$tryReplace = function(range, replacement) {
var input = this.session.getTextRange(range);
var replacement = this.$search.replace(input, replacement);
if (replacement !== null) {
range.end = this.session.replace(range, replacement);
return range;
} else {
return null;
}
};
this.getLastSearchOptions = function() {
return this.$search.getOptions();
};
this.find = function(needle, options) {
this.clearSelection();
options = options || {};
options.needle = needle;
this.$search.set(options);
this.$find();
},
this.findNext = function(options) {
options = options || {};
if (typeof options.backwards == "undefined")
options.backwards = false;
this.$search.set(options);
this.$find();
};
this.findPrevious = function(options) {
options = options || {};
if (typeof options.backwards == "undefined")
options.backwards = true;
this.$search.set(options);
this.$find();
};
this.$find = function(backwards) {
if (!this.selection.isEmpty()) {
this.$search.set({needle: this.session.getTextRange(this.getSelectionRange())});
}
if (typeof backwards != "undefined")
this.$search.set({backwards: backwards});
var range = this.$search.find(this.session);
if (range) {
this.gotoLine(range.end.row+1, range.end.column);
this.selection.setSelectionRange(range);
}
};
this.undo = function() {
this.session.getUndoManager().undo();
};
this.redo = function() {
this.session.getUndoManager().redo();
};
this.destroy = function() {
this.renderer.destroy();
}
}).call(Editor.prototype);
exports.Editor = Editor;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/keyboard/textinput', ['require', 'exports', 'module' , 'pilot/event', 'pilot/useragent', 'pilot/dom'], function(require, exports, module) {
var event = require("pilot/event");
var useragent = require("pilot/useragent");
var dom = require("pilot/dom");
var TextInput = function(parentNode, host) {
var text = dom.createElement("textarea");
text.style.left = "-10000px";
parentNode.appendChild(text);
var PLACEHOLDER = String.fromCharCode(0);
sendText();
var inCompostion = false;
var copied = false;
var pasted = false;
var tempStyle = '';
function sendText(valueToSend) {
if (!copied) {
var value = valueToSend || text.value;
if (value) {
if (value.charCodeAt(value.length-1) == PLACEHOLDER.charCodeAt(0)) {
value = value.slice(0, -1);
if (value)
host.onTextInput(value, !pasted);
}
else {
host.onTextInput(value, !pasted);
}
// If editor is no longer focused we quit immediately, since
// it means that something else is in charge now.
if (!isFocused())
return false;
}
}
copied = false;
pasted = false;
// Safari doesn't fire copy events if no text is selected
text.value = PLACEHOLDER;
text.select();
}
var onTextInput = function(e) {
setTimeout(function () {
if (!inCompostion)
sendText(e.data);
}, 0);
};
var onKeyPress = function(e) {
if (useragent.isIE && text.value.charCodeAt(0) > 128) return;
setTimeout(function() {
if (!inCompostion)
sendText();
}, 0);
};
var onCompositionStart = function(e) {
inCompostion = true;
host.onCompositionStart();
if (!useragent.isGecko) setTimeout(onCompositionUpdate, 0);
};
var onCompositionUpdate = function() {
if (!inCompostion) return;
host.onCompositionUpdate(text.value);
};
var onCompositionEnd = function(e) {
inCompostion = false;
host.onCompositionEnd();
};
var onCopy = function(e) {
copied = true;
var copyText = host.getCopyText();
if(copyText)
text.value = copyText;
else
e.preventDefault();
text.select();
setTimeout(function () {
sendText();
}, 0);
};
var onCut = function(e) {
copied = true;
var copyText = host.getCopyText();
if(copyText) {
text.value = copyText;
host.onCut();
} else
e.preventDefault();
text.select();
setTimeout(function () {
sendText();
}, 0);
};
event.addCommandKeyListener(text, host.onCommandKey.bind(host));
if (useragent.isIE) {
var keytable = { 13:1, 27:1 };
event.addListener(text, "keyup", function (e) {
if (inCompostion && (!text.value || keytable[e.keyCode]))
setTimeout(onCompositionEnd, 0);
if ((text.value.charCodeAt(0)|0) < 129) {
return;
};
inCompostion ? onCompositionUpdate() : onCompositionStart();
});
};
if (text.attachEvent) {
// Old IE + Opera
event.addListener(text, "propertychange", onKeyPress);
}
else {
if (useragent.isChrome || useragent.isSafari)
event.addListener(text, "textInput", onTextInput);
else if (useragent.isIE)
// IE9
event.addListener(text, "textinput", onTextInput);
else
// All browsers except old IE
event.addListener(text, "input", onTextInput);
}
event.addListener(text, "paste", function(e) {
// Mark that the next input text comes from past.
pasted = true;
// Some browsers support the event.clipboardData API. Use this to get
// the pasted content which increases speed if pasting a lot of lines.
if (e.clipboardData && e.clipboardData.getData) {
sendText(e.clipboardData.getData("text/plain"));
e.preventDefault();
}
else {
// If a browser doesn't support any of the things above, use the regular
// method to detect the pasted input.
onKeyPress();
}
});
if (useragent.isIE) {
event.addListener(text, "beforecopy", function(e) {
var copyText = host.getCopyText();
if(copyText)
clipboardData.setData("Text", copyText);
else
e.preventDefault();
});
event.addListener(parentNode, "keydown", function(e) {
if (e.ctrlKey && e.keyCode == 88) {
var copyText = host.getCopyText();
if (copyText) {
clipboardData.setData("Text", copyText);
host.onCut();
}
event.preventDefault(e)
}
});
}
else {
event.addListener(text, "copy", onCopy);
event.addListener(text, "cut", onCut);
}
event.addListener(text, "compositionstart", onCompositionStart);
if (useragent.isGecko) {
event.addListener(text, "text", onCompositionUpdate);
};
if (useragent.isWebKit) {
event.addListener(text, "keyup", onCompositionUpdate);
};
event.addListener(text, "compositionend", onCompositionEnd);
event.addListener(text, "blur", function() {
host.onBlur();
});
event.addListener(text, "focus", function() {
host.onFocus();
text.select();
});
this.focus = function() {
host.onFocus();
text.select();
text.focus();
};
this.blur = function() {
text.blur();
};
function isFocused() {
return document.activeElement === text;
};
this.isFocused = isFocused;
this.getElement = function() {
return text;
};
this.onContextMenu = function(mousePos, isEmpty){
if (mousePos) {
if(!tempStyle)
tempStyle = text.style.cssText;
text.style.cssText = 'position:fixed; z-index:1000;' +
'left:' + (mousePos.x - 2) + 'px; top:' + (mousePos.y - 2) + 'px;'
}
if (isEmpty)
text.value='';
}
this.onContextMenuClose = function(){
setTimeout(function () {
if (tempStyle) {
text.style.cssText = tempStyle;
tempStyle = '';
}
sendText();
}, 0);
}
};
exports.TextInput = TextInput;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mouse_handler', ['require', 'exports', 'module' , 'pilot/event', 'pilot/dom', 'pilot/browser_focus'], function(require, exports, module) {
var event = require("pilot/event");
var dom = require("pilot/dom");
var BrowserFocus = require("pilot/browser_focus").BrowserFocus;
var STATE_UNKNOWN = 0;
var STATE_SELECT = 1;
var STATE_DRAG = 2;
var DRAG_TIMER = 250; // milliseconds
var DRAG_OFFSET = 5; // pixels
var MouseHandler = function(editor) {
this.editor = editor;
this.browserFocus = new BrowserFocus();
event.addListener(editor.container, "mousedown", function(e) {
editor.focus();
return event.preventDefault(e);
});
event.addListener(editor.container, "selectstart", function(e) {
return event.preventDefault(e);
});
var mouseTarget = editor.renderer.getMouseEventTarget();
event.addListener(mouseTarget, "mousedown", this.onMouseDown.bind(this));
event.addMultiMouseDownListener(mouseTarget, 0, 2, 500, this.onMouseDoubleClick.bind(this));
event.addMultiMouseDownListener(mouseTarget, 0, 3, 600, this.onMouseTripleClick.bind(this));
event.addMultiMouseDownListener(mouseTarget, 0, 4, 600, this.onMouseQuadClick.bind(this));
event.addMouseWheelListener(mouseTarget, this.onMouseWheel.bind(this));
};
(function() {
this.$scrollSpeed = 1;
this.setScrollSpeed = function(speed) {
this.$scrollSpeed = speed;
};
this.getScrollSpeed = function() {
return this.$scrollSpeed;
};
this.$getEventPosition = function(e) {
var pageX = event.getDocumentX(e);
var pageY = event.getDocumentY(e);
var pos = this.editor.renderer.screenToTextCoordinates(pageX, pageY);
pos.row = Math.max(0, Math.min(pos.row, this.editor.session.getLength()-1));
return pos;
};
this.$distance = function(ax, ay, bx, by) {
return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
};
this.onMouseDown = function(e) {
// if this click caused the editor to be focused ignore the click
// for selection and cursor placement
if (
!this.browserFocus.isFocused()
|| new Date().getTime() - this.browserFocus.lastFocus < 20
|| !this.editor.isFocused()
)
return;
var pageX = event.getDocumentX(e);
var pageY = event.getDocumentY(e);
var pos = this.$getEventPosition(e);
var editor = this.editor;
var self = this;
var selectionRange = editor.getSelectionRange();
var selectionEmpty = selectionRange.isEmpty();
var state = STATE_UNKNOWN;
var inSelection = false;
var button = event.getButton(e);
if (button !== 0) {
if (selectionEmpty) {
editor.moveCursorToPosition(pos);
}
if(button == 2) {
editor.textInput.onContextMenu({x: pageX, y: pageY}, selectionEmpty);
event.capture(editor.container, function(){}, editor.textInput.onContextMenuClose);
}
return;
} else {
// Select the fold as the user clicks it.
var fold = editor.session.getFoldAt(pos.row, pos.column, 1);
if (fold) {
editor.selection.setSelectionRange(fold.range);
return;
}
inSelection = !editor.getReadOnly()
&& !selectionEmpty
&& selectionRange.contains(pos.row, pos.column);
}
if (!inSelection) {
// Directly pick STATE_SELECT, since the user is not clicking inside
// a selection.
onStartSelect(pos);
}
var mousePageX, mousePageY;
var overwrite = editor.getOverwrite();
var mousedownTime = (new Date()).getTime();
var dragCursor, dragRange;
var onMouseSelection = function(e) {
mousePageX = event.getDocumentX(e);
mousePageY = event.getDocumentY(e);
};
var onMouseSelectionEnd = function() {
clearInterval(timerId);
if (state == STATE_UNKNOWN)
onStartSelect(pos);
else if (state == STATE_DRAG)
onMouseDragSelectionEnd();
self.$clickSelection = null;
state = STATE_UNKNOWN;
};
var onMouseDragSelectionEnd = function() {
dom.removeCssClass(editor.container, "ace_dragging");
editor.session.removeMarker(dragSelectionMarker);
if (!self.$clickSelection) {
if (!dragCursor) {
editor.moveCursorToPosition(pos);
editor.selection.clearSelection(pos.row, pos.column);
}
}
if (!dragCursor)
return;
if (dragRange.contains(dragCursor.row, dragCursor.column)) {
dragCursor = null;
return;
}
editor.clearSelection();
var newRange = editor.moveText(dragRange, dragCursor);
if (!newRange) {
dragCursor = null;
return;
}
editor.selection.setSelectionRange(newRange);
};
var onSelectionInterval = function() {
if (mousePageX === undefined || mousePageY === undefined)
return;
if (state == STATE_UNKNOWN) {
var distance = self.$distance(pageX, pageY, mousePageX, mousePageY);
var time = (new Date()).getTime();
if (distance > DRAG_OFFSET) {
state = STATE_SELECT;
var cursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY);
cursor.row = Math.max(0, Math.min(cursor.row, editor.session.getLength()-1));
onStartSelect(cursor);
} else if ((time - mousedownTime) > DRAG_TIMER) {
state = STATE_DRAG;
dragRange = editor.getSelectionRange();
var style = editor.getSelectionStyle();
dragSelectionMarker = editor.session.addMarker(dragRange, "ace_selection", style);
editor.clearSelection();
dom.addCssClass(editor.container, "ace_dragging");
}
}
if (state == STATE_DRAG)
onDragSelectionInterval();
else if (state == STATE_SELECT)
onUpdateSelectionInterval();
};
function onStartSelect(pos) {
if (e.shiftKey)
editor.selection.selectToPosition(pos)
else {
if (!self.$clickSelection) {
editor.moveCursorToPosition(pos);
editor.selection.clearSelection(pos.row, pos.column);
}
}
state = STATE_SELECT;
}
var onUpdateSelectionInterval = function() {
var cursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY);
cursor.row = Math.max(0, Math.min(cursor.row, editor.session.getLength()-1));
if (self.$clickSelection) {
if (self.$clickSelection.contains(cursor.row, cursor.column)) {
editor.selection.setSelectionRange(self.$clickSelection);
} else {
if (self.$clickSelection.compare(cursor.row, cursor.column) == -1) {
var anchor = self.$clickSelection.end;
} else {
var anchor = self.$clickSelection.start;
}
editor.selection.setSelectionAnchor(anchor.row, anchor.column);
editor.selection.selectToPosition(cursor);
}
}
else {
editor.selection.selectToPosition(cursor);
}
editor.renderer.scrollCursorIntoView();
};
var onDragSelectionInterval = function() {
dragCursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY);
dragCursor.row = Math.max(0, Math.min(dragCursor.row,
editor.session.getLength() - 1));
editor.moveCursorToPosition(dragCursor);
};
event.capture(editor.container, onMouseSelection, onMouseSelectionEnd);
var timerId = setInterval(onSelectionInterval, 20);
return event.preventDefault(e);
};
this.onMouseDoubleClick = function(e) {
var editor = this.editor;
var pos = this.$getEventPosition(e);
// If the user dclicked on a fold, then expand it.
var fold = editor.session.getFoldAt(pos.row, pos.column, 1);
if (fold) {
editor.session.expandFold(fold);
} else {
editor.moveCursorToPosition(pos);
editor.selection.selectWord();
this.$clickSelection = editor.getSelectionRange();
}
};
this.onMouseTripleClick = function(e) {
var pos = this.$getEventPosition(e);
this.editor.moveCursorToPosition(pos);
this.editor.selection.selectLine();
this.$clickSelection = this.editor.getSelectionRange();
};
this.onMouseQuadClick = function(e) {
this.editor.selectAll();
this.$clickSelection = this.editor.getSelectionRange();
};
this.onMouseWheel = function(e) {
var speed = this.$scrollSpeed * 2;
this.editor.renderer.scrollBy(e.wheelX * speed, e.wheelY * speed);
return event.preventDefault(e);
};
}).call(MouseHandler.prototype);
exports.MouseHandler = MouseHandler;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/browser_focus', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/event', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var event = require("pilot/event");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
/**
* This class keeps track of the focus state of the given window.
* Focus changes for example when the user switches a browser tab,
* goes to the location bar or switches to another application.
*/
var BrowserFocus = function(win) {
win = win || window;
this.lastFocus = new Date().getTime();
this._isFocused = true;
var _self = this;
event.addListener(win, "blur", function(e) {
_self._setFocused(false);
});
event.addListener(win, "focus", function(e) {
_self._setFocused(true);
});
};
(function(){
oop.implement(this, EventEmitter);
this.isFocused = function() {
return this._isFocused;
};
this._setFocused = function(isFocused) {
if (this._isFocused == isFocused)
return;
if (isFocused)
this.lastFocus = new Date().getTime();
this._isFocused = isFocused;
this._emit("changeFocus");
};
}).call(BrowserFocus.prototype);
exports.BrowserFocus = BrowserFocus;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/keyboard/keybinding', ['require', 'exports', 'module' , 'pilot/useragent', 'pilot/keys', 'pilot/event', 'pilot/settings', 'pilot/canon', 'ace/commands/default_commands'], function(require, exports, module) {
var useragent = require("pilot/useragent");
var keyUtil = require("pilot/keys");
var event = require("pilot/event");
var settings = require("pilot/settings").settings;
var canon = require("pilot/canon");
require("ace/commands/default_commands");
var KeyBinding = function(editor) {
this.$editor = editor;
this.$data = { };
this.$keyboardHandler = null;
};
(function() {
this.setKeyboardHandler = function(keyboardHandler) {
if (this.$keyboardHandler != keyboardHandler) {
this.$data = { };
this.$keyboardHandler = keyboardHandler;
}
};
this.getKeyboardHandler = function() {
return this.$keyboardHandler;
};
this.$callKeyboardHandler = function (e, hashId, keyOrText, keyCode) {
var env = {editor: this.$editor},
toExecute;
if (this.$keyboardHandler) {
toExecute =
this.$keyboardHandler.handleKeyboard(this.$data, hashId, keyOrText, keyCode, e);
}
// If there is nothing to execute yet, then use the default keymapping.
if (!toExecute || !toExecute.command) {
if (hashId != 0 || keyCode != 0) {
toExecute = {
command: canon.findKeyCommand(env, "editor", hashId, keyOrText)
}
} else {
toExecute = {
command: "inserttext",
args: {
text: keyOrText
}
}
}
}
var success = false;
if (toExecute) {
success = canon.exec(toExecute.command,
env, "editor", toExecute.args);
if (success) {
event.stopEvent(e);
}
}
return success;
};
this.onCommandKey = function(e, hashId, keyCode, keyString) {
// In case there is no keyString, try to interprete the keyCode.
if (!keyString) {
keyString = keyUtil.keyCodeToString(keyCode);
}
return this.$callKeyboardHandler(e, hashId, keyString, keyCode);
};
this.onTextInput = function(text) {
return this.$callKeyboardHandler({}, 0, text, 0);
}
}).call(KeyBinding.prototype);
exports.KeyBinding = KeyBinding;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
* Mihai Sucan <mihai.sucan@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/commands/default_commands', ['require', 'exports', 'module' , 'pilot/lang', 'pilot/canon'], function(require, exports, module) {
var lang = require("pilot/lang");
var canon = require("pilot/canon");
function bindKey(win, mac) {
return {
win: win,
mac: mac,
sender: "editor"
};
}
canon.addCommand({
name: "null",
exec: function(env, args, request) { }
});
canon.addCommand({
name: "selectall",
bindKey: bindKey("Ctrl-A", "Command-A"),
exec: function(env, args, request) { env.editor.selectAll(); }
});
canon.addCommand({
name: "removeline",
bindKey: bindKey("Ctrl-D", "Command-D"),
exec: function(env, args, request) { env.editor.removeLines(); }
});
canon.addCommand({
name: "gotoline",
bindKey: bindKey("Ctrl-L", "Command-L"),
exec: function(env, args, request) {
var line = parseInt(prompt("Enter line number:"));
if (!isNaN(line)) {
env.editor.gotoLine(line);
}
}
});
canon.addCommand({
name: "togglecomment",
bindKey: bindKey("Ctrl-7", "Command-7"),
exec: function(env, args, request) { env.editor.toggleCommentLines(); }
});
canon.addCommand({
name: "findnext",
bindKey: bindKey("Ctrl-K", "Command-G"),
exec: function(env, args, request) { env.editor.findNext(); }
});
canon.addCommand({
name: "findprevious",
bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"),
exec: function(env, args, request) { env.editor.findPrevious(); }
});
canon.addCommand({
name: "find",
bindKey: bindKey("Ctrl-F", "Command-F"),
exec: function(env, args, request) {
var needle = prompt("Find:");
env.editor.find(needle);
}
});
canon.addCommand({
name: "replace",
bindKey: bindKey("Ctrl-R", "Command-Option-F"),
exec: function(env, args, request) {
var needle = prompt("Find:");
if (!needle)
return;
var replacement = prompt("Replacement:");
if (!replacement)
return;
env.editor.replace(replacement, {needle: needle});
}
});
canon.addCommand({
name: "replaceall",
bindKey: bindKey("Ctrl-Shift-R", "Command-Shift-Option-F"),
exec: function(env, args, request) {
var needle = prompt("Find:");
if (!needle)
return;
var replacement = prompt("Replacement:");
if (!replacement)
return;
env.editor.replaceAll(replacement, {needle: needle});
}
});
canon.addCommand({
name: "undo",
bindKey: bindKey("Ctrl-Z", "Command-Z"),
exec: function(env, args, request) { env.editor.undo(); }
});
canon.addCommand({
name: "redo",
bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"),
exec: function(env, args, request) { env.editor.redo(); }
});
canon.addCommand({
name: "overwrite",
bindKey: bindKey("Insert", "Insert"),
exec: function(env, args, request) { env.editor.toggleOverwrite(); }
});
canon.addCommand({
name: "copylinesup",
bindKey: bindKey("Ctrl-Alt-Up", "Command-Option-Up"),
exec: function(env, args, request) { env.editor.copyLinesUp(); }
});
canon.addCommand({
name: "movelinesup",
bindKey: bindKey("Alt-Up", "Option-Up"),
exec: function(env, args, request) { env.editor.moveLinesUp(); }
});
canon.addCommand({
name: "selecttostart",
bindKey: bindKey("Ctrl-Shift-Home|Alt-Shift-Up", "Command-Shift-Up"),
exec: function(env, args, request) { env.editor.getSelection().selectFileStart(); }
});
canon.addCommand({
name: "gotostart",
bindKey: bindKey("Ctrl-Home|Ctrl-Up", "Command-Home|Command-Up"),
exec: function(env, args, request) { env.editor.navigateFileStart(); }
});
canon.addCommand({
name: "selectup",
bindKey: bindKey("Shift-Up", "Shift-Up"),
exec: function(env, args, request) { env.editor.getSelection().selectUp(); }
});
canon.addCommand({
name: "golineup",
bindKey: bindKey("Up", "Up|Ctrl-P"),
exec: function(env, args, request) { env.editor.navigateUp(args.times); }
});
canon.addCommand({
name: "copylinesdown",
bindKey: bindKey("Ctrl-Alt-Down", "Command-Option-Down"),
exec: function(env, args, request) { env.editor.copyLinesDown(); }
});
canon.addCommand({
name: "movelinesdown",
bindKey: bindKey("Alt-Down", "Option-Down"),
exec: function(env, args, request) { env.editor.moveLinesDown(); }
});
canon.addCommand({
name: "selecttoend",
bindKey: bindKey("Ctrl-Shift-End|Alt-Shift-Down", "Command-Shift-Down"),
exec: function(env, args, request) { env.editor.getSelection().selectFileEnd(); }
});
canon.addCommand({
name: "gotoend",
bindKey: bindKey("Ctrl-End|Ctrl-Down", "Command-End|Command-Down"),
exec: function(env, args, request) { env.editor.navigateFileEnd(); }
});
canon.addCommand({
name: "selectdown",
bindKey: bindKey("Shift-Down", "Shift-Down"),
exec: function(env, args, request) { env.editor.getSelection().selectDown(); }
});
canon.addCommand({
name: "golinedown",
bindKey: bindKey("Down", "Down|Ctrl-N"),
exec: function(env, args, request) { env.editor.navigateDown(args.times); }
});
canon.addCommand({
name: "selectwordleft",
bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"),
exec: function(env, args, request) { env.editor.getSelection().selectWordLeft(); }
});
canon.addCommand({
name: "gotowordleft",
bindKey: bindKey("Ctrl-Left", "Option-Left"),
exec: function(env, args, request) { env.editor.navigateWordLeft(); }
});
canon.addCommand({
name: "selecttolinestart",
bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left"),
exec: function(env, args, request) { env.editor.getSelection().selectLineStart(); }
});
canon.addCommand({
name: "gotolinestart",
bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"),
exec: function(env, args, request) { env.editor.navigateLineStart(); }
});
canon.addCommand({
name: "selectleft",
bindKey: bindKey("Shift-Left", "Shift-Left"),
exec: function(env, args, request) { env.editor.getSelection().selectLeft(); }
});
canon.addCommand({
name: "gotoleft",
bindKey: bindKey("Left", "Left|Ctrl-B"),
exec: function(env, args, request) { env.editor.navigateLeft(args.times); }
});
canon.addCommand({
name: "selectwordright",
bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"),
exec: function(env, args, request) { env.editor.getSelection().selectWordRight(); }
});
canon.addCommand({
name: "gotowordright",
bindKey: bindKey("Ctrl-Right", "Option-Right"),
exec: function(env, args, request) { env.editor.navigateWordRight(); }
});
canon.addCommand({
name: "selecttolineend",
bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right"),
exec: function(env, args, request) { env.editor.getSelection().selectLineEnd(); }
});
canon.addCommand({
name: "gotolineend",
bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"),
exec: function(env, args, request) { env.editor.navigateLineEnd(); }
});
canon.addCommand({
name: "selectright",
bindKey: bindKey("Shift-Right", "Shift-Right"),
exec: function(env, args, request) { env.editor.getSelection().selectRight(); }
});
canon.addCommand({
name: "gotoright",
bindKey: bindKey("Right", "Right|Ctrl-F"),
exec: function(env, args, request) { env.editor.navigateRight(args.times); }
});
canon.addCommand({
name: "selectpagedown",
bindKey: bindKey("Shift-PageDown", "Shift-PageDown"),
exec: function(env, args, request) { env.editor.selectPageDown(); }
});
canon.addCommand({
name: "pagedown",
bindKey: bindKey(null, "PageDown"),
exec: function(env, args, request) { env.editor.scrollPageDown(); }
});
canon.addCommand({
name: "gotopagedown",
bindKey: bindKey("PageDown", "Option-PageDown|Ctrl-V"),
exec: function(env, args, request) { env.editor.gotoPageDown(); }
});
canon.addCommand({
name: "selectpageup",
bindKey: bindKey("Shift-PageUp", "Shift-PageUp"),
exec: function(env, args, request) { env.editor.selectPageUp(); }
});
canon.addCommand({
name: "pageup",
bindKey: bindKey(null, "PageUp"),
exec: function(env, args, request) { env.editor.scrollPageUp(); }
});
canon.addCommand({
name: "gotopageup",
bindKey: bindKey("PageUp", "Option-PageUp"),
exec: function(env, args, request) { env.editor.gotoPageUp(); }
});
canon.addCommand({
name: "selectlinestart",
bindKey: bindKey("Shift-Home", "Shift-Home"),
exec: function(env, args, request) { env.editor.getSelection().selectLineStart(); }
});
canon.addCommand({
name: "selectlineend",
bindKey: bindKey("Shift-End", "Shift-End"),
exec: function(env, args, request) { env.editor.getSelection().selectLineEnd(); }
});
canon.addCommand({
name: "del",
bindKey: bindKey("Delete", "Delete|Ctrl-D"),
exec: function(env, args, request) { env.editor.removeRight(); }
});
canon.addCommand({
name: "backspace",
bindKey: bindKey(
"Ctrl-Backspace|Command-Backspace|Option-Backspace|Shift-Backspace|Backspace",
"Ctrl-Backspace|Command-Backspace|Shift-Backspace|Backspace|Ctrl-H"
),
exec: function(env, args, request) { env.editor.removeLeft(); }
});
canon.addCommand({
name: "removetolinestart",
bindKey: bindKey(null, "Option-Backspace"),
exec: function(env, args, request) { env.editor.removeToLineStart(); }
});
canon.addCommand({
name: "removetolineend",
bindKey: bindKey(null, "Ctrl-K"),
exec: function(env, args, request) { env.editor.removeToLineEnd(); }
});
canon.addCommand({
name: "removewordleft",
bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"),
exec: function(env, args, request) { env.editor.removeWordLeft(); }
});
canon.addCommand({
name: "removewordright",
bindKey: bindKey(null, "Alt-Delete"),
exec: function(env, args, request) { env.editor.removeWordRight(); }
});
canon.addCommand({
name: "outdent",
bindKey: bindKey("Shift-Tab", "Shift-Tab"),
exec: function(env, args, request) { env.editor.blockOutdent(); }
});
canon.addCommand({
name: "indent",
bindKey: bindKey("Tab", "Tab"),
exec: function(env, args, request) { env.editor.indent(); }
});
canon.addCommand({
name: "inserttext",
exec: function(env, args, request) {
env.editor.insert(lang.stringRepeat(args.text || "", args.times || 1));
}
});
canon.addCommand({
name: "centerselection",
bindKey: bindKey(null, "Ctrl-L"),
exec: function(env, args, request) { env.editor.centerSelection(); }
});
canon.addCommand({
name: "splitline",
bindKey: bindKey(null, "Ctrl-O"),
exec: function(env, args, request) { env.editor.splitLine(); }
});
canon.addCommand({
name: "transposeletters",
bindKey: bindKey("Ctrl-T", "Ctrl-T"),
exec: function(env, args, request) { env.editor.transposeLetters(); }
});
});/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/edit_session', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/lang', 'pilot/event_emitter', 'ace/selection', 'ace/mode/text', 'ace/range', 'ace/document', 'ace/background_tokenizer', 'ace/edit_session/folding'], function(require, exports, module) {
var oop = require("pilot/oop");
var lang = require("pilot/lang");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Selection = require("ace/selection").Selection;
var TextMode = require("ace/mode/text").Mode;
var Range = require("ace/range").Range;
var Document = require("ace/document").Document;
var BackgroundTokenizer = require("ace/background_tokenizer").BackgroundTokenizer;
var EditSession = function(text, mode) {
this.$modified = true;
this.$breakpoints = [];
this.$frontMarkers = {};
this.$backMarkers = {};
this.$markerId = 1;
this.$rowCache = [];
this.$wrapData = [];
this.$foldData = [];
this.$foldData.toString = function() {
var str = "";
this.forEach(function(foldLine) {
str += "\n" + foldLine.toString();
});
return str;
}
if (text instanceof Document) {
this.setDocument(text);
} else {
this.setDocument(new Document(text));
}
this.selection = new Selection(this);
if (mode)
this.setMode(mode);
else
this.setMode(new TextMode());
};
(function() {
oop.implement(this, EventEmitter);
this.setDocument = function(doc) {
if (this.doc)
throw new Error("Document is already set");
this.doc = doc;
doc.on("change", this.onChange.bind(this));
this.on("changeFold", this.onChangeFold.bind(this));
};
this.getDocument = function() {
return this.doc;
};
this.$resetRowCache = function(row) {
if (row == 0) {
this.$rowCache = [];
return;
}
var rowCache = this.$rowCache;
for (var i = 0; i < rowCache.length; i++) {
if (rowCache[i].docRow >= row) {
rowCache.splice(i, rowCache.length);
return;
}
}
};
this.onChangeFold = function(e) {
var fold = e.data;
this.$resetRowCache(fold.start.row);
};
this.onChange = function(e) {
var delta = e.data;
this.$modified = true;
this.$resetRowCache(delta.range.start.row);
var removedFolds = this.$updateInternalDataOnChange(e);
if (!this.$fromUndo && this.$undoManager && !delta.ignore) {
this.$deltasDoc.push(delta);
if (removedFolds && removedFolds.length != 0) {
this.$deltasFold.push({
action: "removeFolds",
folds: removedFolds
});
}
this.$informUndoManager.schedule();
}
this.bgTokenizer.start(delta.range.start.row);
this._dispatchEvent("change", e);
};
this.setValue = function(text) {
this.doc.setValue(text);
this.selection.moveCursorTo(0, 0);
this.selection.clearSelection();
this.$resetRowCache(0);
this.$deltas = [];
this.$deltasDoc = [];
this.$deltasFold = [];
this.getUndoManager().reset();
};
this.getValue =
this.toString = function() {
return this.doc.getValue();
};
this.getSelection = function() {
return this.selection;
};
this.getState = function(row) {
return this.bgTokenizer.getState(row);
};
this.getTokens = function(firstRow, lastRow) {
return this.bgTokenizer.getTokens(firstRow, lastRow);
};
this.setUndoManager = function(undoManager) {
this.$undoManager = undoManager;
this.$resetRowCache(0);
this.$deltas = [];
this.$deltasDoc = [];
this.$deltasFold = [];
if (this.$informUndoManager)
this.$informUndoManager.cancel();
if (undoManager) {
var self = this;
this.$syncInformUndoManager = function() {
self.$informUndoManager.cancel();
if (self.$deltasFold.length) {
self.$deltas.push({
group: "fold",
deltas: self.$deltasFold
});
self.$deltasFold = [];
}
if (self.$deltasDoc.length) {
self.$deltas.push({
group: "doc",
deltas: self.$deltasDoc
});
self.$deltasDoc = [];
}
if (self.$deltas.length > 0) {
undoManager.execute({
action: "aceupdate",
args: [self.$deltas, self]
});
}
self.$deltas = [];
}
this.$informUndoManager =
lang.deferredCall(this.$syncInformUndoManager);
}
};
this.$defaultUndoManager = {
undo: function() {},
redo: function() {},
reset: function() {}
};
this.getUndoManager = function() {
return this.$undoManager || this.$defaultUndoManager;
},
this.getTabString = function() {
if (this.getUseSoftTabs()) {
return lang.stringRepeat(" ", this.getTabSize());
} else {
return "\t";
}
};
this.$useSoftTabs = true;
this.setUseSoftTabs = function(useSoftTabs) {
if (this.$useSoftTabs === useSoftTabs) return;
this.$useSoftTabs = useSoftTabs;
};
this.getUseSoftTabs = function() {
return this.$useSoftTabs;
};
this.$tabSize = 4;
this.setTabSize = function(tabSize) {
if (isNaN(tabSize) || this.$tabSize === tabSize) return;
this.$modified = true;
this.$tabSize = tabSize;
this._dispatchEvent("changeTabSize");
};
this.getTabSize = function() {
return this.$tabSize;
};
this.isTabStop = function(position) {
return this.$useSoftTabs && (position.column % this.$tabSize == 0);
};
this.$overwrite = false;
this.setOverwrite = function(overwrite) {
if (this.$overwrite == overwrite) return;
this.$overwrite = overwrite;
this._dispatchEvent("changeOverwrite");
};
this.getOverwrite = function() {
return this.$overwrite;
};
this.toggleOverwrite = function() {
this.setOverwrite(!this.$overwrite);
};
this.getBreakpoints = function() {
return this.$breakpoints;
};
this.setBreakpoints = function(rows) {
this.$breakpoints = [];
for (var i=0; i<rows.length; i++) {
this.$breakpoints[rows[i]] = true;
}
this._dispatchEvent("changeBreakpoint", {});
};
this.clearBreakpoints = function() {
this.$breakpoints = [];
this._dispatchEvent("changeBreakpoint", {});
};
this.setBreakpoint = function(row) {
this.$breakpoints[row] = true;
this._dispatchEvent("changeBreakpoint", {});
};
this.clearBreakpoint = function(row) {
delete this.$breakpoints[row];
this._dispatchEvent("changeBreakpoint", {});
};
this.getBreakpoints = function() {
return this.$breakpoints;
};
this.addMarker = function(range, clazz, type, inFront) {
var id = this.$markerId++;
var marker = {
range : range,
type : type || "line",
renderer: typeof type == "function" ? type : null,
clazz : clazz,
inFront: !!inFront
}
if (inFront) {
this.$frontMarkers[id] = marker;
this._dispatchEvent("changeFrontMarker")
} else {
this.$backMarkers[id] = marker;
this._dispatchEvent("changeBackMarker")
}
return id;
};
this.removeMarker = function(markerId) {
var marker = this.$frontMarkers[markerId] || this.$backMarkers[markerId];
if (!marker)
return;
var markers = marker.inFront ? this.$frontMarkers : this.$backMarkers;
if (marker) {
delete (markers[markerId]);
this._dispatchEvent(marker.inFront ? "changeFrontMarker" : "changeBackMarker");
}
};
this.getMarkers = function(inFront) {
return inFront ? this.$frontMarkers : this.$backMarkers;
};
/**
* Error:
* {
* row: 12,
* column: 2, //can be undefined
* text: "Missing argument",
* type: "error" // or "warning" or "info"
* }
*/
this.setAnnotations = function(annotations) {
this.$annotations = {};
for (var i=0; i<annotations.length; i++) {
var annotation = annotations[i];
var row = annotation.row;
if (this.$annotations[row])
this.$annotations[row].push(annotation);
else
this.$annotations[row] = [annotation];
}
this._dispatchEvent("changeAnnotation", {});
};
this.getAnnotations = function() {
return this.$annotations;
};
this.clearAnnotations = function() {
this.$annotations = {};
this._dispatchEvent("changeAnnotation", {});
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r?\n)/m);
if (match) {
this.$autoNewLine = match[1];
} else {
this.$autoNewLine = "\n";
}
};
this.getWordRange = function(row, column) {
var line = this.getLine(row);
var inToken = false;
if (column > 0) {
inToken = !!line.charAt(column - 1).match(this.tokenRe);
}
if (!inToken) {
inToken = !!line.charAt(column).match(this.tokenRe);
}
var re = inToken ? this.tokenRe : this.nonTokenRe;
var start = column;
if (start > 0) {
do {
start--;
}
while (start >= 0 && line.charAt(start).match(re));
start++;
}
var end = column;
while (end < line.length && line.charAt(end).match(re)) {
end++;
}
return new Range(row, start, row, end);
};
this.setNewLineMode = function(newLineMode) {
this.doc.setNewLineMode(newLineMode);
};
this.getNewLineMode = function() {
return this.doc.getNewLineMode();
};
this.$useWorker = true;
this.setUseWorker = function(useWorker) {
if (this.$useWorker == useWorker)
return;
this.$useWorker = useWorker;
this.$stopWorker();
if (useWorker)
this.$startWorker();
};
this.getUseWorker = function() {
return this.$useWorker;
};
this.onReloadTokenizer = function(e) {
var rows = e.data;
this.bgTokenizer.start(rows.first);
this._dispatchEvent("tokenizerUpdate", e);
};
this.$mode = null;
this.setMode = function(mode) {
if (this.$mode === mode) return;
this.$mode = mode;
this.$stopWorker();
if (this.$useWorker)
this.$startWorker();
var tokenizer = mode.getTokenizer();
if(tokenizer.addEventListener !== undefined) {
var onReloadTokenizer = this.onReloadTokenizer.bind(this);
tokenizer.addEventListener("update", onReloadTokenizer);
}
if (!this.bgTokenizer) {
this.bgTokenizer = new BackgroundTokenizer(tokenizer);
var _self = this;
this.bgTokenizer.addEventListener("update", function(e) {
_self._dispatchEvent("tokenizerUpdate", e);
});
} else {
this.bgTokenizer.setTokenizer(tokenizer);
}
this.bgTokenizer.setDocument(this.getDocument());
this.bgTokenizer.start(0);
this.tokenRe = mode.tokenRe;
this.nonTokenRe = mode.nonTokenRe;
this._dispatchEvent("changeMode");
};
this.$stopWorker = function() {
if (this.$worker)
this.$worker.terminate();
this.$worker = null;
};
this.$startWorker = function() {
if (typeof Worker !== "undefined" && !require.noWorker) {
try {
this.$worker = this.$mode.createWorker(this);
} catch (e) {
console.log("Could not load worker");
console.log(e);
this.$worker = null;
}
}
else
this.$worker = null;
};
this.getMode = function() {
return this.$mode;
};
this.$scrollTop = 0;
this.setScrollTopRow = function(scrollTopRow) {
if (this.$scrollTop === scrollTopRow) return;
this.$scrollTop = scrollTopRow;
this._dispatchEvent("changeScrollTop");
};
this.getScrollTopRow = function() {
return this.$scrollTop;
};
this.getWidth = function() {
this.$computeWidth();
return this.width;
};
this.getScreenWidth = function() {
this.$computeWidth();
return this.screenWidth;
};
this.$computeWidth = function(force) {
if (this.$modified || force) {
this.$modified = false;
var lines = this.doc.getAllLines();
var longestLine = 0;
var longestScreenLine = 0;
for ( var i = 0; i < lines.length; i++) {
var foldLine = this.getFoldLine(i),
line, len;
line = lines[i];
if (foldLine) {
var end = foldLine.range.end;
line = this.getFoldDisplayLine(foldLine);
// Continue after the foldLine.end.row. All the lines in
// between are folded.
i = end.row;
}
len = line.length;
longestLine = Math.max(longestLine, len);
if (!this.$useWrapMode) {
longestScreenLine = Math.max(
longestScreenLine,
this.$getStringScreenWidth(line)[0]
);
}
}
this.width = longestLine;
if (this.$useWrapMode) {
this.screenWidth = this.$wrapLimit;
} else {
this.screenWidth = longestScreenLine;
}
}
};
/**
* Get a verbatim copy of the given line as it is in the document
*/
this.getLine = function(row) {
return this.doc.getLine(row);
};
this.getLines = function(firstRow, lastRow) {
return this.doc.getLines(firstRow, lastRow);
};
this.getLength = function() {
return this.doc.getLength();
};
this.getTextRange = function(range) {
return this.doc.getTextRange(range);
};
this.findMatchingBracket = function(position) {
if (position.column == 0) return null;
var charBeforeCursor = this.getLine(position.row).charAt(position.column-1);
if (charBeforeCursor == "") return null;
var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/);
if (!match) {
return null;
}
if (match[1]) {
return this.$findClosingBracket(match[1], position);
} else {
return this.$findOpeningBracket(match[2], position);
}
};
this.$brackets = {
")": "(",
"(": ")",
"]": "[",
"[": "]",
"{": "}",
"}": "{"
};
this.$findOpeningBracket = function(bracket, position) {
var openBracket = this.$brackets[bracket];
var column = position.column - 2;
var row = position.row;
var depth = 1;
var line = this.getLine(row);
while (true) {
while(column >= 0) {
var ch = line.charAt(column);
if (ch == openBracket) {
depth -= 1;
if (depth == 0) {
return {row: row, column: column};
}
}
else if (ch == bracket) {
depth +=1;
}
column -= 1;
}
row -=1;
if (row < 0) break;
var line = this.getLine(row);
var column = line.length-1;
}
return null;
};
this.$findClosingBracket = function(bracket, position) {
var closingBracket = this.$brackets[bracket];
var column = position.column;
var row = position.row;
var depth = 1;
var line = this.getLine(row);
var lineCount = this.getLength();
while (true) {
while(column < line.length) {
var ch = line.charAt(column);
if (ch == closingBracket) {
depth -= 1;
if (depth == 0) {
return {row: row, column: column};
}
}
else if (ch == bracket) {
depth +=1;
}
column += 1;
}
row +=1;
if (row >= lineCount) break;
var line = this.getLine(row);
var column = 0;
}
return null;
};
this.insert = function(position, text) {
return this.doc.insert(position, text);
};
this.remove = function(range) {
return this.doc.remove(range);
};
this.undoChanges = function(deltas, dontSelect) {
if (!deltas.length)
return;
this.$fromUndo = true;
var lastUndoRange = null;
for (var i = deltas.length - 1; i != -1; i--) {
delta = deltas[i];
if (delta.group == "doc") {
this.doc.revertDeltas(delta.deltas);
lastUndoRange =
this.$getUndoSelection(delta.deltas, true, lastUndoRange);
} else {
delta.deltas.forEach(function(foldDelta) {
this.addFolds(foldDelta.folds);
}, this);
}
}
this.$fromUndo = false;
lastUndoRange &&
!dontSelect &&
this.selection.setSelectionRange(lastUndoRange);
return lastUndoRange;
},
this.redoChanges = function(deltas, dontSelect) {
if (!deltas.length)
return;
this.$fromUndo = true;
var lastUndoRange = null;
for (var i = 0; i < deltas.length; i++) {
delta = deltas[i];
if (delta.group == "doc") {
this.doc.applyDeltas(delta.deltas);
lastUndoRange =
this.$getUndoSelection(delta.deltas, false, lastUndoRange);
}
}
this.$fromUndo = false;
lastUndoRange &&
!dontSelect &&
this.selection.setSelectionRange(lastUndoRange);
return lastUndoRange;
},
this.$getUndoSelection = function(deltas, isUndo, lastUndoRange) {
function isInsert(delta) {
var insert =
delta.action == "insertText" || delta.action == "insertLines";
return isUndo ? !insert : insert;
}
var delta = deltas[0];
var range, point;
var lastDeltaIsInsert = false;
if (isInsert(delta)) {
range = delta.range.clone();
lastDeltaIsInsert = true;
} else {
range = Range.fromPoints(delta.range.start, delta.range.start);
lastDeltaIsInsert = false;
}
for (var i = 1; i < deltas.length; i++) {
delta = deltas[i];
if (isInsert(delta)) {
point = delta.range.start;
if (range.compare(point.row, point.column) == -1) {
range.setStart(delta.range.start);
}
point = delta.range.end;
if (range.compare(point.row, point.column) == 1) {
range.setEnd(delta.range.end);
}
lastDeltaIsInsert = true;
} else {
point = delta.range.start;
if (range.compare(point.row, point.column) == -1) {
range =
Range.fromPoints(delta.range.start, delta.range.start);
}
lastDeltaIsInsert = false;
}
}
// Check if this range and the last undo range has something in common.
// If true, merge the ranges.
if (lastUndoRange != null) {
var cmp = lastUndoRange.compareRange(range);
if (cmp == 1) {
range.setStart(lastUndoRange.start);
} else if (cmp == -1) {
range.setEnd(lastUndoRange.end);
}
}
return range;
},
this.replace = function(range, text) {
return this.doc.replace(range, text);
};
/**
* Move a range of text from the given range to the given position.
*
* @param fromRange {Range} The range of text you want moved within the
* document.
* @param toPosition {Object} The location (row and column) where you want
* to move the text to.
* @return {Range} The new range where the text was moved to.
*/
this.moveText = function(fromRange, toPosition) {
var text = this.getTextRange(fromRange);
this.remove(fromRange);
var toRow = toPosition.row;
var toColumn = toPosition.column;
// Make sure to update the insert location, when text is removed in
// front of the chosen point of insertion.
if (!fromRange.isMultiLine() && fromRange.start.row == toRow &&
fromRange.end.column < toColumn)
toColumn -= text.length;
if (fromRange.isMultiLine() && fromRange.end.row < toRow) {
var lines = this.doc.$split(text);
toRow -= lines.length - 1;
}
var endRow = toRow + fromRange.end.row - fromRange.start.row;
var endColumn = fromRange.isMultiLine() ?
fromRange.end.column :
toColumn + fromRange.end.column - fromRange.start.column;
var toRange = new Range(toRow, toColumn, endRow, endColumn);
this.insert(toRange.start, text);
return toRange;
};
this.indentRows = function(startRow, endRow, indentString) {
indentString = indentString.replace(/\t/g, this.getTabString());
for (var row=startRow; row<=endRow; row++) {
this.insert({row: row, column:0}, indentString);
}
};
this.outdentRows = function (range) {
var rowRange = range.collapseRows();
var deleteRange = new Range(0, 0, 0, 0);
var size = this.getTabSize();
for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) {
var line = this.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
for (var j = 0; j < size; ++j)
if (line.charAt(j) != ' ')
break;
if (j < size && line.charAt(j) == '\t') {
deleteRange.start.column = j;
deleteRange.end.column = j + 1;
} else {
deleteRange.start.column = 0;
deleteRange.end.column = j;
}
this.remove(deleteRange);
}
};
this.moveLinesUp = function(firstRow, lastRow) {
if (firstRow <= 0) return 0;
var removed = this.doc.removeLines(firstRow, lastRow);
this.doc.insertLines(firstRow - 1, removed);
return -1;
};
this.moveLinesDown = function(firstRow, lastRow) {
if (lastRow >= this.doc.getLength()-1) return 0;
var removed = this.doc.removeLines(firstRow, lastRow);
this.doc.insertLines(firstRow+1, removed);
return 1;
};
this.duplicateLines = function(firstRow, lastRow) {
var firstRow = this.$clipRowToDocument(firstRow);
var lastRow = this.$clipRowToDocument(lastRow);
var lines = this.getLines(firstRow, lastRow);
this.doc.insertLines(firstRow, lines);
var addedRows = lastRow - firstRow + 1;
return addedRows;
};
this.$clipRowToDocument = function(row) {
return Math.max(0, Math.min(row, this.doc.getLength()-1));
};
this.$clipPositionToDocument = function(row, column) {
column = Math.max(0, column);
if (row < 0) {
row = 0;
column = 0;
} else {
var len = this.doc.getLength();
if (row >= len) {
row = len - 1;
column = this.doc.getLine(len-1).length;
} else {
column = Math.min(this.doc.getLine(row).length, column);
}
}
return {
row: row,
column: column
};
};
// WRAPMODE
this.$wrapLimit = 80;
this.$useWrapMode = false;
this.$wrapLimitRange = {
min : null,
max : null
};
this.setUseWrapMode = function(useWrapMode) {
if (useWrapMode != this.$useWrapMode) {
this.$useWrapMode = useWrapMode;
this.$modified = true;
this.$resetRowCache(0);
// If wrapMode is activaed, the wrapData array has to be initialized.
if (useWrapMode) {
var len = this.getLength();
this.$wrapData = [];
for (i = 0; i < len; i++) {
this.$wrapData.push([]);
}
this.$updateWrapData(0, len - 1);
}
this._dispatchEvent("changeWrapMode");
}
};
this.getUseWrapMode = function() {
return this.$useWrapMode;
};
// Allow the wrap limit to move freely between min and max. Either
// parameter can be null to allow the wrap limit to be unconstrained
// in that direction. Or set both parameters to the same number to pin
// the limit to that value.
this.setWrapLimitRange = function(min, max) {
if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) {
this.$wrapLimitRange.min = min;
this.$wrapLimitRange.max = max;
this.$modified = true;
// This will force a recalculation of the wrap limit
this._dispatchEvent("changeWrapMode");
}
};
// This should generally only be called by the renderer when a resize
// is detected.
this.adjustWrapLimit = function(desiredLimit) {
var wrapLimit = this.$constrainWrapLimit(desiredLimit);
if (wrapLimit != this.$wrapLimit && wrapLimit > 0) {
this.$wrapLimit = wrapLimit;
this.$modified = true;
if (this.$useWrapMode) {
this.$updateWrapData(0, this.getLength() - 1);
this.$resetRowCache(0)
this._dispatchEvent("changeWrapLimit");
}
return true;
}
return false;
};
this.$constrainWrapLimit = function(wrapLimit) {
var min = this.$wrapLimitRange.min;
if (min)
wrapLimit = Math.max(min, wrapLimit);
var max = this.$wrapLimitRange.max;
if (max)
wrapLimit = Math.min(max, wrapLimit);
// What would a limit of 0 even mean?
return Math.max(1, wrapLimit);
};
this.getWrapLimit = function() {
return this.$wrapLimit;
};
this.getWrapLimitRange = function() {
// Avoid unexpected mutation by returning a copy
return {
min : this.$wrapLimitRange.min,
max : this.$wrapLimitRange.max
};
};
this.$updateInternalDataOnChange = function(e) {
var useWrapMode = this.$useWrapMode;
var len;
var action = e.data.action;
var firstRow = e.data.range.start.row,
lastRow = e.data.range.end.row,
start = e.data.range.start,
end = e.data.range.end;
var removedFolds = null;
if (action.indexOf("Lines") != -1) {
if (action == "insertLines") {
lastRow = firstRow + (e.data.lines.length);
} else {
lastRow = firstRow;
}
len = e.data.lines.length;
} else {
len = lastRow - firstRow;
}
if (len != 0) {
if (action.indexOf("remove") != -1) {
useWrapMode && this.$wrapData.splice(firstRow, len);
var foldLines = this.$foldData;
removedFolds = this.getFoldsInRange(e.data.range);
this.removeFolds(removedFolds);
var foldLine = this.getFoldLine(end.row);
var idx = 0;
if (foldLine) {
foldLine.addRemoveChars(end.row, end.column, start.column - end.column);
foldLine.shiftRow(-len);
var foldLineBefore = this.getFoldLine(firstRow);
if (foldLineBefore && foldLineBefore !== foldLine) {
foldLineBefore.merge(foldLine);
foldLine = foldLineBefore;
}
idx = foldLines.indexOf(foldLine) + 1;
}
for (idx; idx < foldLines.length; idx++) {
var foldLine = foldLines[idx];
if (foldLine.start.row >= end.row) {
foldLine.shiftRow(-len);
}
}
lastRow = firstRow;
} else {
var args;
if (useWrapMode) {
args = [firstRow, 0];
for (var i = 0; i < len; i++) args.push([]);
this.$wrapData.splice.apply(this.$wrapData, args);
}
// If some new line is added inside of a foldLine, then split
// the fold line up.
var foldLines = this.$foldData;
var foldLine = this.getFoldLine(firstRow);
var idx = 0;
if (foldLine) {
var cmp = foldLine.range.compareInside(start.row, start.column)
// Inside of the foldLine range. Need to split stuff up.
if (cmp == 0) {
foldLine = foldLine.split(start.row, start.column);
foldLine.shiftRow(len);
foldLine.addRemoveChars(
lastRow, 0, end.column - start.column);
} else
// Infront of the foldLine but same row. Need to shift column.
if (cmp == -1) {
foldLine.addRemoveChars(firstRow, 0, end.column - start.column);
foldLine.shiftRow(len);
}
// Nothing to do if the insert is after the foldLine.
idx = foldLines.indexOf(foldLine) + 1;
}
for (idx; idx < foldLines.length; idx++) {
var foldLine = foldLines[idx];
if (foldLine.start.row >= firstRow) {
foldLine.shiftRow(len);
}
}
}
} else {
// Realign folds. E.g. if you add some new chars before a fold, the
// fold should "move" to the right.
var column;
len = Math.abs(e.data.range.start.column - e.data.range.end.column);
if (action.indexOf("remove") != -1) {
// Get all the folds in the change range and remove them.
removedFolds = this.getFoldsInRange(e.data.range);
this.removeFolds(removedFolds);
len = -len;
}
var foldLine = this.getFoldLine(firstRow);
if (foldLine) {
foldLine.addRemoveChars(firstRow, start.column, len);
}
}
if (useWrapMode && this.$wrapData.length != this.doc.getLength()) {
console.error("doc.getLength() and $wrapData.length have to be the same!");
}
useWrapMode && this.$updateWrapData(firstRow, lastRow);
return removedFolds;
};
this.$updateWrapData = function(firstRow, lastRow) {
var lines = this.doc.getAllLines();
var tabSize = this.getTabSize();
var wrapData = this.$wrapData;
var wrapLimit = this.$wrapLimit;
var tokens;
var foldLine;
var row = firstRow;
lastRow = Math.min(lastRow, lines.length - 1);
while (row <= lastRow) {
foldLine = this.getFoldLine(row);
if (!foldLine) {
tokens = this.$getDisplayTokens(lang.stringTrimRight(lines[row]));
} else {
tokens = [];
foldLine.walk(
function(placeholder, row, column, lastColumn) {
var walkTokens;
if (placeholder) {
walkTokens = this.$getDisplayTokens(
placeholder, tokens.length);
walkTokens[0] = PLACEHOLDER_START;
for (var i = 1; i < walkTokens.length; i++) {
walkTokens[i] = PLACEHOLDER_BODY;
}
} else {
walkTokens = this.$getDisplayTokens(
lines[row].substring(lastColumn, column),
tokens.length);
}
tokens = tokens.concat(walkTokens);
}.bind(this),
foldLine.end.row,
lines[foldLine.end.row].length + 1
);
// Remove spaces/tabs from the back of the token array.
while (tokens.length != 0
&& tokens[tokens.length - 1] >= SPACE)
{
tokens.pop();
}
}
wrapData[row] =
this.$computeWrapSplits(tokens, wrapLimit, tabSize);
row = this.getRowFoldEnd(row) + 1;
}
};
// "Tokens"
var CHAR = 1,
CHAR_EXT = 2,
PLACEHOLDER_START = 3,
PLACEHOLDER_BODY = 4,
SPACE = 10,
TAB = 11,
TAB_SPACE = 12;
this.$computeWrapSplits = function(tokens, wrapLimit, tabSize) {
if (tokens.length == 0) {
return [];
}
var tabSize = this.getTabSize();
var splits = [];
var displayLength = tokens.length;
var lastSplit = 0, lastDocSplit = 0;
function addSplit(screenPos) {
var displayed = tokens.slice(lastSplit, screenPos);
// The document size is the current size - the extra width for tabs
// and multipleWidth characters.
var len = displayed.length;
displayed.join("").
// Get all the TAB_SPACEs.
replace(/12/g, function(m) {
len -= 1;
}).
// Get all the CHAR_EXT/multipleWidth characters.
replace(/2/g, function(m) {
len -= 1;
});
lastDocSplit += len;
splits.push(lastDocSplit);
lastSplit = screenPos;
}
while (displayLength - lastSplit > wrapLimit) {
// This is, where the split should be.
var split = lastSplit + wrapLimit;
// If there is a space or tab at this split position, then making
// a split is simple.
if (tokens[split] >= SPACE) {
// Include all following spaces + tabs in this split as well.
while (tokens[split] >= SPACE) {
split ++;
}
addSplit(split);
continue;
}
// === ELSE ===
// Check if split is inside of a placeholder. Placeholder are
// not splitable. Therefore, seek the beginning of the placeholder
// and try to place the split beofre the placeholder's start.
if (tokens[split] == PLACEHOLDER_START
|| tokens[split] == PLACEHOLDER_BODY)
{
// Seek the start of the placeholder and do the split
// before the placeholder. By definition there always
// a PLACEHOLDER_START between split and lastSplit.
for (split; split != lastSplit - 1; split--) {
if (tokens[split] == PLACEHOLDER_START) {
// split++; << No incremental here as we want to
// have the position before the Placeholder.
break;
}
}
// If the PLACEHOLDER_START is not the index of the
// last split, then we can do the split
if (split > lastSplit) {
addSplit(split);
continue;
}
// If the PLACEHOLDER_START IS the index of the last
// split, then we have to place the split after the
// placeholder. So, let's seek for the end of the placeholder.
split = lastSplit + wrapLimit;
for (split; split < tokens.length; split++) {
if (tokens[split] != PLACEHOLDER_BODY)
{
break;
}
}
// If spilt == tokens.length, then the placeholder is the last
// thing in the line and adding a new split doesn't make sense.
if (split == tokens.length) {
break; // Breaks the while-loop.
}
// Finally, add the split...
addSplit(split);
continue;
}
// === ELSE ===
// Search for the first non space/tab/placeholder token backwards.
for (split; split != lastSplit - 1; split--) {
if (tokens[split] >= PLACEHOLDER_START) {
split++;
break;
}
}
// If we found one, then add the split.
if (split > lastSplit) {
addSplit(split);
continue;
}
// === ELSE ===
split = lastSplit + wrapLimit;
// The split is inside of a CHAR or CHAR_EXT token and no space
// around -> force a split.
addSplit(lastSplit + wrapLimit);
}
return splits;
}
/**
* @param
* offset: The offset in screenColumn at which position str starts.
* Important for calculating the realTabSize.
*/
this.$getDisplayTokens = function(str, offset) {
var arr = [];
var tabSize;
offset = offset || 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
// Tab
if (c == 9) {
tabSize = this.getScreenTabSize(arr.length + offset);
arr.push(TAB);
for (var n = 1; n < tabSize; n++) {
arr.push(TAB_SPACE);
}
}
// Space
else if(c == 32) {
arr.push(SPACE);
}
// full width characters
else if (isFullWidth(c)) {
arr.push(CHAR, CHAR_EXT);
} else {
arr.push(CHAR);
}
}
return arr;
}
/**
* Calculates the width of the a string on the screen while assuming that
* the string starts at the first column on the screen.
*
* @param string str String to calculate the screen width of
* @return array
* [0]: number of columns for str on screen.
* [1]: docColumn position that was read until (useful with screenColumn)
*/
this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) {
if (maxScreenColumn == 0) {
return [0, 0];
}
if (maxScreenColumn == null) {
maxScreenColumn = screenColumn +
str.length * Math.max(this.getTabSize(), 2);
}
screenColumn = screenColumn || 0;
var c, column;
for (column = 0; column < str.length; column++) {
c = str.charCodeAt(column);
// tab
if (c == 9) {
screenColumn += this.getScreenTabSize(screenColumn);
}
// full width characters
else if (isFullWidth(c)) {
screenColumn += 2;
} else {
screenColumn += 1;
}
if (screenColumn > maxScreenColumn) {
break
}
}
return [screenColumn, column];
}
/**
* Returns the number of rows required to render this row on the screen
*/
this.getRowLength = function(row) {
if (!this.$useWrapMode || !this.$wrapData[row]) {
return 1;
} else {
return this.$wrapData[row].length + 1;
}
}
/**
* Returns the height in pixels required to render this row on the screen
**/
this.getRowHeight = function(config, row) {
return this.getRowLength(row) * config.lineHeight;
}
this.getScreenLastRowColumn = function(screenRow) {
//return this.screenToDocumentColumn(screenRow, Number.MAX_VALUE / 10)
return this.documentToScreenColumn(screenRow, this.doc.getLine(screenRow).length);
};
this.getDocumentLastRowColumn = function(docRow, docColumn) {
var screenRow = this.documentToScreenRow(docRow, docColumn);
return this.getScreenLastRowColumn(screenRow);
};
this.getDocumentLastRowColumnPosition = function(docRow, docColumn) {
var screenRow = this.documentToScreenRow(docRow, docColumn);
return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10);
};
this.getRowSplitData = function(row) {
if (!this.$useWrapMode) {
return undefined;
} else {
return this.$wrapData[row];
}
};
/**
* Returns the width of a tab character at screenColumn.
*/
this.getScreenTabSize = function(screenColumn) {
return this.$tabSize - screenColumn % this.$tabSize;
};
this.screenToDocumentRow = function(screenRow, screenColumn) {
return this.screenToDocumentPosition(screenRow, screenColumn).row;
};
this.screenToDocumentColumn = function(screenRow, screenColumn) {
return this.screenToDocumentPosition(screenRow, screenColumn).column;
};
this.screenToDocumentPosition = function(screenRow, screenColumn) {
if (screenRow < 0) {
return {
row: 0,
column: 0
}
}
var line;
var docRow = 0;
var docColumn = 0;
var column;
var foldLineRowLength;
var row = 0;
var rowLength = 0;
var rowCache = this.$rowCache;
for (var i = 0; i < rowCache.length; i++) {
if (rowCache[i].screenRow < screenRow) {
row = rowCache[i].screenRow;
docRow = rowCache[i].docRow;
}
else {
break;
}
}
var doCache = !rowCache.length || i == rowCache.length;
// clamp row before clamping column, for selection on last line
var maxRow = this.getLength() - 1;
var foldLine = this.getNextFold(docRow);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (row <= screenRow) {
rowLength = this.getRowLength(docRow);
if (row + rowLength - 1 >= screenRow || docRow >= maxRow) {
break;
} else {
row += rowLength;
docRow++;
if (docRow > foldStart) {
docRow = foldLine.end.row+1;
foldLine = this.getNextFold(docRow);
foldStart = foldLine ? foldLine.start.row : Infinity;
}
}
if (doCache) {
rowCache.push({
docRow: docRow,
screenRow: row
});
}
}
if (foldLine && foldLine.start.row <= docRow)
line = this.getFoldDisplayLine(foldLine);
else {
line = this.getLine(docRow);
foldLine = null;
}
var splits = [];
if (this.$useWrapMode) {
splits = this.$wrapData[docRow];
if (splits) {
column = splits[screenRow - row]
if(screenRow > row && splits.length) {
docColumn = splits[screenRow - row - 1] || splits[splits.length - 1];
line = line.substring(docColumn);
}
}
}
docColumn += this.$getStringScreenWidth(line, screenColumn)[1];
// clip row at the end of the document
if (row + splits.length < screenRow)
docColumn = Number.MAX_VALUE;
// Need to do some clamping action here.
if (this.$useWrapMode) {
if (docColumn >= column) {
// We remove one character at the end such that the docColumn
// position returned is not associated to the next row on the
// screen.
docColumn = column - 1;
}
} else {
docColumn = Math.min(docColumn, line.length);
}
if (foldLine) {
return foldLine.idxToPosition(docColumn);
}
return {
row: docRow,
column: docColumn
}
};
this.documentToScreenPosition = function(docRow, docColumn) {
// Normalize the passed in arguments.
if (typeof docColumn === "undefined")
var pos = this.$clipPositionToDocument(docRow.row, docRow.column);
else
pos = this.$clipPositionToDocument(docRow, docColumn);
docRow = pos.row;
docColumn = pos.column;
var LL = this.$rowCache.length;
var wrapData;
// Special case in wrapMode if the doc is at the end of the document.
if (this.$useWrapMode) {
wrapData = this.$wrapData;
if (docRow > wrapData.length - 1) {
return {
row: this.getScreenLength(),
column: wrapData.length == 0
? 0
: (wrapData[wrapData.length - 1].length - 1)
};
}
}
var screenRow = 0;
var screenColumn = 0;
var foldStartRow = null;
var fold = null;
// Clamp the docRow position in case it's inside of a folded block.
fold = this.getFoldAt(docRow, docColumn, 1);
if (fold) {
docRow = fold.start.row;
docColumn = fold.start.column;
}
var rowEnd, row = 0;
var rowCache = this.$rowCache;
for (var i = 0; i < rowCache.length; i++) {
if (rowCache[i].docRow < docRow) {
screenRow = rowCache[i].screenRow;
row = rowCache[i].docRow;
} else {
break;
}
}
var doCache = !rowCache.length || i == rowCache.length;
var foldLine = this.getNextFold(row);
var foldStart = foldLine ?foldLine.start.row :Infinity;
while (row < docRow) {
if (row >= foldStart) {
rowEnd = foldLine.end.row + 1;
if (rowEnd > docRow)
break;
foldLine = this.getNextFold(rowEnd);
foldStart = foldLine ?foldLine.start.row :Infinity;
}
else {
rowEnd = row + 1;
}
screenRow += this.getRowLength(row);
row = rowEnd;
if (doCache) {
rowCache.push({
docRow: row,
screenRow: screenRow
});
}
}
// Calculate the text line that is displayed in docRow on the screen.
var textLine = "";
// Check if the final row we want to reach is inside of a fold.
if (foldLine && row >= foldStart) {
textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn);
foldStartRow = foldLine.start.row;
} else {
textLine = this.getLine(docRow).substring(0, docColumn);
foldStartRow = docRow;
}
// Clamp textLine if in wrapMode.
if (this.$useWrapMode) {
var wrapRow = wrapData[foldStartRow];
var screenRowOffset = 0;
while (textLine.length >= wrapRow[screenRowOffset]) {
screenRow ++;
screenRowOffset++;
}
textLine = textLine.substring(
wrapRow[screenRowOffset - 1] || 0, textLine.length
);
}
return {
row: screenRow,
column: this.$getStringScreenWidth(textLine)[0]
};
};
this.documentToScreenColumn = function(row, docColumn) {
return this.documentToScreenPosition(row, docColumn).column;
};
this.documentToScreenRow = function(docRow, docColumn) {
return this.documentToScreenPosition(docRow, docColumn).row;
};
this.getScreenLength = function() {
var screenRows = 0;
var lastFoldLine = null;
var foldLine = null;
if (!this.$useWrapMode) {
screenRows = this.getLength();
// Remove the folded lines again.
var foldData = this.$foldData;
for (var i = 0; i < foldData.length; i++) {
foldLine = foldData[i];
screenRows -= foldLine.end.row - foldLine.start.row;
}
} else {
for (var row = 0; row < this.$wrapData.length; row++) {
if (foldLine = this.getFoldLine(row, lastFoldLine)) {
row = foldLine.end.row;
screenRows += 1;
} else {
screenRows += this.$wrapData[row].length + 1;
}
}
}
return screenRows;
}
// For every keystroke this gets called once per char in the whole doc!!
// Wouldn't hurt to make it a bit faster for c >= 0x1100
function isFullWidth(c) {
if (c < 0x1100)
return false;
return c >= 0x1100 && c <= 0x115F ||
c >= 0x11A3 && c <= 0x11A7 ||
c >= 0x11FA && c <= 0x11FF ||
c >= 0x2329 && c <= 0x232A ||
c >= 0x2E80 && c <= 0x2E99 ||
c >= 0x2E9B && c <= 0x2EF3 ||
c >= 0x2F00 && c <= 0x2FD5 ||
c >= 0x2FF0 && c <= 0x2FFB ||
c >= 0x3000 && c <= 0x303E ||
c >= 0x3041 && c <= 0x3096 ||
c >= 0x3099 && c <= 0x30FF ||
c >= 0x3105 && c <= 0x312D ||
c >= 0x3131 && c <= 0x318E ||
c >= 0x3190 && c <= 0x31BA ||
c >= 0x31C0 && c <= 0x31E3 ||
c >= 0x31F0 && c <= 0x321E ||
c >= 0x3220 && c <= 0x3247 ||
c >= 0x3250 && c <= 0x32FE ||
c >= 0x3300 && c <= 0x4DBF ||
c >= 0x4E00 && c <= 0xA48C ||
c >= 0xA490 && c <= 0xA4C6 ||
c >= 0xA960 && c <= 0xA97C ||
c >= 0xAC00 && c <= 0xD7A3 ||
c >= 0xD7B0 && c <= 0xD7C6 ||
c >= 0xD7CB && c <= 0xD7FB ||
c >= 0xF900 && c <= 0xFAFF ||
c >= 0xFE10 && c <= 0xFE19 ||
c >= 0xFE30 && c <= 0xFE52 ||
c >= 0xFE54 && c <= 0xFE66 ||
c >= 0xFE68 && c <= 0xFE6B ||
c >= 0xFF01 && c <= 0xFF60 ||
c >= 0xFFE0 && c <= 0xFFE6;
};
}).call(EditSession.prototype);
require("ace/edit_session/folding").Folding.call(EditSession.prototype);
exports.EditSession = EditSession;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/selection', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/lang', 'pilot/event_emitter', 'ace/range'], function(require, exports, module) {
var oop = require("pilot/oop");
var lang = require("pilot/lang");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Range = require("ace/range").Range;
/**
* Keeps cursor position and the text selection of an edit session.
*
* The row/columns used in the selection are in document coordinates
* representing ths coordinates as thez appear in the document
* before applying soft wrap and folding.
*/
var Selection = function(session) {
this.session = session;
this.doc = session.getDocument();
this.clearSelection();
this.selectionLead = this.doc.createAnchor(0, 0);
this.selectionAnchor = this.doc.createAnchor(0, 0);
var _self = this;
this.selectionLead.on("change", function(e) {
_self._dispatchEvent("changeCursor");
if (!_self.$isEmpty)
_self._dispatchEvent("changeSelection");
if (!_self.$preventUpdateDesiredColumnOnChange && e.old.column != e.value.column)
_self.$updateDesiredColumn();
});
this.selectionAnchor.on("change", function() {
if (!_self.$isEmpty)
_self._dispatchEvent("changeSelection");
});
};
(function() {
oop.implement(this, EventEmitter);
this.isEmpty = function() {
return (this.$isEmpty || (
this.selectionAnchor.row == this.selectionLead.row &&
this.selectionAnchor.column == this.selectionLead.column
));
};
this.isMultiLine = function() {
if (this.isEmpty()) {
return false;
}
return this.getRange().isMultiLine();
};
this.getCursor = function() {
return this.selectionLead.getPosition();
};
this.setSelectionAnchor = function(row, column) {
this.selectionAnchor.setPosition(row, column);
if (this.$isEmpty) {
this.$isEmpty = false;
this._dispatchEvent("changeSelection");
}
};
this.getSelectionAnchor = function() {
if (this.$isEmpty)
return this.getSelectionLead()
else
return this.selectionAnchor.getPosition();
};
this.getSelectionLead = function() {
return this.selectionLead.getPosition();
};
this.shiftSelection = function(columns) {
if (this.$isEmpty) {
this.moveCursorTo(this.selectionLead.row, this.selectionLead.column + columns);
return;
};
var anchor = this.getSelectionAnchor();
var lead = this.getSelectionLead();
var isBackwards = this.isBackwards();
if (!isBackwards || anchor.column !== 0)
this.setSelectionAnchor(anchor.row, anchor.column + columns);
if (isBackwards || lead.column !== 0) {
this.$moveSelection(function() {
this.moveCursorTo(lead.row, lead.column + columns);
});
}
};
this.isBackwards = function() {
var anchor = this.selectionAnchor;
var lead = this.selectionLead;
return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column));
};
this.getRange = function() {
var anchor = this.selectionAnchor;
var lead = this.selectionLead;
if (this.isEmpty())
return Range.fromPoints(lead, lead);
if (this.isBackwards()) {
return Range.fromPoints(lead, anchor);
}
else {
return Range.fromPoints(anchor, lead);
}
};
this.clearSelection = function() {
if (!this.$isEmpty) {
this.$isEmpty = true;
this._dispatchEvent("changeSelection");
}
};
this.selectAll = function() {
var lastRow = this.doc.getLength() - 1;
this.setSelectionAnchor(lastRow, this.doc.getLine(lastRow).length);
this.moveCursorTo(0, 0);
};
this.setSelectionRange = function(range, reverse) {
if (reverse) {
this.setSelectionAnchor(range.end.row, range.end.column);
this.selectTo(range.start.row, range.start.column);
} else {
this.setSelectionAnchor(range.start.row, range.start.column);
this.selectTo(range.end.row, range.end.column);
}
this.$updateDesiredColumn();
};
this.$updateDesiredColumn = function() {
var cursor = this.getCursor();
this.$desiredColumn = this.session.documentToScreenColumn(cursor.row, cursor.column);
};
this.$moveSelection = function(mover) {
var lead = this.selectionLead;
if (this.$isEmpty)
this.setSelectionAnchor(lead.row, lead.column);
mover.call(this);
};
this.selectTo = function(row, column) {
this.$moveSelection(function() {
this.moveCursorTo(row, column);
});
};
this.selectToPosition = function(pos) {
this.$moveSelection(function() {
this.moveCursorToPosition(pos);
});
};
this.selectUp = function() {
this.$moveSelection(this.moveCursorUp);
};
this.selectDown = function() {
this.$moveSelection(this.moveCursorDown);
};
this.selectRight = function() {
this.$moveSelection(this.moveCursorRight);
};
this.selectLeft = function() {
this.$moveSelection(this.moveCursorLeft);
};
this.selectLineStart = function() {
this.$moveSelection(this.moveCursorLineStart);
};
this.selectLineEnd = function() {
this.$moveSelection(this.moveCursorLineEnd);
};
this.selectFileEnd = function() {
this.$moveSelection(this.moveCursorFileEnd);
};
this.selectFileStart = function() {
this.$moveSelection(this.moveCursorFileStart);
};
this.selectWordRight = function() {
this.$moveSelection(this.moveCursorWordRight);
};
this.selectWordLeft = function() {
this.$moveSelection(this.moveCursorWordLeft);
};
this.selectWord = function() {
var cursor = this.getCursor();
var range = this.session.getWordRange(cursor.row, cursor.column);
this.setSelectionRange(range);
};
this.selectLine = function() {
var rowStart = this.selectionLead.row;
var rowEnd;
var foldLine = this.session.getFoldLine(rowStart);
if (foldLine) {
rowStart = foldLine.start.row;
rowEnd = foldLine.end.row;
} else {
rowEnd = rowStart;
}
this.setSelectionAnchor(rowStart, 0);
this.$moveSelection(function() {
this.moveCursorTo(rowEnd + 1, 0);
});
};
this.moveCursorUp = function() {
this.moveCursorBy(-1, 0);
};
this.moveCursorDown = function() {
this.moveCursorBy(1, 0);
};
this.moveCursorLeft = function() {
var cursor = this.selectionLead.getPosition(),
fold;
if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) {
this.moveCursorTo(fold.start.row, fold.start.column);
} else if (cursor.column == 0) {
// cursor is a line (start
if (cursor.row > 0) {
this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length);
}
}
else {
var tabSize = this.session.getTabSize();
if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column-tabSize, cursor.column).split(" ").length-1 == tabSize)
this.moveCursorBy(0, -tabSize);
else
this.moveCursorBy(0, -1);
}
};
this.moveCursorRight = function() {
var cursor = this.selectionLead.getPosition(),
fold;
if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) {
this.moveCursorTo(fold.end.row, fold.end.column);
}
else if (this.selectionLead.column == this.doc.getLine(this.selectionLead.row).length) {
if (this.selectionLead.row < this.doc.getLength() - 1) {
this.moveCursorTo(this.selectionLead.row + 1, 0);
}
}
else {
var tabSize = this.session.getTabSize();
var cursor = this.selectionLead;
if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column, cursor.column+tabSize).split(" ").length-1 == tabSize)
this.moveCursorBy(0, tabSize);
else
this.moveCursorBy(0, 1);
}
};
this.moveCursorLineStart = function() {
var row = this.selectionLead.row;
var column = this.selectionLead.column;
var screenRow = this.session.documentToScreenRow(row, column);
// Determ the doc-position of the first character at the screen line.
var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0);
// Determ the line
var beforeCursor = this.session.getDisplayLine(
row, null,
firstColumnPosition.row, firstColumnPosition.column
);
var leadingSpace = beforeCursor.match(/^\s*/);
if (leadingSpace[0].length == column) {
this.moveCursorTo(
firstColumnPosition.row, firstColumnPosition.column
);
}
else {
this.moveCursorTo(
firstColumnPosition.row,
firstColumnPosition.column + leadingSpace[0].length
);
}
};
this.moveCursorLineEnd = function() {
var lead = this.selectionLead;
var lastRowColumnPosition =
this.session.getDocumentLastRowColumnPosition(lead.row, lead.column);
this.moveCursorTo(
lastRowColumnPosition.row,
lastRowColumnPosition.column
);
};
this.moveCursorFileEnd = function() {
var row = this.doc.getLength() - 1;
var column = this.doc.getLine(row).length;
this.moveCursorTo(row, column);
};
this.moveCursorFileStart = function() {
this.moveCursorTo(0, 0);
};
this.moveCursorWordRight = function() {
var row = this.selectionLead.row;
var column = this.selectionLead.column;
var line = this.doc.getLine(row);
var rightOfCursor = line.substring(column);
var match;
this.session.nonTokenRe.lastIndex = 0;
this.session.tokenRe.lastIndex = 0;
var fold;
if (fold = this.session.getFoldAt(row, column, 1)) {
this.moveCursorTo(fold.end.row, fold.end.column);
return;
} else if (column == line.length) {
this.moveCursorRight();
return;
}
else if (match = this.session.nonTokenRe.exec(rightOfCursor)) {
column += this.session.nonTokenRe.lastIndex;
this.session.nonTokenRe.lastIndex = 0;
}
else if (match = this.session.tokenRe.exec(rightOfCursor)) {
column += this.session.tokenRe.lastIndex;
this.session.tokenRe.lastIndex = 0;
}
this.moveCursorTo(row, column);
};
this.moveCursorWordLeft = function() {
var row = this.selectionLead.row;
var column = this.selectionLead.column;
var fold;
if (fold = this.session.getFoldAt(row, column, -1)) {
this.moveCursorTo(fold.start.row, fold.start.column);
return;
}
if (column == 0) {
this.moveCursorLeft();
return;
}
var str = this.session.getFoldStringAt(row, column, -1);
if (str == null) {
str = this.doc.getLine(row).substring(0, column)
}
var leftOfCursor = lang.stringReverse(str);
var match;
this.session.nonTokenRe.lastIndex = 0;
this.session.tokenRe.lastIndex = 0;
if (match = this.session.nonTokenRe.exec(leftOfCursor)) {
column -= this.session.nonTokenRe.lastIndex;
this.session.nonTokenRe.lastIndex = 0;
}
else if (match = this.session.tokenRe.exec(leftOfCursor)) {
column -= this.session.tokenRe.lastIndex;
this.session.tokenRe.lastIndex = 0;
}
this.moveCursorTo(row, column);
};
this.moveCursorBy = function(rows, chars) {
var screenPos = this.session.documentToScreenPosition(
this.selectionLead.row,
this.selectionLead.column
);
var screenCol = (chars == 0 && this.$desiredColumn) || screenPos.column;
var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenCol);
this.moveCursorTo(docPos.row, docPos.column + chars, chars == 0);
};
this.moveCursorToPosition = function(position) {
this.moveCursorTo(position.row, position.column);
};
this.moveCursorTo = function(row, column, preventUpdateDesiredColumn) {
// Ensure the row/column is not inside of a fold.
var fold = this.session.getFoldAt(row, column, 1);
if (fold) {
row = fold.start.row;
column = fold.start.column;
}
this.$preventUpdateDesiredColumnOnChange = true;
this.selectionLead.setPosition(row, column);
this.$preventUpdateDesiredColumnOnChange = false;
if (!preventUpdateDesiredColumn)
this.$updateDesiredColumn(this.selectionLead.column);
};
this.moveCursorToScreen = function(row, column, preventUpdateDesiredColumn) {
var pos = this.session.screenToDocumentPosition(row, column);
row = pos.row;
column = pos.column;
this.moveCursorTo(row, column, preventUpdateDesiredColumn);
};
}).call(Selection.prototype);
exports.Selection = Selection;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) {
var Range = function(startRow, startColumn, endRow, endColumn) {
this.start = {
row: startRow,
column: startColumn
};
this.end = {
row: endRow,
column: endColumn
};
};
(function() {
this.toString = function() {
return ("Range: [" + this.start.row + "/" + this.start.column +
"] -> [" + this.end.row + "/" + this.end.column + "]");
};
this.contains = function(row, column) {
return this.compare(row, column) == 0;
};
/**
* Compares this range (A) with another range (B), where B is the passed in
* range.
*
* Return values:
* -2: (B) is infront of (A) and doesn't intersect with (A)
* -1: (B) begins before (A) but ends inside of (A)
* 0: (B) is completly inside of (A) OR (A) is complety inside of (B)
* +1: (B) begins inside of (A) but ends outside of (A)
* +2: (B) is after (A) and doesn't intersect with (A)
*
* 42: FTW state: (B) ends in (A) but starts outside of (A)
*/
this.compareRange = function(range) {
var cmp,
end = range.end,
start = range.start;
cmp = this.compare(end.row, end.column);
if (cmp == 1) {
cmp = this.compare(start.row, start.column);
if (cmp == 1) {
return 2;
} else if (cmp == 0) {
return 1;
} else {
return 0;
}
} else if (cmp == -1) {
return -2;
} else {
cmp = this.compare(start.row, start.column);
if (cmp == -1) {
return -1;
} else if (cmp == 1) {
return 42;
} else {
return 0;
}
}
}
this.containsRange = function(range) {
var cmp = this.compareRange(range);
return (cmp == -1 || cmp == 0 || cmp == 1);
}
this.isEnd = function(row, column) {
return this.end.row == row && this.end.column == column;
}
this.isStart = function(row, column) {
return this.start.row == row && this.start.column == column;
}
this.setStart = function(row, column) {
if (typeof row == "object") {
this.start.column = row.column;
this.start.row = row.row;
} else {
this.start.row = row;
this.start.column = column;
}
}
this.setEnd = function(row, column) {
if (typeof row == "object") {
this.end.column = row.column;
this.end.row = row.row;
} else {
this.end.row = row;
this.end.column = column;
}
}
this.inside = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column) || this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
this.insideStart = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
this.insideEnd = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
this.compare = function(row, column) {
if (!this.isMultiLine()) {
if (row === this.start.row) {
return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
};
}
if (row < this.start.row)
return -1;
if (row > this.end.row)
return 1;
if (this.start.row === row)
return column >= this.start.column ? 0 : -1;
if (this.end.row === row)
return column <= this.end.column ? 0 : 1;
return 0;
};
/**
* Like .compare(), but if isStart is true, return -1;
*/
this.compareStart = function(row, column) {
if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
}
/**
* Like .compare(), but if isEnd is true, return 1;
*/
this.compareEnd = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else {
return this.compare(row, column);
}
}
this.compareInside = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
}
this.clipRows = function(firstRow, lastRow) {
if (this.end.row > lastRow) {
var end = {
row: lastRow+1,
column: 0
};
}
if (this.start.row > lastRow) {
var start = {
row: lastRow+1,
column: 0
};
}
if (this.start.row < firstRow) {
var start = {
row: firstRow,
column: 0
};
}
if (this.end.row < firstRow) {
var end = {
row: firstRow,
column: 0
};
}
return Range.fromPoints(start || this.start, end || this.end);
};
this.extend = function(row, column) {
var cmp = this.compare(row, column);
if (cmp == 0)
return this;
else if (cmp == -1)
var start = {row: row, column: column};
else
var end = {row: row, column: column};
return Range.fromPoints(start || this.start, end || this.end);
};
this.isEmpty = function() {
return (this.start.row == this.end.row && this.start.column == this.end.column);
};
this.isMultiLine = function() {
return (this.start.row !== this.end.row);
};
this.clone = function() {
return Range.fromPoints(this.start, this.end);
};
this.collapseRows = function() {
if (this.end.column == 0)
return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
else
return new Range(this.start.row, 0, this.end.row, 0)
};
this.toScreenRange = function(session) {
var screenPosStart =
session.documentToScreenPosition(this.start);
var screenPosEnd =
session.documentToScreenPosition(this.end);
return new Range(
screenPosStart.row, screenPosStart.column,
screenPosEnd.row, screenPosEnd.column
);
};
}).call(Range.prototype);
Range.fromPoints = function(start, end) {
return new Range(start.row, start.column, end.row, end.column);
};
exports.Range = Range;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
* Chris Spencer <chris.ag.spencer AT googlemail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/text', ['require', 'exports', 'module' , 'ace/tokenizer', 'ace/mode/text_highlight_rules', 'ace/mode/behaviour', 'ace/unicode'], function(require, exports, module) {
var Tokenizer = require("ace/tokenizer").Tokenizer;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var Behaviour = require("ace/mode/behaviour").Behaviour;
var unicode = require("ace/unicode");
var Mode = function() {
this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
this.$behaviour = new Behaviour();
};
(function() {
this.tokenRe = new RegExp("^["
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]+", "g"
);
this.nonTokenRe = new RegExp("^(?:[^"
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]|\s])+", "g"
);
this.getTokenizer = function() {
return this.$tokenizer;
};
this.toggleCommentLines = function(state, doc, startRow, endRow) {
};
this.getNextLineIndent = function(state, line, tab) {
return "";
};
this.checkOutdent = function(state, line, input) {
return false;
};
this.autoOutdent = function(state, doc, row) {
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
this.createWorker = function(session) {
return null;
};
this.highlightSelection = function(editor) {
var session = editor.session;
if (!session.$selectionOccurrences)
session.$selectionOccurrences = [];
if (session.$selectionOccurrences.length)
this.clearSelectionHighlight(editor);
var selection = editor.getSelectionRange();
if (selection.isEmpty() || selection.isMultiLine())
return;
var startOuter = selection.start.column - 1;
var endOuter = selection.end.column + 1;
var line = session.getLine(selection.start.row);
var lineCols = line.length;
var needle = line.substring(Math.max(startOuter, 0),
Math.min(endOuter, lineCols));
// Make sure the outer characters are not part of the word.
if ((startOuter >= 0 && /^[\w\d]/.test(needle)) ||
(endOuter <= lineCols && /[\w\d]$/.test(needle)))
return;
needle = line.substring(selection.start.column, selection.end.column);
if (!/^[\w\d]+$/.test(needle))
return;
var cursor = editor.getCursorPosition();
var newOptions = {
wrap: true,
wholeWord: true,
caseSensitive: true,
needle: needle
};
var currentOptions = editor.$search.getOptions();
editor.$search.set(newOptions);
var ranges = editor.$search.findAll(session);
ranges.forEach(function(range) {
if (!range.contains(cursor.row, cursor.column)) {
var marker = session.addMarker(range, "ace_selected_word", "text");
session.$selectionOccurrences.push(marker);
}
});
editor.$search.set(currentOptions);
};
this.clearSelectionHighlight = function(editor) {
if (!editor.session.$selectionOccurrences)
return;
editor.session.$selectionOccurrences.forEach(function(marker) {
editor.session.removeMarker(marker);
});
editor.session.$selectionOccurrences = [];
};
this.createModeDelegates = function (mapping) {
if (!this.$embeds) {
return;
}
this.$modes = {};
for (var i = 0; i < this.$embeds.length; i++) {
if (mapping[this.$embeds[i]]) {
this.$modes[this.$embeds[i]] = new mapping[this.$embeds[i]]();
}
}
var delegations = ['toggleCommentLines', 'getNextLineIndent', 'checkOutdent', 'autoOutdent', 'transformAction'];
for (var i = 0; i < delegations.length; i++) {
(function(scope) {
var functionName = delegations[i];
var defaultHandler = scope[functionName];
scope[delegations[i]] = function() {
return this.$delegator(functionName, arguments, defaultHandler);
}
} (this));
}
}
this.$delegator = function(method, args, defaultHandler) {
var state = args[0];
for (var i = 0; i < this.$embeds.length; i++) {
if (!this.$modes[this.$embeds[i]]) continue;
var split = state.split(this.$embeds[i]);
if (!split[0] && split[1]) {
args[0] = split[1];
var mode = this.$modes[this.$embeds[i]];
return mode[method].apply(mode, args);
}
}
var ret = defaultHandler.apply(this, args);
return defaultHandler ? ret : undefined;
};
this.transformAction = function(state, action, editor, session, param) {
if (this.$behaviour) {
var behaviours = this.$behaviour.getBehaviours();
for (var key in behaviours) {
if (behaviours[key][action]) {
var ret = behaviours[key][action].apply(this, arguments);
if (ret !== false) {
return ret;
}
}
}
}
return false;
}
}).call(Mode.prototype);
exports.Mode = Mode;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/tokenizer', ['require', 'exports', 'module' ], function(require, exports, module) {
var Tokenizer = function(rules) {
this.rules = rules;
this.regExps = {};
this.matchMappings = {};
for ( var key in this.rules) {
var rule = this.rules[key];
var state = rule;
var ruleRegExps = [];
var matchTotal = 0;
var mapping = this.matchMappings[key] = {};
for ( var i = 0; i < state.length; i++) {
// Count number of matching groups. 2 extra groups from the full match
// And the catch-all on the end (used to force a match);
var matchcount = new RegExp("(?:(" + state[i].regex + ")|(.))").exec("a").length - 2;
// Replace any backreferences and offset appropriately.
var adjustedregex = state[i].regex.replace(/\\([0-9]+)/g, function (match, digit) {
return "\\" + (parseInt(digit, 10) + matchTotal + 1);
});
mapping[matchTotal] = {
rule: i,
len: matchcount
};
matchTotal += matchcount;
ruleRegExps.push(adjustedregex);
}
this.regExps[key] = new RegExp("(?:(" + ruleRegExps.join(")|(") + ")|(.))", "g");
}
};
(function() {
this.getLineTokens = function(line, startState) {
var currentState = startState;
var state = this.rules[currentState];
var mapping = this.matchMappings[currentState];
var re = this.regExps[currentState];
re.lastIndex = 0;
var match, tokens = [];
var lastIndex = 0;
var token = {
type: null,
value: ""
};
while (match = re.exec(line)) {
var type = "text";
var rule = null;
var value = [match[0]];
for (var i = 0; i < match.length-2; i++) {
if (match[i + 1] !== undefined) {
rule = state[mapping[i].rule];
if (mapping[i].len > 1) {
value = match.slice(i+2, i+1+mapping[i].len);
}
// compute token type
if (typeof rule.token == "function")
type = rule.token.apply(this, value);
else
type = rule.token;
var next = rule.next;
if (next && next !== currentState) {
currentState = next;
state = this.rules[currentState];
mapping = this.matchMappings[currentState];
lastIndex = re.lastIndex;
re = this.regExps[currentState];
re.lastIndex = lastIndex;
}
break;
}
};
if (value[0]) {
if (typeof type == "string") {
value = [value.join("")];
type = [type];
}
for (var i = 0; i < value.length; i++) {
if ((!rule || rule.merge || type[i] === "text") && token.type === type[i]) {
token.value += value[i];
} else {
if (token.type) {
tokens.push(token);
}
token = {
type: type[i],
value: value[i]
}
}
}
}
if (lastIndex == line.length)
break;
lastIndex = re.lastIndex;
};
if (token.type)
tokens.push(token);
return {
tokens : tokens,
state : currentState
};
};
}).call(Tokenizer.prototype);
exports.Tokenizer = Tokenizer;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/text_highlight_rules', ['require', 'exports', 'module' , 'pilot/lang'], function(require, exports, module) {
var lang = require("pilot/lang");
var TextHighlightRules = function() {
// regexp must not have capturing parentheses
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [{
token : "empty_line",
regex : '^$'
}, {
token : "text",
regex : ".+"
}]
};
};
(function() {
this.addRules = function(rules, prefix) {
for (var key in rules) {
var state = rules[key];
for (var i=0; i<state.length; i++) {
var rule = state[i];
if (rule.next) {
rule.next = prefix + rule.next;
} else {
rule.next = prefix + key;
}
}
this.$rules[prefix + key] = state;
}
};
this.getRules = function() {
return this.$rules;
};
this.embedRules = function (HighlightRules, prefix, escapeRules, states) {
var embedRules = new HighlightRules().getRules();
if (states) {
for (var i = 0; i < states.length; i++) {
states[i] = prefix + states[i];
}
} else {
states = [];
for (var key in embedRules) {
states.push(prefix + key);
}
}
this.addRules(embedRules, prefix);
for (var i = 0; i < states.length; i++) {
Array.prototype.unshift.apply(this.$rules[states[i]], lang.deepCopy(escapeRules));
}
if (!this.$embeds) {
this.$embeds = [];
}
this.$embeds.push(prefix);
}
this.getEmbeds = function() {
return this.$embeds;
}
}).call(TextHighlightRules.prototype);
exports.TextHighlightRules = TextHighlightRules;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Chris Spencer <chris.ag.spencer AT googlemail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/behaviour', ['require', 'exports', 'module' ], function(require, exports, module) {
var Behaviour = function() {
this.$behaviours = {};
};
(function () {
this.add = function (name, action, callback) {
switch (undefined) {
case this.$behaviours:
this.$behaviours = {};
case this.$behaviours[name]:
this.$behaviours[name] = {};
}
this.$behaviours[name][action] = callback;
}
this.addBehaviours = function (behaviours) {
for (var key in behaviours) {
for (var action in behaviours[key]) {
this.add(key, action, behaviours[key][action]);
}
}
}
this.remove = function (name) {
if (this.$behaviours && this.$behaviours[name]) {
delete this.$behaviours[name];
}
}
this.inherit = function (mode, filter) {
if (typeof mode === "function") {
var behaviours = new mode().getBehaviours(filter);
} else {
var behaviours = mode.getBehaviours(filter);
}
this.addBehaviours(behaviours);
}
this.getBehaviours = function (filter) {
if (!filter) {
return this.$behaviours;
} else {
var ret = {}
for (var i = 0; i < filter.length; i++) {
if (this.$behaviours[filter[i]]) {
ret[filter[i]] = this.$behaviours[filter[i]];
}
}
return ret;
}
}
}).call(Behaviour.prototype);
exports.Behaviour = Behaviour;
});define('ace/unicode', ['require', 'exports', 'module' ], function(require, exports, module) {
/*
XRegExp Unicode plugin pack: Categories 1.0
(c) 2010 Steven Levithan
MIT License
<http://xregexp.com>
Uses the Unicode 5.2 character database
This package for the XRegExp Unicode plugin enables the following Unicode categories (aka properties):
L - Letter (the top-level Letter category is included in the Unicode plugin base script)
Ll - Lowercase letter
Lu - Uppercase letter
Lt - Titlecase letter
Lm - Modifier letter
Lo - Letter without case
M - Mark
Mn - Non-spacing mark
Mc - Spacing combining mark
Me - Enclosing mark
N - Number
Nd - Decimal digit
Nl - Letter number
No - Other number
P - Punctuation
Pd - Dash punctuation
Ps - Open punctuation
Pe - Close punctuation
Pi - Initial punctuation
Pf - Final punctuation
Pc - Connector punctuation
Po - Other punctuation
S - Symbol
Sm - Math symbol
Sc - Currency symbol
Sk - Modifier symbol
So - Other symbol
Z - Separator
Zs - Space separator
Zl - Line separator
Zp - Paragraph separator
C - Other
Cc - Control
Cf - Format
Co - Private use
Cs - Surrogate
Cn - Unassigned
Example usage:
\p{N}
\p{Cn}
*/
// will be populated by addUnicodePackage
exports.packages = {};
addUnicodePackage({
L: "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
Ll: "0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A",
Lu: "0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A",
Lt: "01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC",
Lm: "02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F",
Lo: "01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
M: "0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26",
Mn: "0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26",
Mc: "0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC",
Me: "0488048906DE20DD-20E020E2-20E4A670-A672",
N: "0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
Nd: "0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
Nl: "16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF",
No: "00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835",
P: "0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65",
Pd: "002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D",
Ps: "0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62",
Pe: "0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63",
Pi: "00AB2018201B201C201F20392E022E042E092E0C2E1C2E20",
Pf: "00BB2019201D203A2E032E052E0A2E0D2E1D2E21",
Pc: "005F203F20402054FE33FE34FE4D-FE4FFF3F",
Po: "0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65",
S: "0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD",
Sm: "002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC",
Sc: "002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6",
Sk: "005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3",
So: "00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD",
Z: "002000A01680180E2000-200A20282029202F205F3000",
Zs: "002000A01680180E2000-200A202F205F3000",
Zl: "2028",
Zp: "2029",
C: "0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF",
Cc: "0000-001F007F-009F",
Cf: "00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB",
Co: "E000-F8FF",
Cs: "D800-DFFF",
Cn: "03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF"
});
function addUnicodePackage (pack) {
var codePoint = /\w{4}/g;
for (var name in pack)
exports.packages[name] = pack[name].replace(codePoint, "\\u$&");
};
});/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/document', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) {
var oop = require("pilot/oop");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Range = require("ace/range").Range;
var Anchor = require("ace/anchor").Anchor;
var Document = function(text) {
this.$lines = [];
if (Array.isArray(text)) {
this.insertLines(0, text);
}
// There has to be one line at least in the document. If you pass an empty
// string to the insert function, nothing will happen. Workaround.
else if (text.length == 0) {
this.$lines = [""];
} else {
this.insert({row: 0, column:0}, text);
}
};
(function() {
oop.implement(this, EventEmitter);
this.setValue = function(text) {
var len = this.getLength();
this.remove(new Range(0, 0, len, this.getLine(len-1).length));
this.insert({row: 0, column:0}, text);
};
this.getValue = function() {
return this.getAllLines().join(this.getNewLineCharacter());
};
this.createAnchor = function(row, column) {
return new Anchor(this, row, column);
};
// check for IE split bug
if ("aaa".split(/a/).length == 0)
this.$split = function(text) {
return text.replace(/\r\n|\r/g, "\n").split("\n");
}
else
this.$split = function(text) {
return text.split(/\r\n|\r|\n/);
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r?\n)/m);
if (match) {
this.$autoNewLine = match[1];
} else {
this.$autoNewLine = "\n";
}
};
this.getNewLineCharacter = function() {
switch (this.$newLineMode) {
case "windows":
return "\r\n";
case "unix":
return "\n";
case "auto":
return this.$autoNewLine;
}
},
this.$autoNewLine = "\n";
this.$newLineMode = "auto";
this.setNewLineMode = function(newLineMode) {
if (this.$newLineMode === newLineMode) return;
this.$newLineMode = newLineMode;
};
this.getNewLineMode = function() {
return this.$newLineMode;
};
this.isNewLine = function(text) {
return (text == "\r\n" || text == "\r" || text == "\n");
};
/**
* Get a verbatim copy of the given line as it is in the document
*/
this.getLine = function(row) {
return this.$lines[row] || "";
};
this.getLines = function(firstRow, lastRow) {
return this.$lines.slice(firstRow, lastRow + 1);
};
/**
* Returns all lines in the document as string array. Warning: The caller
* should not modify this array!
*/
this.getAllLines = function() {
return this.getLines(0, this.getLength());
};
this.getLength = function() {
return this.$lines.length;
};
this.getTextRange = function(range) {
if (range.start.row == range.end.row) {
return this.$lines[range.start.row].substring(range.start.column,
range.end.column);
}
else {
var lines = [];
lines.push(this.$lines[range.start.row].substring(range.start.column));
lines.push.apply(lines, this.getLines(range.start.row+1, range.end.row-1));
lines.push(this.$lines[range.end.row].substring(0, range.end.column));
return lines.join(this.getNewLineCharacter());
}
};
this.$clipPosition = function(position) {
var length = this.getLength();
if (position.row >= length) {
position.row = Math.max(0, length - 1);
position.column = this.getLine(length-1).length;
}
return position;
}
this.insert = function(position, text) {
if (text.length == 0)
return position;
position = this.$clipPosition(position);
if (this.getLength() <= 1)
this.$detectNewLine(text);
var lines = this.$split(text);
var firstLine = lines.splice(0, 1)[0];
var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0];
position = this.insertInLine(position, firstLine);
if (lastLine !== null) {
position = this.insertNewLine(position); // terminate first line
position = this.insertLines(position.row, lines);
position = this.insertInLine(position, lastLine || "");
}
return position;
};
this.insertLines = function(row, lines) {
if (lines.length == 0)
return {row: row, column: 0};
var args = [row, 0];
args.push.apply(args, lines);
this.$lines.splice.apply(this.$lines, args);
var range = new Range(row, 0, row + lines.length, 0);
var delta = {
action: "insertLines",
range: range,
lines: lines
};
this._dispatchEvent("change", { data: delta });
return range.end;
},
this.insertNewLine = function(position) {
position = this.$clipPosition(position);
var line = this.$lines[position.row] || "";
this.$lines[position.row] = line.substring(0, position.column);
this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length));
var end = {
row : position.row + 1,
column : 0
};
var delta = {
action: "insertText",
range: Range.fromPoints(position, end),
text: this.getNewLineCharacter()
};
this._dispatchEvent("change", { data: delta });
return end;
};
this.insertInLine = function(position, text) {
if (text.length == 0)
return position;
var line = this.$lines[position.row] || "";
this.$lines[position.row] = line.substring(0, position.column) + text
+ line.substring(position.column);
var end = {
row : position.row,
column : position.column + text.length
};
var delta = {
action: "insertText",
range: Range.fromPoints(position, end),
text: text
};
this._dispatchEvent("change", { data: delta });
return end;
};
this.remove = function(range) {
// clip to document
range.start = this.$clipPosition(range.start);
range.end = this.$clipPosition(range.end);
if (range.isEmpty())
return range.start;
var firstRow = range.start.row;
var lastRow = range.end.row;
if (range.isMultiLine()) {
var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1;
var lastFullRow = lastRow - 1;
if (range.end.column > 0)
this.removeInLine(lastRow, 0, range.end.column);
if (lastFullRow >= firstFullRow)
this.removeLines(firstFullRow, lastFullRow);
if (firstFullRow != firstRow) {
this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length);
this.removeNewLine(range.start.row);
}
}
else {
this.removeInLine(firstRow, range.start.column, range.end.column);
}
return range.start;
};
this.removeInLine = function(row, startColumn, endColumn) {
if (startColumn == endColumn)
return;
var range = new Range(row, startColumn, row, endColumn);
var line = this.getLine(row);
var removed = line.substring(startColumn, endColumn);
var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length);
this.$lines.splice(row, 1, newLine);
var delta = {
action: "removeText",
range: range,
text: removed
};
this._dispatchEvent("change", { data: delta });
return range.start;
};
/**
* Removes a range of full lines
*
* @param firstRow {Integer} The first row to be removed
* @param lastRow {Integer} The last row to be removed
* @return {String[]} The removed lines
*/
this.removeLines = function(firstRow, lastRow) {
var range = new Range(firstRow, 0, lastRow + 1, 0);
var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1);
var delta = {
action: "removeLines",
range: range,
nl: this.getNewLineCharacter(),
lines: removed
};
this._dispatchEvent("change", { data: delta });
return removed;
};
this.removeNewLine = function(row) {
var firstLine = this.getLine(row);
var secondLine = this.getLine(row+1);
var range = new Range(row, firstLine.length, row+1, 0);
var line = firstLine + secondLine;
this.$lines.splice(row, 2, line);
var delta = {
action: "removeText",
range: range,
text: this.getNewLineCharacter()
};
this._dispatchEvent("change", { data: delta });
};
this.replace = function(range, text) {
if (text.length == 0 && range.isEmpty())
return range.start;
// Shortcut: If the text we want to insert is the same as it is already
// in the document, we don't have to replace anything.
if (text == this.getTextRange(range))
return range.end;
this.remove(range);
if (text) {
var end = this.insert(range.start, text);
}
else {
end = range.start;
}
return end;
};
this.applyDeltas = function(deltas) {
for (var i=0; i<deltas.length; i++) {
var delta = deltas[i];
var range = Range.fromPoints(delta.range.start, delta.range.end);
if (delta.action == "insertLines")
this.insertLines(range.start.row, delta.lines)
else if (delta.action == "insertText")
this.insert(range.start, delta.text)
else if (delta.action == "removeLines")
this.removeLines(range.start.row, range.end.row - 1)
else if (delta.action == "removeText")
this.remove(range)
}
};
this.revertDeltas = function(deltas) {
for (var i=deltas.length-1; i>=0; i--) {
var delta = deltas[i];
var range = Range.fromPoints(delta.range.start, delta.range.end);
if (delta.action == "insertLines")
this.removeLines(range.start.row, range.end.row - 1)
else if (delta.action == "insertText")
this.remove(range)
else if (delta.action == "removeLines")
this.insertLines(range.start.row, delta.lines)
else if (delta.action == "removeText")
this.insert(range.start, delta.text)
}
};
}).call(Document.prototype);
exports.Document = Document;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/anchor', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
/**
* An Anchor is a floating pointer in the document. Whenever text is inserted or
* deleted before the cursor, the position of the cursor is updated
*/
var Anchor = exports.Anchor = function(doc, row, column) {
this.document = doc;
if (typeof column == "undefined")
this.setPosition(row.row, row.column);
else
this.setPosition(row, column);
this.$onChange = this.onChange.bind(this);
doc.on("change", this.$onChange);
};
(function() {
oop.implement(this, EventEmitter);
this.getPosition = function() {
return this.$clipPositionToDocument(this.row, this.column);
};
this.getDocument = function() {
return this.document;
};
this.onChange = function(e) {
var delta = e.data;
var range = delta.range;
if (range.start.row == range.end.row && range.start.row != this.row)
return;
if (range.start.row > this.row)
return;
if (range.start.row == this.row && range.start.column > this.column)
return;
var row = this.row;
var column = this.column;
if (delta.action === "insertText") {
if (range.start.row === row && range.start.column <= column) {
if (range.start.row === range.end.row) {
column += range.end.column - range.start.column;
}
else {
column -= range.start.column;
row += range.end.row - range.start.row;
}
}
else if (range.start.row !== range.end.row && range.start.row < row) {
row += range.end.row - range.start.row;
}
} else if (delta.action === "insertLines") {
if (range.start.row <= row) {
row += range.end.row - range.start.row;
}
}
else if (delta.action == "removeText") {
if (range.start.row == row && range.start.column < column) {
if (range.end.column >= column)
column = range.start.column;
else
column = Math.max(0, column - (range.end.column - range.start.column));
} else if (range.start.row !== range.end.row && range.start.row < row) {
if (range.end.row == row) {
column = Math.max(0, column - range.end.column) + range.start.column;
}
row -= (range.end.row - range.start.row);
}
else if (range.end.row == row) {
row -= range.end.row - range.start.row;
column = Math.max(0, column - range.end.column) + range.start.column;
}
} else if (delta.action == "removeLines") {
if (range.start.row <= row) {
if (range.end.row <= row)
row -= range.end.row - range.start.row;
else {
row = range.start.row;
column = 0;
}
}
}
this.setPosition(row, column, true);
};
this.setPosition = function(row, column, noClip) {
var pos;
if (noClip) {
pos = {
row: row,
column: column
};
}
else {
pos = this.$clipPositionToDocument(row, column);
}
if (this.row == pos.row && this.column == pos.column)
return;
var old = {
row: this.row,
column: this.column
};
this.row = pos.row;
this.column = pos.column;
this._dispatchEvent("change", {
old: old,
value: pos
});
};
this.detach = function() {
this.document.removeEventListener("change", this.$onChange);
};
this.$clipPositionToDocument = function(row, column) {
var pos = {};
if (row >= this.document.getLength()) {
pos.row = Math.max(0, this.document.getLength() - 1);
pos.column = this.document.getLine(pos.row).length;
}
else if (row < 0) {
pos.row = 0;
pos.column = 0;
}
else {
pos.row = row;
pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
}
if (column < 0)
pos.column = 0;
return pos;
};
}).call(Anchor.prototype);
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/background_tokenizer', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var BackgroundTokenizer = function(tokenizer, editor) {
this.running = false;
this.lines = [];
this.currentLine = 0;
this.tokenizer = tokenizer;
var self = this;
this.$worker = function() {
if (!self.running) { return; }
var workerStart = new Date();
var startLine = self.currentLine;
var doc = self.doc;
var processedLines = 0;
var len = doc.getLength();
while (self.currentLine < len) {
self.lines[self.currentLine] = self.$tokenizeRows(self.currentLine, self.currentLine)[0];
self.currentLine++;
// only check every 5 lines
processedLines += 1;
if ((processedLines % 5 == 0) && (new Date() - workerStart) > 20) {
self.fireUpdateEvent(startLine, self.currentLine-1);
self.running = setTimeout(self.$worker, 20);
return;
}
}
self.running = false;
self.fireUpdateEvent(startLine, len - 1);
};
};
(function(){
oop.implement(this, EventEmitter);
this.setTokenizer = function(tokenizer) {
this.tokenizer = tokenizer;
this.lines = [];
this.start(0);
};
this.setDocument = function(doc) {
this.doc = doc;
this.lines = [];
this.stop();
};
this.fireUpdateEvent = function(firstRow, lastRow) {
var data = {
first: firstRow,
last: lastRow
};
this._dispatchEvent("update", {data: data});
};
this.start = function(startRow) {
this.currentLine = Math.min(startRow || 0, this.currentLine,
this.doc.getLength());
// remove all cached items below this line
this.lines.splice(this.currentLine, this.lines.length);
this.stop();
// pretty long delay to prevent the tokenizer from interfering with the user
this.running = setTimeout(this.$worker, 700);
};
this.stop = function() {
if (this.running)
clearTimeout(this.running);
this.running = false;
};
this.getTokens = function(firstRow, lastRow) {
return this.$tokenizeRows(firstRow, lastRow);
};
this.getState = function(row) {
return this.$tokenizeRows(row, row)[0].state;
};
this.$tokenizeRows = function(firstRow, lastRow) {
if (!this.doc)
return [];
var rows = [];
// determine start state
var state = "start";
var doCache = false;
if (firstRow > 0 && this.lines[firstRow - 1]) {
state = this.lines[firstRow - 1].state;
doCache = true;
} else if (firstRow == 0) {
state = "start";
doCache = true;
} else if (this.lines.length > 0) {
// Guess that we haven't changed state.
state = this.lines[this.lines.length-1].state;
}
var lines = this.doc.getLines(firstRow, lastRow);
for (var row=firstRow; row<=lastRow; row++) {
if (!this.lines[row]) {
var tokens = this.tokenizer.getLineTokens(lines[row-firstRow] || "", state);
var state = tokens.state;
rows.push(tokens);
if (doCache) {
this.lines[row] = tokens;
}
}
else {
var tokens = this.lines[row];
state = tokens.state;
rows.push(tokens);
}
}
return rows;
};
}).call(BackgroundTokenizer.prototype);
exports.BackgroundTokenizer = BackgroundTokenizer;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/edit_session/folding', ['require', 'exports', 'module' , 'ace/range', 'ace/edit_session/fold_line', 'ace/edit_session/fold'], function(require, exports, module) {
var Range = require("ace/range").Range;
var FoldLine = require("ace/edit_session/fold_line").FoldLine;
var Fold = require("ace/edit_session/fold").Fold;
function Folding() {
/**
* Looks up a fold at a given row/column. Possible values for side:
* -1: ignore a fold if fold.start = row/column
* +1: ignore a fold if fold.end = row/column
*/
this.getFoldAt = function(row, column, side) {
var foldLine = this.getFoldLine(row);
if (!foldLine)
return null;
var folds = foldLine.folds;
for (var i = 0; i < folds.length; i++) {
var fold = folds[i];
if (fold.range.contains(row, column)) {
if (side == 1 && fold.range.isEnd(row, column)) {
continue;
} else if (side == -1 && fold.range.isStart(row, column)) {
continue;
}
return fold;
}
}
};
/**
* Returns all folds in the given range. Note, that this will return folds
*
*/
this.getFoldsInRange = function(range) {
range = range.clone();
var start = range.start;
var end = range.end;
var foldLines = this.$foldData;
var foundFolds = [];
start.column += 1;
end.column -= 1;
for (var i = 0; i < foldLines.length; i++) {
var cmp = foldLines[i].range.compareRange(range);
if (cmp == 2) {
// Range is before foldLine. No intersection. This means,
// there might be other foldLines that intersect.
continue;
}
else if (cmp == -2) {
// Range is after foldLine. There can't be any other foldLines then,
// so let's give up.
break;
}
var folds = foldLines[i].folds;
for (var j = 0; j < folds.length; j++) {
var fold = folds[j];
cmp = fold.range.compareRange(range);
if (cmp == -2) {
break;
} else if (cmp == 2) {
continue;
} else
// WTF-state: Can happen due to -1/+1 to start/end column.
if (cmp == 42) {
break;
}
foundFolds.push(fold);
}
}
return foundFolds;
}
/**
* Returns the string between folds at the given position.
* E.g.
* foo<fold>b|ar<fold>wolrd -> "bar"
* foo<fold>bar<fold>wol|rd -> "world"
* foo<fold>bar<fo|ld>wolrd -> <null>
*
* where | means the position of row/column
*
* The trim option determs if the return string should be trimed according
* to the "side" passed with the trim value:
*
* E.g.
* foo<fold>b|ar<fold>wolrd -trim=-1> "b"
* foo<fold>bar<fold>wol|rd -trim=+1> "rld"
* fo|o<fold>bar<fold>wolrd -trim=00> "foo"
*/
this.getFoldStringAt = function(row, column, trim, foldLine) {
var foldLine = foldLine || this.getFoldLine(row);
if (!foldLine)
return null;
var lastFold = {
end: { column: 0 }
};
// TODO: Refactor to use getNextFoldTo function.
for (var i = 0; i < foldLine.folds.length; i++) {
var fold = foldLine.folds[i];
var cmp = fold.range.compareEnd(row, column);
if (cmp == -1) {
var str = this
.getLine(fold.start.row)
.substring(lastFold.end.column, fold.start.column);
break;
}
else if (cmp == 0) {
return null;
}
lastFold = fold;
}
if (!str)
str = this.getLine(fold.start.row).substring(lastFold.end.column);
if (trim == -1)
return str.substring(0, column - lastFold.end.column);
else if (trim == 1)
return str.substring(column - lastFold.end.column)
else
return str;
}
this.getFoldLine = function(docRow, startFoldLine) {
var foldData = this.$foldData;
var i = 0;
if (startFoldLine)
i = foldData.indexOf(startFoldLine);
if (i == -1)
i = 0;
for (i; i < foldData.length; i++) {
var foldLine = foldData[i];
if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) {
return foldLine;
} else if (foldLine.end.row > docRow) {
return null;
}
}
return null;
}
// returns the fold which starts after or contains docRow
this.getNextFold = function(docRow, startFoldLine) {
var foldData = this.$foldData, ans;
var i = 0;
if (startFoldLine)
i = foldData.indexOf(startFoldLine);
if (i == -1)
i = 0;
for (i; i < foldData.length; i++) {
var foldLine = foldData[i];
if (foldLine.end.row >= docRow) {
return foldLine;
}
}
return null;
}
this.getFoldedRowCount = function(first, last) {
var foldData = this.$foldData, rowCount = last-first+1;
for (var i = 0; i < foldData.length; i++) {
var foldLine = foldData[i],
end = foldLine.end.row,
start = foldLine.start.row;
if (end >= last) {
if(start < last) {
if(start >= first)
rowCount -= last-start;
else
rowCount = 0;//in one fold
}
break;
} else if(end >= first){
if (start >= first) //fold inside range
rowCount -= end-start;
else
rowCount -= end-first+1;
}
}
return rowCount;
}
this.$addFoldLine = function(foldLine) {
this.$foldData.push(foldLine);
this.$foldData.sort(function(a, b) {
return a.start.row - b.start.row;
});
return foldLine;
}
/**
* Adds a new fold.
*
* @returns
* The new created Fold object or an existing fold object in case the
* passed in range fits an existing fold exactly.
*/
this.addFold = function(placeholder, range) {
var foldData = this.$foldData;
var added = false;
if (placeholder instanceof Fold)
var fold = placeholder;
else
fold = new Fold(range, placeholder);
var startRow = fold.start.row;
var startColumn = fold.start.column;
var endRow = fold.end.row;
var endColumn = fold.end.column;
// --- Some checking ---
if (fold.placeholder.length < 2)
throw "Placeholder has to be at least 2 characters";
if (startRow == endRow && endColumn - startColumn < 2)
throw "The range has to be at least 2 characters width";
var existingFold = this.getFoldAt(startRow, startColumn, 1);
if (
existingFold
&& existingFold.range.isEnd(endRow, endColumn)
&& existingFold.range.isStart(startRow, startColumn)
) {
return fold;
}
existingFold = this.getFoldAt(startRow, startColumn, 1);
if (existingFold && !existingFold.range.isStart(startRow, startColumn))
throw "A fold can't start inside of an already existing fold";
existingFold = this.getFoldAt(endRow, endColumn, -1);
if (existingFold && !existingFold.range.isEnd(endRow, endColumn))
throw "A fold can't end inside of an already existing fold";
if (endRow >= this.doc.getLength())
throw "End of fold is outside of the document.";
if (endColumn > this.getLine(endRow).length || startColumn > this.getLine(startRow).length)
throw "End of fold is outside of the document.";
// Check if there are folds in the range we create the new fold for.
var folds = this.getFoldsInRange(fold.range);
if (folds.length > 0) {
// Remove the folds from fold data.
this.removeFolds(folds);
// Add the removed folds as subfolds on the new fold.
fold.subFolds = folds;
}
for (var i = 0; i < foldData.length; i++) {
var foldLine = foldData[i];
if (endRow == foldLine.start.row) {
foldLine.addFold(fold);
added = true;
break;
}
else if (startRow == foldLine.end.row) {
foldLine.addFold(fold);
added = true;
if (!fold.sameRow) {
// Check if we might have to merge two FoldLines.
foldLineNext = foldData[i + 1];
if (foldLineNext && foldLineNext.start.row == endRow) {
// We need to merge!
foldLine.merge(foldLineNext);
break;
}
}
break;
}
else if (endRow <= foldLine.start.row) {
break;
}
}
if (!added)
foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold));
if (this.$useWrapMode)
this.$updateWrapData(foldLine.start.row, foldLine.start.row);
// Notify that fold data has changed.
this.$modified = true;
this._dispatchEvent("changeFold", { data: fold });
return fold;
};
this.addFolds = function(folds) {
folds.forEach(function(fold) {
this.addFold(fold);
}, this);
};
this.removeFold = function(fold) {
var foldLine = fold.foldLine;
var startRow = foldLine.start.row;
var endRow = foldLine.end.row;
var foldLines = this.$foldData,
folds = foldLine.folds;
// Simple case where there is only one fold in the FoldLine such that
// the entire fold line can get removed directly.
if (folds.length == 1) {
foldLines.splice(foldLines.indexOf(foldLine), 1);
} else
// If the fold is the last fold of the foldLine, just remove it.
if (foldLine.range.isEnd(fold.end.row, fold.end.column)) {
folds.pop();
foldLine.end.row = folds[folds.length - 1].end.row;
foldLine.end.column = folds[folds.length - 1].end.column;
} else
// If the fold is the first fold of the foldLine, just remove it.
if (foldLine.range.isStart(fold.start.row, fold.start.column)) {
folds.shift();
foldLine.start.row = folds[0].start.row;
foldLine.start.column = folds[0].start.column;
} else
// We know there are more then 2 folds and the fold is not at the edge.
// This means, the fold is somewhere in between.
//
// If the fold is in one row, we just can remove it.
if (fold.sameRow) {
folds.splice(folds.indexOf(fold), 1);
} else
// The fold goes over more then one row. This means remvoing this fold
// will cause the fold line to get splitted up.
{
var newFoldLine = foldLine.split(fold.start.row, fold.start.column);
newFoldLine.folds.shift();
foldLine.start.row = folds[0].start.row;
foldLine.start.column = folds[0].start.column;
this.$addFoldLine(newFoldLine);
}
if (this.$useWrapMode) {
this.$updateWrapData(startRow, endRow);
}
// Notify that fold data has changed.
this.$modified = true;
this._dispatchEvent("changeFold", { data: fold });
}
this.removeFolds = function(folds) {
// We need to clone the folds array passed in as it might be the folds
// array of a fold line and as we call this.removeFold(fold), folds
// are removed from folds and changes the current index.
var cloneFolds = [];
for (var i = 0; i < folds.length; i++) {
cloneFolds.push(folds[i]);
}
cloneFolds.forEach(function(fold) {
this.removeFold(fold);
}, this);
this.$modified = true;
}
this.expandFold = function(fold) {
this.removeFold(fold);
fold.subFolds.forEach(function(fold) {
this.addFold(fold);
}, this);
fold.subFolds = [];
}
this.expandFolds = function(folds) {
folds.forEach(function(fold) {
this.expandFold(fold);
}, this);
}
/**
* Checks if a given documentRow is folded. This is true if there are some
* folded parts such that some parts of the line is still visible.
**/
this.isRowFolded = function(docRow, startFoldRow) {
return !!this.getFoldLine(docRow, startFoldRow);
};
this.getRowFoldEnd = function(docRow, startFoldRow) {
var foldLine = this.getFoldLine(docRow, startFoldRow);
return (foldLine
? foldLine.end.row
: docRow)
};
this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) {
if (startRow == null) {
startRow = foldLine.start.row;
startColumn = 0;
}
if (endRow == null) {
endRow = foldLine.end.row;
endColumn = this.getLine(endRow).length;
}
// Build the textline using the FoldLine walker.
var line = "";
var doc = this.doc;
var textLine = "";
foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
if (row < startRow) {
return;
} else if (row == startRow) {
if (column < startColumn) {
return;
}
lastColumn = Math.max(startColumn, lastColumn);
}
if (placeholder) {
textLine += placeholder;
} else {
textLine += doc.getLine(row).substring(lastColumn, column);
}
}.bind(this), endRow, endColumn);
return textLine;
};
this.getDisplayLine = function(row, endColumn, startRow, startColumn) {
var foldLine = this.getFoldLine(row);
if (!foldLine) {
var line;
line = this.doc.getLine(row);
return line.substring(startColumn || 0, endColumn || line.length);
} else {
return this.getFoldDisplayLine(
foldLine, row, endColumn, startRow, startColumn);
}
};
this.$cloneFoldData = function() {
var foldData = this.$foldData;
var fd = [];
fd = this.$foldData.map(function(foldLine) {
var folds = foldLine.folds.map(function(fold) {
return fold.clone();
});
return new FoldLine(fd, folds);
});
return fd;
};
}
exports.Folding = Folding;
});/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/edit_session/fold_line', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("ace/range").Range;
/**
* If the an array is passed in, the folds are expected to be sorted already.
*/
function FoldLine(foldData, folds) {
this.foldData = foldData;
if (Array.isArray(folds)) {
this.folds = folds;
} else {
folds = this.folds = [ folds ];
}
var last = folds[folds.length - 1]
this.range = new Range(folds[0].start.row, folds[0].start.column,
last.end.row, last.end.column);
this.start = this.range.start;
this.end = this.range.end;
this.folds.forEach(function(fold) {
fold.setFoldLine(this);
}, this);
}
(function() {
/**
* Note: This doesn't update wrapData!
*/
this.shiftRow = function(shift) {
this.start.row += shift;
this.end.row += shift;
this.folds.forEach(function(fold) {
fold.start.row += shift;
fold.end.row += shift;
});
}
this.addFold = function(fold) {
if (fold.sameRow) {
if (fold.start.row < this.startRow || fold.endRow > this.endRow) {
throw "Can't add a fold to this FoldLine as it has no connection";
}
this.folds.push(fold);
this.folds.sort(function(a, b) {
return -a.range.compareEnd(b.start.row, b.start.column);
});
if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) {
this.end.row = fold.end.row;
this.end.column = fold.end.column;
} else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) {
this.start.row = fold.start.row;
this.start.column = fold.start.column;
}
} else if (fold.start.row == this.end.row) {
this.folds.push(fold);
this.end.row = fold.end.row;
this.end.column = fold.end.column;
} else if (fold.end.row == this.start.row) {
this.folds.unshift(fold);
this.start.row = fold.start.row;
this.start.column = fold.start.column;
} else {
throw "Trying to add fold to FoldRow that doesn't have a matching row";
}
fold.foldLine = this;
}
this.containsRow = function(row) {
return row >= this.start.row && row <= this.end.row;
}
this.walk = function(callback, endRow, endColumn) {
var lastEnd = 0,
folds = this.folds,
fold,
comp, stop, isNewRow = true;
if (endRow == null) {
endRow = this.end.row;
endColumn = this.end.column;
}
for (var i = 0; i < folds.length; i++) {
fold = folds[i];
comp = fold.range.compareStart(endRow, endColumn);
// This fold is after the endRow/Column.
if (comp == -1) {
callback(null, endRow, endColumn, lastEnd, isNewRow);
return;
}
stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow);
stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd);
// If the user requested to stop the walk or endRow/endColumn is
// inside of this fold (comp == 0), then end here.
if (stop || comp == 0) {
return;
}
// Note the new lastEnd might not be on the same line. However,
// it's the callback's job to recognize this.
isNewRow = !fold.sameRow;
lastEnd = fold.end.column;
}
callback(null, endRow, endColumn, lastEnd, isNewRow);
}
this.getNextFoldTo = function(row, column) {
var fold, cmp;
for (var i = 0; i < this.folds.length; i++) {
fold = this.folds[i];
cmp = fold.range.compareEnd(row, column);
if (cmp == -1) {
return {
fold: fold,
kind: "after"
};
} else if (cmp == 0) {
return {
fold: fold,
kind: "inside"
}
}
}
return null;
}
this.addRemoveChars = function(row, column, len) {
var ret = this.getNextFoldTo(row, column),
fold, folds;
if (ret) {
fold = ret.fold;
if (ret.kind == "inside"
&& fold.start.column != column
&& fold.start.row != row)
{
throw "Moving characters inside of a fold should never be reached";
} else if (fold.start.row == row) {
folds = this.folds;
var i = folds.indexOf(fold);
if (i == 0) {
this.start.column += len;
}
for (i; i < folds.length; i++) {
fold = folds[i];
fold.start.column += len;
if (!fold.sameRow) {
return;
}
fold.end.column += len;
}
this.end.column += len;
}
}
}
this.split = function(row, column) {
var fold = this.getNextFoldTo(row, column).fold,
folds = this.folds;
var foldData = this.foldData;
if (!fold) {
return null;
}
var i = folds.indexOf(fold);
var foldBefore = folds[i - 1];
this.end.row = foldBefore.end.row;
this.end.column = foldBefore.end.column;
// Remove the folds after row/column and create a new FoldLine
// containing these removed folds.
folds = folds.splice(i, folds.length - i);
var newFoldLine = new FoldLine(foldData, folds);
foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine);
return newFoldLine;
}
this.merge = function(foldLineNext) {
var folds = foldLineNext.folds;
for (var i = 0; i < folds.length; i++) {
this.addFold(folds[i]);
}
// Remove the foldLineNext - no longer needed, as
// it's merged now with foldLineNext.
var foldData = this.foldData;
foldData.splice(foldData.indexOf(foldLineNext), 1);
}
this.toString = function() {
var ret = [this.range.toString() + ": [" ];
this.folds.forEach(function(fold) {
ret.push(" " + fold.toString());
});
ret.push("]")
return ret.join("\n");
}
this.idxToPosition = function(idx) {
var lastFoldEndColumn = 0;
var fold;
for (var i = 0; i < this.folds.length; i++) {
var fold = this.folds[i];
idx -= fold.start.column - lastFoldEndColumn;
if (idx < 0) {
return {
row: fold.start.row,
column: fold.start.column + idx
};
}
idx -= fold.placeholder.length;
if (idx < 0) {
return fold.start;
}
lastFoldEndColumn = fold.end.column;
}
return {
row: this.end.row,
column: this.end.column + idx
};
}
}).call(FoldLine.prototype);
exports.FoldLine = FoldLine;
});/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/edit_session/fold', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* Simple fold-data struct.
**/
var Fold = exports.Fold = function(range, placeholder) {
this.foldLine = null;
this.placeholder = placeholder;
this.range = range;
this.start = range.start;
this.end = range.end;
this.sameRow = range.start.row == range.end.row;
this.subFolds = [];
};
(function() {
this.toString = function() {
return '"' + this.placeholder + '" ' + this.range.toString();
};
this.setFoldLine = function(foldLine) {
this.foldLine = foldLine;
this.subFolds.forEach(function(fold) {
fold.setFoldLine(foldLine);
});
};
this.clone = function() {
var range = this.range.clone();
var fold = new Fold(range, this.placeholder);
this.subFolds.forEach(function(subFold) {
fold.subFolds.push(subFold.clone());
});
return fold;
};
}).call(Fold.prototype);
});/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/search', ['require', 'exports', 'module' , 'pilot/lang', 'pilot/oop', 'ace/range'], function(require, exports, module) {
var lang = require("pilot/lang");
var oop = require("pilot/oop");
var Range = require("ace/range").Range;
var Search = function() {
this.$options = {
needle: "",
backwards: false,
wrap: false,
caseSensitive: false,
wholeWord: false,
scope: Search.ALL,
regExp: false
};
};
Search.ALL = 1;
Search.SELECTION = 2;
(function() {
this.set = function(options) {
oop.mixin(this.$options, options);
return this;
};
this.getOptions = function() {
return lang.copyObject(this.$options);
};
this.find = function(session) {
if (!this.$options.needle)
return null;
if (this.$options.backwards) {
var iterator = this.$backwardMatchIterator(session);
} else {
iterator = this.$forwardMatchIterator(session);
}
var firstRange = null;
iterator.forEach(function(range) {
firstRange = range;
return true;
});
return firstRange;
};
this.findAll = function(session) {
if (!this.$options.needle)
return [];
if (this.$options.backwards) {
var iterator = this.$backwardMatchIterator(session);
} else {
iterator = this.$forwardMatchIterator(session);
}
var ranges = [];
iterator.forEach(function(range) {
ranges.push(range);
});
return ranges;
};
this.replace = function(input, replacement) {
var re = this.$assembleRegExp();
var match = re.exec(input);
if (match && match[0].length == input.length) {
if (this.$options.regExp) {
return input.replace(re, replacement);
} else {
return replacement;
}
} else {
return null;
}
};
this.$forwardMatchIterator = function(session) {
var re = this.$assembleRegExp();
var self = this;
return {
forEach: function(callback) {
self.$forwardLineIterator(session).forEach(function(line, startIndex, row) {
if (startIndex) {
line = line.substring(startIndex);
}
var matches = [];
line.replace(re, function(str) {
var offset = arguments[arguments.length-2];
matches.push({
str: str,
offset: startIndex + offset
});
return str;
});
for (var i=0; i<matches.length; i++) {
var match = matches[i];
var range = self.$rangeFromMatch(row, match.offset, match.str.length);
if (callback(range))
return true;
}
});
}
};
};
this.$backwardMatchIterator = function(session) {
var re = this.$assembleRegExp();
var self = this;
return {
forEach: function(callback) {
self.$backwardLineIterator(session).forEach(function(line, startIndex, row) {
if (startIndex) {
line = line.substring(startIndex);
}
var matches = [];
line.replace(re, function(str, offset) {
matches.push({
str: str,
offset: startIndex + offset
});
return str;
});
for (var i=matches.length-1; i>= 0; i--) {
var match = matches[i];
var range = self.$rangeFromMatch(row, match.offset, match.str.length);
if (callback(range))
return true;
}
});
}
};
};
this.$rangeFromMatch = function(row, column, length) {
return new Range(row, column, row, column+length);
};
this.$assembleRegExp = function() {
if (this.$options.regExp) {
var needle = this.$options.needle;
} else {
needle = lang.escapeRegExp(this.$options.needle);
}
if (this.$options.wholeWord) {
needle = "\\b" + needle + "\\b";
}
var modifier = "g";
if (!this.$options.caseSensitive) {
modifier += "i";
}
var re = new RegExp(needle, modifier);
return re;
};
this.$forwardLineIterator = function(session) {
var searchSelection = this.$options.scope == Search.SELECTION;
var range = session.getSelection().getRange();
var start = session.getSelection().getCursor();
var firstRow = searchSelection ? range.start.row : 0;
var firstColumn = searchSelection ? range.start.column : 0;
var lastRow = searchSelection ? range.end.row : session.getLength() - 1;
var wrap = this.$options.wrap;
var inWrap = false;
function getLine(row) {
var line = session.getLine(row);
if (searchSelection && row == range.end.row) {
line = line.substring(0, range.end.column);
}
if (inWrap && row == start.row) {
line = line.substring(0, start.column);
}
return line;
}
return {
forEach: function(callback) {
var row = start.row;
var line = getLine(row);
var startIndex = start.column;
var stop = false;
inWrap = false;
while (!callback(line, startIndex, row)) {
if (stop) {
return;
}
row++;
startIndex = 0;
if (row > lastRow) {
if (wrap) {
row = firstRow;
startIndex = firstColumn;
inWrap = true;
} else {
return;
}
}
if (row == start.row)
stop = true;
line = getLine(row);
}
}
};
};
this.$backwardLineIterator = function(session) {
var searchSelection = this.$options.scope == Search.SELECTION;
var range = session.getSelection().getRange();
var start = searchSelection ? range.end : range.start;
var firstRow = searchSelection ? range.start.row : 0;
var firstColumn = searchSelection ? range.start.column : 0;
var lastRow = searchSelection ? range.end.row : session.getLength() - 1;
var wrap = this.$options.wrap;
return {
forEach : function(callback) {
var row = start.row;
var line = session.getLine(row).substring(0, start.column);
var startIndex = 0;
var stop = false;
var inWrap = false;
while (!callback(line, startIndex, row)) {
if (stop)
return;
row--;
startIndex = 0;
if (row < firstRow) {
if (wrap) {
row = lastRow;
inWrap = true;
} else {
return;
}
}
if (row == start.row)
stop = true;
line = session.getLine(row);
if (searchSelection) {
if (row == firstRow)
startIndex = firstColumn;
else if (row == lastRow)
line = line.substring(0, range.end.column);
}
if (inWrap && row == start.row)
startIndex = start.column;
}
}
};
};
}).call(Search.prototype);
exports.Search = Search;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/undomanager', ['require', 'exports', 'module' ], function(require, exports, module) {
var UndoManager = function() {
this.reset();
};
(function() {
this.execute = function(options) {
var deltas = options.args[0];
this.$doc = options.args[1];
this.$undoStack.push(deltas);
this.$redoStack = [];
};
this.undo = function(dontSelect) {
var deltas = this.$undoStack.pop();
var undoSelectionRange = null;
if (deltas) {
undoSelectionRange =
this.$doc.undoChanges(deltas, dontSelect);
this.$redoStack.push(deltas);
}
return undoSelectionRange;
};
this.redo = function(dontSelect) {
var deltas = this.$redoStack.pop();
var redoSelectionRange = null;
if (deltas) {
redoSelectionRange =
this.$doc.redoChanges(deltas, dontSelect);
this.$undoStack.push(deltas);
}
return redoSelectionRange;
};
this.reset = function() {
this.$undoStack = [];
this.$redoStack = [];
};
this.hasUndo = function() {
return this.$undoStack.length > 0;
};
this.hasRedo = function() {
return this.$redoStack.length > 0;
};
}).call(UndoManager.prototype);
exports.UndoManager = UndoManager;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian@ajax.org>
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/virtual_renderer', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/dom', 'pilot/event', 'pilot/useragent', 'ace/layer/gutter', 'ace/layer/marker', 'ace/layer/text', 'ace/layer/cursor', 'ace/scrollbar', 'ace/renderloop', 'pilot/event_emitter', 'text/ace/css/editor.css'], function(require, exports, module) {
var oop = require("pilot/oop");
var dom = require("pilot/dom");
var event = require("pilot/event");
var useragent = require("pilot/useragent");
var GutterLayer = require("ace/layer/gutter").Gutter;
var MarkerLayer = require("ace/layer/marker").Marker;
var TextLayer = require("ace/layer/text").Text;
var CursorLayer = require("ace/layer/cursor").Cursor;
var ScrollBar = require("ace/scrollbar").ScrollBar;
var RenderLoop = require("ace/renderloop").RenderLoop;
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var editorCss = require("text/ace/css/editor.css");
// import CSS once
dom.importCssString(editorCss);
var VirtualRenderer = function(container, theme) {
this.container = container;
dom.addCssClass(this.container, "ace_editor");
this.setTheme(theme);
this.$gutter = dom.createElement("div");
this.$gutter.className = "ace_gutter";
this.container.appendChild(this.$gutter);
this.scroller = dom.createElement("div");
this.scroller.className = "ace_scroller";
this.container.appendChild(this.scroller);
this.content = dom.createElement("div");
this.content.className = "ace_content";
this.scroller.appendChild(this.content);
this.$gutterLayer = new GutterLayer(this.$gutter);
this.$markerBack = new MarkerLayer(this.content);
var textLayer = this.$textLayer = new TextLayer(this.content);
this.canvas = textLayer.element;
this.$markerFront = new MarkerLayer(this.content);
this.characterWidth = textLayer.getCharacterWidth();
this.lineHeight = textLayer.getLineHeight();
this.$cursorLayer = new CursorLayer(this.content);
this.$cursorPadding = 8;
// Indicates whether the horizontal scrollbar is visible
this.$horizScroll = true;
this.$horizScrollAlwaysVisible = true;
this.scrollBar = new ScrollBar(container);
this.scrollBar.addEventListener("scroll", this.onScroll.bind(this));
this.scrollTop = 0;
this.cursorPos = {
row : 0,
column : 0
};
var _self = this;
this.$textLayer.addEventListener("changeCharaterSize", function() {
_self.characterWidth = textLayer.getCharacterWidth();
_self.lineHeight = textLayer.getLineHeight();
_self.$updatePrintMargin();
_self.onResize(true);
_self.$loop.schedule(_self.CHANGE_FULL);
});
event.addListener(this.$gutter, "click", this.$onGutterClick.bind(this));
event.addListener(this.$gutter, "dblclick", this.$onGutterClick.bind(this));
this.$size = {
width: 0,
height: 0,
scrollerHeight: 0,
scrollerWidth: 0
};
this.layerConfig = {
width : 1,
padding : 0,
firstRow : 0,
firstRowScreen: 0,
lastRow : 0,
lineHeight : 1,
characterWidth : 1,
minHeight : 1,
maxHeight : 1,
offset : 0,
height : 1
};
this.$loop = new RenderLoop(this.$renderChanges.bind(this));
this.$loop.schedule(this.CHANGE_FULL);
this.setPadding(4);
this.$updatePrintMargin();
};
(function() {
this.showGutter = true;
this.CHANGE_CURSOR = 1;
this.CHANGE_MARKER = 2;
this.CHANGE_GUTTER = 4;
this.CHANGE_SCROLL = 8;
this.CHANGE_LINES = 16;
this.CHANGE_TEXT = 32;
this.CHANGE_SIZE = 64;
this.CHANGE_MARKER_BACK = 128;
this.CHANGE_MARKER_FRONT = 256;
this.CHANGE_FULL = 512;
oop.implement(this, EventEmitter);
this.setSession = function(session) {
this.session = session;
this.$cursorLayer.setSession(session);
this.$markerBack.setSession(session);
this.$markerFront.setSession(session);
this.$gutterLayer.setSession(session);
this.$textLayer.setSession(session);
this.$loop.schedule(this.CHANGE_FULL);
};
/**
* Triggers partial update of the text layer
*/
this.updateLines = function(firstRow, lastRow) {
if (lastRow === undefined)
lastRow = Infinity;
if (!this.$changedLines) {
this.$changedLines = {
firstRow: firstRow,
lastRow: lastRow
};
}
else {
if (this.$changedLines.firstRow > firstRow)
this.$changedLines.firstRow = firstRow;
if (this.$changedLines.lastRow < lastRow)
this.$changedLines.lastRow = lastRow;
}
this.$loop.schedule(this.CHANGE_LINES);
};
/**
* Triggers full update of the text layer
*/
this.updateText = function() {
this.$loop.schedule(this.CHANGE_TEXT);
};
/**
* Triggers a full update of all layers
*/
this.updateFull = function() {
this.$loop.schedule(this.CHANGE_FULL);
};
this.updateFontSize = function() {
this.$textLayer.checkForSizeChanges();
};
/**
* Triggers resize of the editor
*/
this.onResize = function(force) {
var changes = this.CHANGE_SIZE;
var size = this.$size;
var height = dom.getInnerHeight(this.container);
if (force || size.height != height) {
size.height = height;
this.scroller.style.height = height + "px";
size.scrollerHeight = this.scroller.clientHeight;
this.scrollBar.setHeight(size.scrollerHeight);
if (this.session) {
this.scrollToY(this.getScrollTop());
changes = changes | this.CHANGE_FULL;
}
}
var width = dom.getInnerWidth(this.container);
if (force || size.width != width) {
size.width = width;
var gutterWidth = this.showGutter ? this.$gutter.offsetWidth : 0;
this.scroller.style.left = gutterWidth + "px";
size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBar.getWidth())
this.scroller.style.width = size.scrollerWidth + "px";
if (this.session.getUseWrapMode() && this.adjustWrapLimit() || force)
changes = changes | this.CHANGE_FULL;
}
this.$loop.schedule(changes);
};
this.adjustWrapLimit = function(){
var availableWidth = this.$size.scrollerWidth - this.$padding * 2;
var limit = Math.floor(availableWidth / this.characterWidth) - 1;
return this.session.adjustWrapLimit(limit);
};
this.$onGutterClick = function(e) {
var pageX = event.getDocumentX(e);
var pageY = event.getDocumentY(e);
this._dispatchEvent("gutter" + e.type, {
row: this.screenToTextCoordinates(pageX, pageY).row,
htmlEvent: e
});
};
this.setShowInvisibles = function(showInvisibles) {
if (this.$textLayer.setShowInvisibles(showInvisibles))
this.$loop.schedule(this.CHANGE_TEXT);
};
this.getShowInvisibles = function() {
return this.$textLayer.showInvisibles;
};
this.$showPrintMargin = true;
this.setShowPrintMargin = function(showPrintMargin) {
this.$showPrintMargin = showPrintMargin;
this.$updatePrintMargin();
};
this.getShowPrintMargin = function() {
return this.$showPrintMargin;
};
this.$printMarginColumn = 80;
this.setPrintMarginColumn = function(showPrintMargin) {
this.$printMarginColumn = showPrintMargin;
this.$updatePrintMargin();
};
this.getPrintMarginColumn = function() {
return this.$printMarginColumn;
};
this.getShowGutter = function(){
return this.showGutter;
};
this.setShowGutter = function(show){
if(this.showGutter === show)
return;
this.$gutter.style.display = show ? "block" : "none";
this.showGutter = show;
this.onResize(true);
};
this.$updatePrintMargin = function() {
var containerEl;
if (!this.$showPrintMargin && !this.$printMarginEl)
return;
if (!this.$printMarginEl) {
containerEl = dom.createElement("div");
containerEl.className = "ace_print_margin_layer";
this.$printMarginEl = dom.createElement("div");
this.$printMarginEl.className = "ace_print_margin";
containerEl.appendChild(this.$printMarginEl);
this.content.insertBefore(containerEl, this.$textLayer.element);
}
var style = this.$printMarginEl.style;
style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding * 2) + "px";
style.visibility = this.$showPrintMargin ? "visible" : "hidden";
};
this.getContainerElement = function() {
return this.container;
};
this.getMouseEventTarget = function() {
return this.content;
};
this.getTextAreaContainer = function() {
return this.container;
};
this.moveTextAreaToCursor = function(textarea) {
// in IE the native cursor always shines through
if (useragent.isIE)
return;
var pos = this.$cursorLayer.getPixelPosition();
if (!pos)
return;
var bounds = this.content.getBoundingClientRect();
var offset = this.layerConfig.offset;
textarea.style.left = (bounds.left + pos.left + this.$padding) + "px";
textarea.style.top = (bounds.top + pos.top - this.scrollTop + offset) + "px";
};
this.getFirstVisibleRow = function() {
return this.layerConfig.firstRow;
};
this.getFirstFullyVisibleRow = function() {
return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1);
};
this.getLastFullyVisibleRow = function() {
var flint = Math.floor((this.layerConfig.height + this.layerConfig.offset) / this.layerConfig.lineHeight);
return this.layerConfig.firstRow - 1 + flint;
};
this.getLastVisibleRow = function() {
return this.layerConfig.lastRow;
};
this.$padding = null;
this.setPadding = function(padding) {
this.$padding = padding;
this.$textLayer.setPadding(padding);
this.$cursorLayer.setPadding(padding);
this.$markerFront.setPadding(padding);
this.$markerBack.setPadding(padding);
this.$loop.schedule(this.CHANGE_FULL);
this.$updatePrintMargin();
};
this.getHScrollBarAlwaysVisible = function() {
return this.$horizScrollAlwaysVisible;
};
this.setHScrollBarAlwaysVisible = function(alwaysVisible) {
if (this.$horizScrollAlwaysVisible != alwaysVisible) {
this.$horizScrollAlwaysVisible = alwaysVisible;
if (!this.$horizScrollAlwaysVisible || !this.$horizScroll)
this.$loop.schedule(this.CHANGE_SCROLL);
}
};
this.onScroll = function(e) {
this.scrollToY(e.data);
};
this.$updateScrollBar = function() {
this.scrollBar.setInnerHeight(this.layerConfig.maxHeight);
this.scrollBar.setScrollTop(this.scrollTop);
};
this.$renderChanges = function(changes) {
if (!changes || !this.session)
return;
// text, scrolling and resize changes can cause the view port size to change
if (changes & this.CHANGE_FULL ||
changes & this.CHANGE_SIZE ||
changes & this.CHANGE_TEXT ||
changes & this.CHANGE_LINES ||
changes & this.CHANGE_SCROLL
)
this.$computeLayerConfig();
// full
if (changes & this.CHANGE_FULL) {
this.$textLayer.update(this.layerConfig);
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
this.$markerBack.update(this.layerConfig);
this.$markerFront.update(this.layerConfig);
this.$cursorLayer.update(this.layerConfig);
this.$updateScrollBar();
return;
}
// scrolling
if (changes & this.CHANGE_SCROLL) {
if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES)
this.$textLayer.update(this.layerConfig);
else
this.$textLayer.scrollLines(this.layerConfig);
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
this.$markerBack.update(this.layerConfig);
this.$markerFront.update(this.layerConfig);
this.$cursorLayer.update(this.layerConfig);
this.$updateScrollBar();
return;
}
if (changes & this.CHANGE_TEXT) {
this.$textLayer.update(this.layerConfig);
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
}
else if (changes & this.CHANGE_LINES) {
this.$updateLines();
this.$updateScrollBar();
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
} else if (changes & this.CHANGE_GUTTER) {
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
}
if (changes & this.CHANGE_CURSOR)
this.$cursorLayer.update(this.layerConfig);
if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) {
this.$markerFront.update(this.layerConfig);
}
if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) {
this.$markerBack.update(this.layerConfig);
}
if (changes & this.CHANGE_SIZE)
this.$updateScrollBar();
};
this.$computeLayerConfig = function() {
var session = this.session;
var offset = this.scrollTop % this.lineHeight;
var minHeight = this.$size.scrollerHeight + this.lineHeight;
var longestLine = this.$getLongestLine();
var widthChanged = this.layerConfig.width != longestLine;
var horizScroll = this.$horizScrollAlwaysVisible || this.$size.scrollerWidth - longestLine < 0;
var horizScrollChanged = this.$horizScroll !== horizScroll;
this.$horizScroll = horizScroll;
if (horizScrollChanged)
this.scroller.style.overflowX = horizScroll ? "scroll" : "hidden";
var maxHeight = this.session.getScreenLength() * this.lineHeight;
this.scrollTop = Math.max(0, Math.min(this.scrollTop, maxHeight - this.$size.scrollerHeight));
var lineCount = Math.ceil(minHeight / this.lineHeight) - 1;
var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight));
var lastRow = firstRow + lineCount;
// Map lines on the screen to lines in the document.
var firstRowScreen, firstRowHeight;
var lineHeight = { lineHeight: this.lineHeight };
firstRow = session.screenToDocumentRow(firstRow, 0);
// Check if firstRow is inside of a foldLine. If true, then use the first
// row of the foldLine.
var foldLine = session.getFoldLine(firstRow);
if (foldLine) {
firstRow = foldLine.start.row;
}
firstRowScreen = session.documentToScreenRow(firstRow, 0);
firstRowHeight = session.getRowHeight(lineHeight, firstRow);
lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1);
minHeight = this.$size.scrollerHeight + session.getRowHeight(lineHeight, lastRow)+
firstRowHeight;
offset = this.scrollTop - firstRowScreen * this.lineHeight;
this.layerConfig = {
width : longestLine,
padding : this.$padding,
firstRow : firstRow,
firstRowScreen: firstRowScreen,
lastRow : lastRow,
lineHeight : this.lineHeight,
characterWidth : this.characterWidth,
minHeight : minHeight,
maxHeight : maxHeight,
offset : offset,
height : this.$size.scrollerHeight
};
// For debugging.
// console.log(JSON.stringify(this.layerConfig));
this.$gutterLayer.element.style.marginTop = (-offset) + "px";
this.content.style.marginTop = (-offset) + "px";
this.content.style.width = longestLine + "px";
this.content.style.height = minHeight + "px";
// scroller.scrollWidth was smaller than scrollLeft we needed
if (this.$desiredScrollLeft) {
this.scrollToX(this.$desiredScrollLeft);
this.$desiredScrollLeft = 0;
}
// Horizontal scrollbar visibility may have changed, which changes
// the client height of the scroller
if (horizScrollChanged)
this.onResize(true);
};
this.$updateLines = function() {
var firstRow = this.$changedLines.firstRow;
var lastRow = this.$changedLines.lastRow;
this.$changedLines = null;
var layerConfig = this.layerConfig;
// if the update changes the width of the document do a full redraw
if (layerConfig.width != this.$getLongestLine())
return this.$textLayer.update(layerConfig);
if (firstRow > layerConfig.lastRow + 1) { return; }
if (lastRow < layerConfig.firstRow) { return; }
// if the last row is unknown -> redraw everything
if (lastRow === Infinity) {
if (this.showGutter)
this.$gutterLayer.update(layerConfig);
this.$textLayer.update(layerConfig);
return;
}
// else update only the changed rows
this.$textLayer.updateLines(layerConfig, firstRow, lastRow);
};
this.$getLongestLine = function() {
var charCount = this.session.getScreenWidth() + 1;
if (this.$textLayer.showInvisibles)
charCount += 1;
return Math.max(this.$size.scrollerWidth, Math.round(charCount * this.characterWidth));
};
this.updateFrontMarkers = function() {
this.$markerFront.setMarkers(this.session.getMarkers(true));
this.$loop.schedule(this.CHANGE_MARKER_FRONT);
};
this.updateBackMarkers = function() {
this.$markerBack.setMarkers(this.session.getMarkers());
this.$loop.schedule(this.CHANGE_MARKER_BACK);
};
this.addGutterDecoration = function(row, className){
this.$gutterLayer.addGutterDecoration(row, className);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.removeGutterDecoration = function(row, className){
this.$gutterLayer.removeGutterDecoration(row, className);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.setBreakpoints = function(rows) {
this.$gutterLayer.setBreakpoints(rows);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.setAnnotations = function(annotations) {
this.$gutterLayer.setAnnotations(annotations);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.updateCursor = function() {
this.$loop.schedule(this.CHANGE_CURSOR);
};
this.hideCursor = function() {
this.$cursorLayer.hideCursor();
};
this.showCursor = function() {
this.$cursorLayer.showCursor();
};
this.scrollCursorIntoView = function() {
// the editor is not visible
if (this.$size.scrollerHeight === 0)
return;
var pos = this.$cursorLayer.getPixelPosition();
var left = pos.left + this.$padding;
var top = pos.top;
if (this.scrollTop > top) {
this.scrollToY(top);
}
if (this.scrollTop + this.$size.scrollerHeight < top + this.lineHeight) {
this.scrollToY(top + this.lineHeight - this.$size.scrollerHeight);
}
var scrollLeft = this.scroller.scrollLeft;
if (scrollLeft > left) {
this.scrollToX(left);
}
if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) {
if (left > this.layerConfig.width)
this.$desiredScrollLeft = left + 2 * this.characterWidth;
else
this.scrollToX(Math.round(left + this.characterWidth - this.$size.scrollerWidth));
}
};
this.getScrollTop = function() {
return this.scrollTop;
};
this.getScrollLeft = function() {
return this.scroller.scrollLeft;
};
this.getScrollTopRow = function() {
return this.scrollTop / this.lineHeight;
};
this.getScrollBottomRow = function() {
return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1);
};
this.scrollToRow = function(row) {
this.scrollToY(row * this.lineHeight);
};
this.scrollToLine = function(line, center) {
var lineHeight = { lineHeight: this.lineHeight };
var offset = 0;
for (var l = 1; l < line; l++) {
offset += this.session.getRowHeight(lineHeight, l-1);
}
if (center) {
offset -= this.$size.scrollerHeight / 2;
}
this.scrollToY(offset);
};
this.scrollToY = function(scrollTop) {
// after calling scrollBar.setScrollTop
// scrollbar sends us event with same scrollTop. ignore it
scrollTop = Math.max(0, scrollTop);
if (this.scrollTop !== scrollTop) {
this.$loop.schedule(this.CHANGE_SCROLL);
this.scrollTop = scrollTop;
}
};
this.scrollToX = function(scrollLeft) {
if (scrollLeft <= this.$padding)
scrollLeft = 0;
this.scroller.scrollLeft = scrollLeft;
};
this.scrollBy = function(deltaX, deltaY) {
deltaY && this.scrollToY(this.scrollTop + deltaY);
deltaX && this.scrollToX(this.scroller.scrollLeft + deltaX);
};
this.screenToTextCoordinates = function(pageX, pageY) {
var canvasPos = this.scroller.getBoundingClientRect();
var col = Math.round((pageX + this.scroller.scrollLeft - canvasPos.left - this.$padding - dom.getPageScrollLeft())
/ this.characterWidth);
var row = Math.floor((pageY + this.scrollTop - canvasPos.top - dom.getPageScrollTop())
/ this.lineHeight);
return this.session.screenToDocumentPosition(row, Math.max(col, 0));
};
this.textToScreenCoordinates = function(row, column) {
var canvasPos = this.scroller.getBoundingClientRect();
var pos = this.session.documentToScreenPosition(row, column);
var x = this.$padding + Math.round(pos.column * this.characterWidth);
var y = pos.row * this.lineHeight;
return {
pageX: canvasPos.left + x - this.getScrollLeft(),
pageY: canvasPos.top + y - this.getScrollTop()
};
};
this.visualizeFocus = function() {
dom.addCssClass(this.container, "ace_focus");
};
this.visualizeBlur = function() {
dom.removeCssClass(this.container, "ace_focus");
};
this.showComposition = function(position) {
if (!this.$composition) {
this.$composition = dom.createElement("div");
this.$composition.className = "ace_composition";
this.content.appendChild(this.$composition);
}
this.$composition.innerHTML = " ";
var pos = this.$cursorLayer.getPixelPosition();
var style = this.$composition.style;
style.top = pos.top + "px";
style.left = (pos.left + this.$padding) + "px";
style.height = this.lineHeight + "px";
this.hideCursor();
};
this.setCompositionText = function(text) {
dom.setInnerText(this.$composition, text);
};
this.hideComposition = function() {
this.showCursor();
if (!this.$composition)
return;
var style = this.$composition.style;
style.top = "-10000px";
style.left = "-10000px";
};
this.setTheme = function(theme) {
var _self = this;
this.$themeValue = theme;
if (!theme || typeof theme == "string") {
theme = theme || "ace/theme/textmate";
require([theme], function(theme) {
afterLoad(theme);
});
} else {
afterLoad(theme);
}
function afterLoad(theme) {
if (_self.$theme)
dom.removeCssClass(_self.container, _self.$theme);
_self.$theme = theme ? theme.cssClass : null;
if (_self.$theme)
dom.addCssClass(_self.container, _self.$theme);
// force re-measure of the gutter width
if (_self.$size) {
_self.$size.width = 0;
_self.onResize();
}
}
};
this.getTheme = function() {
return this.$themeValue;
};
// Methods allows to add / remove CSS classnames to the editor element.
// This feature can be used by plug-ins to provide a visual indication of
// a certain mode that editor is in.
this.setStyle = function setStyle(style) {
dom.addCssClass(this.container, style);
};
this.unsetStyle = function unsetStyle(style) {
dom.removeCssClass(this.container, style);
};
this.destroy = function() {
this.$textLayer.destroy();
this.$cursorLayer.destroy();
};
}).call(VirtualRenderer.prototype);
exports.VirtualRenderer = VirtualRenderer;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/layer/gutter', ['require', 'exports', 'module' , 'pilot/dom'], function(require, exports, module) {
var dom = require("pilot/dom");
var Gutter = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_gutter-layer";
parentEl.appendChild(this.element);
this.$breakpoints = [];
this.$annotations = [];
this.$decorations = [];
};
(function() {
this.setSession = function(session) {
this.session = session;
};
this.addGutterDecoration = function(row, className){
if (!this.$decorations[row])
this.$decorations[row] = "";
this.$decorations[row] += " ace_" + className;
}
this.removeGutterDecoration = function(row, className){
this.$decorations[row] = this.$decorations[row].replace(" ace_" + className, "");
};
this.setBreakpoints = function(rows) {
this.$breakpoints = rows.concat();
};
this.setAnnotations = function(annotations) {
// iterate over sparse array
this.$annotations = [];
for (var row in annotations) if (annotations.hasOwnProperty(row)) {
var rowAnnotations = annotations[row];
if (!rowAnnotations)
continue;
var rowInfo = this.$annotations[row] = {
text: []
};
for (var i=0; i<rowAnnotations.length; i++) {
var annotation = rowAnnotations[i];
rowInfo.text.push(annotation.text.replace(/"/g, """).replace(/'/g, "’").replace(/</, "<"));
var type = annotation.type;
if (type == "error")
rowInfo.className = "ace_error";
else if (type == "warning" && rowInfo.className != "ace_error")
rowInfo.className = "ace_warning";
else if (type == "info" && (!rowInfo.className))
rowInfo.className = "ace_info";
}
}
};
this.update = function(config) {
this.$config = config;
var emptyAnno = {className: "", text: []};
var html = [];
var i = config.firstRow;
var lastRow = config.lastRow;
var fold = this.session.getNextFold(i);
var foldStart = fold ? fold.start.row : Infinity;
while (true) {
if(i > foldStart) {
i = fold.end.row + 1;
fold = this.session.getNextFold(i);
foldStart = fold ?fold.start.row :Infinity;
}
if(i > lastRow)
break;
var annotation = this.$annotations[i] || emptyAnno;
html.push("<div class='ace_gutter-cell",
this.$decorations[i] || "",
this.$breakpoints[i] ? " ace_breakpoint " : " ",
annotation.className,
"' title='", annotation.text.join("\n"),
"' style='height:", config.lineHeight, "px;'>", (i+1));
var wrappedRowLength = this.session.getRowLength(i) - 1;
while (wrappedRowLength--) {
html.push("</div><div class='ace_gutter-cell' style='height:", config.lineHeight, "px'>¦</div>");
}
html.push("</div>");
i++;
}
this.element = dom.setInnerHtml(this.element, html.join(""));
this.element.style.height = config.minHeight + "px";
};
}).call(Gutter.prototype);
exports.Gutter = Gutter;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/layer/marker', ['require', 'exports', 'module' , 'ace/range', 'pilot/dom'], function(require, exports, module) {
var Range = require("ace/range").Range;
var dom = require("pilot/dom");
var Marker = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_marker-layer";
parentEl.appendChild(this.element);
};
(function() {
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
};
this.setSession = function(session) {
this.session = session;
};
this.setMarkers = function(markers) {
this.markers = markers;
};
this.update = function(config) {
var config = config || this.config;
if (!config)
return;
this.config = config;
var html = [];
for ( var key in this.markers) {
var marker = this.markers[key];
var range = marker.range.clipRows(config.firstRow, config.lastRow);
if (range.isEmpty()) continue;
range = range.toScreenRange(this.session);
if (marker.renderer) {
var top = this.$getTop(range.start.row, config);
var left = Math.round(
this.$padding + range.start.column * config.characterWidth
);
marker.renderer(html, range, left, top, config);
}
else if (range.isMultiLine()) {
if (marker.type == "text") {
this.drawTextMarker(html, range, marker.clazz, config);
} else {
this.drawMultiLineMarker(
html, range, marker.clazz, config,
marker.type
);
}
}
else {
this.drawSingleLineMarker(
html, range, marker.clazz, config,
null, marker.type
);
}
}
this.element = dom.setInnerHtml(this.element, html.join(""));
};
this.$getTop = function(row, layerConfig) {
return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight;
};
/**
* Draws a marker, which spans a range of text in a single line
*/
this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig) {
// selection start
var row = range.start.row;
var lineRange = new Range(
row, range.start.column,
row, this.session.getScreenLastRowColumn(row)
);
this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 1, "text");
// selection end
row = range.end.row;
lineRange = new Range(row, 0, row, range.end.column);
this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 0, "text");
for (row = range.start.row + 1; row < range.end.row; row++) {
lineRange.start.row = row;
lineRange.end.row = row;
lineRange.end.column = this.session.getScreenLastRowColumn(row);
this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 1, "text");
}
};
/**
* Draws a multi line marker, where lines span the full width
*/
this.drawMultiLineMarker = function(stringBuilder, range, clazz, layerConfig, type) {
// from selection start to the end of the line
var padding = type === "background" ? 0 : this.$padding;
var height = layerConfig.lineHeight;
var width = Math.round(layerConfig.width - (range.start.column * layerConfig.characterWidth));
var top = this.$getTop(range.start.row, layerConfig);
var left = Math.round(
padding + range.start.column * layerConfig.characterWidth
);
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", left, "px;'></div>"
);
// from start of the last line to the selection end
top = this.$getTop(range.end.row, layerConfig);
width = Math.round(range.end.column * layerConfig.characterWidth);
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", padding, "px;'></div>"
);
// all the complete lines
height = (range.end.row - range.start.row - 1) * layerConfig.lineHeight;
if (height < 0)
return;
top = this.$getTop(range.start.row + 1, layerConfig);
width = layerConfig.width;
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", padding, "px;'></div>"
);
};
/**
* Draws a marker which covers one single full line
*/
this.drawSingleLineMarker = function(stringBuilder, range, clazz, layerConfig, extraLength, type) {
var padding = type === "background" ? 0 : this.$padding;
var height = layerConfig.lineHeight;
if (type === "background")
var width = layerConfig.width;
else
width = Math.round((range.end.column + (extraLength || 0) - range.start.column) * layerConfig.characterWidth);
var top = this.$getTop(range.start.row, layerConfig);
var left = Math.round(
padding + range.start.column * layerConfig.characterWidth
);
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", left,"px;'></div>"
);
};
}).call(Marker.prototype);
exports.Marker = Marker;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian DOT viereck AT gmail DOT com>
* Mihai Sucan <mihai.sucan@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/layer/text', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/dom', 'pilot/lang', 'pilot/useragent', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var dom = require("pilot/dom");
var lang = require("pilot/lang");
var useragent = require("pilot/useragent");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Text = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_text-layer";
this.element.style.width = "auto";
parentEl.appendChild(this.element);
this.$characterSize = this.$measureSizes() || {width: 0, height: 0};
this.$pollSizeChanges();
};
(function() {
oop.implement(this, EventEmitter);
this.EOF_CHAR = "¶";
this.EOL_CHAR = "¬";
this.TAB_CHAR = "→";
this.SPACE_CHAR = "·";
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
this.element.style.padding = "0 " + padding + "px";
};
this.getLineHeight = function() {
return this.$characterSize.height || 1;
};
this.getCharacterWidth = function() {
return this.$characterSize.width || 1;
};
this.checkForSizeChanges = function() {
var size = this.$measureSizes();
if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
this.$characterSize = size;
this._dispatchEvent("changeCharaterSize", {data: size});
}
};
this.$pollSizeChanges = function() {
var self = this;
this.$pollSizeChangesTimer = setInterval(function() {
self.checkForSizeChanges();
}, 500);
};
this.$fontStyles = {
fontFamily : 1,
fontSize : 1,
fontWeight : 1,
fontStyle : 1,
lineHeight : 1
};
this.$measureSizes = function() {
var n = 1000;
if (!this.$measureNode) {
var measureNode = this.$measureNode = dom.createElement("div");
var style = measureNode.style;
style.width = style.height = "auto";
style.left = style.top = (-n * 40) + "px";
style.visibility = "hidden";
style.position = "absolute";
style.overflow = "visible";
style.whiteSpace = "nowrap";
// in FF 3.6 monospace fonts can have a fixed sub pixel width.
// that's why we have to measure many characters
// Note: characterWidth can be a float!
measureNode.innerHTML = lang.stringRepeat("Xy", n);
if (document.body) {
document.body.appendChild(measureNode);
} else {
var container = this.element.parentNode;
while (!dom.hasCssClass(container, "ace_editor"))
container = container.parentNode;
container.appendChild(measureNode);
}
}
var style = this.$measureNode.style;
var computedStyle = dom.computedStyle(this.element);
for (var prop in this.$fontStyles)
style[prop] = computedStyle[prop];
var size = {
height: this.$measureNode.offsetHeight,
width: this.$measureNode.offsetWidth / (n * 2)
};
// Size and width can be null if the editor is not visible or
// detached from the document
if (size.width == 0 && size.height == 0)
return null;
return size;
};
this.setSession = function(session) {
this.session = session;
};
this.showInvisibles = false;
this.setShowInvisibles = function(showInvisibles) {
if (this.showInvisibles == showInvisibles)
return false;
this.showInvisibles = showInvisibles;
return true;
};
this.$tabStrings = [];
this.$computeTabString = function() {
var tabSize = this.session.getTabSize();
var tabStr = this.$tabStrings = [0];
for (var i = 1; i < tabSize + 1; i++) {
if (this.showInvisibles) {
tabStr.push("<span class='ace_invisible'>"
+ this.TAB_CHAR
+ new Array(i).join(" ")
+ "</span>");
} else {
tabStr.push(new Array(i+1).join(" "));
}
}
};
this.updateLines = function(config, firstRow, lastRow) {
this.$computeTabString();
// Due to wrap line changes there can be new lines if e.g.
// the line to updated wrapped in the meantime.
if (this.config.lastRow != config.lastRow ||
this.config.firstRow != config.firstRow) {
this.scrollLines(config);
}
this.config = config;
var first = Math.max(firstRow, config.firstRow);
var last = Math.min(lastRow, config.lastRow);
var lineElements = this.element.childNodes;
var lineElementsIdx = 0;
for (var row = config.firstRow; row < first; row++) {
var foldLine = this.session.getFoldLine(row);
if (foldLine) {
if (foldLine.containsRow(first)) {
break;
} else {
row = foldLine.end.row;
}
}
lineElementsIdx ++;
}
for (var i=first; i<=last; i++) {
var lineElement = lineElements[lineElementsIdx++];
if (!lineElement)
continue;
var html = [];
var tokens = this.session.getTokens(i, i);
this.$renderLine(html, i, tokens[0].tokens, true);
lineElement = dom.setInnerHtml(lineElement, html.join(""));
i = this.session.getRowFoldEnd(i);
}
};
this.scrollLines = function(config) {
this.$computeTabString();
var oldConfig = this.config;
this.config = config;
if (!oldConfig || oldConfig.lastRow < config.firstRow)
return this.update(config);
if (config.lastRow < oldConfig.firstRow)
return this.update(config);
var el = this.element;
if (oldConfig.firstRow < config.firstRow)
for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--)
el.removeChild(el.firstChild);
if (oldConfig.lastRow > config.lastRow)
for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--)
el.removeChild(el.lastChild);
if (config.firstRow < oldConfig.firstRow) {
var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1);
if (el.firstChild)
el.insertBefore(fragment, el.firstChild);
else
el.appendChild(fragment);
}
if (config.lastRow > oldConfig.lastRow) {
var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow);
el.appendChild(fragment);
}
};
this.$renderLinesFragment = function(config, firstRow, lastRow) {
var fragment = document.createDocumentFragment(),
row = firstRow,
fold = this.session.getNextFold(row),
foldStart = fold ?fold.start.row :Infinity;
while (true) {
if(row > foldStart) {
row = fold.end.row+1;
fold = this.session.getNextFold(row);
foldStart = fold ?fold.start.row :Infinity;
}
if(row > lastRow)
break;
var container = dom.createElement("div");
var html = [];
// Get the tokens per line as there might be some lines in between
// beeing folded.
// OPTIMIZE: If there is a long block of unfolded lines, just make
// this call once for that big block of unfolded lines.
var tokens = this.session.getTokens(row, row);
if (tokens.length == 1)
this.$renderLine(html, row, tokens[0].tokens, false);
// don't use setInnerHtml since we are working with an empty DIV
container.innerHTML = html.join("");
var lines = container.childNodes
while(lines.length)
fragment.appendChild(lines[0]);
row++;
}
return fragment;
};
this.update = function(config) {
this.$computeTabString();
this.config = config;
var html = [];
var firstRow = config.firstRow, lastRow = config.lastRow;
var row = firstRow,
fold = this.session.getNextFold(row),
foldStart = fold ?fold.start.row :Infinity;
while (true) {
if(row > foldStart) {
row = fold.end.row+1;
fold = this.session.getNextFold(row);
foldStart = fold ?fold.start.row :Infinity;
}
if(row > lastRow)
break;
// Get the tokens per line as there might be some lines in between
// beeing folded.
// OPTIMIZE: If there is a long block of unfolded lines, just make
// this call once for that big block of unfolded lines.
var tokens = this.session.getTokens(row, row);
if (tokens.length == 1)
this.$renderLine(html, row, tokens[0].tokens, false);
row++;
}
this.element = dom.setInnerHtml(this.element, html.join(""));
};
this.$textToken = {
"text": true,
"rparen": true,
"lparen": true
};
this.$renderToken = function(stringBuilder, screenColumn, token, value) {
var self = this;
var replaceReg = /\t|&|<|( +)|([\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000])|[\u1100-\u115F]|[\u11A3-\u11A7]|[\u11FA-\u11FF]|[\u2329-\u232A]|[\u2E80-\u2E99]|[\u2E9B-\u2EF3]|[\u2F00-\u2FD5]|[\u2FF0-\u2FFB]|[\u3000-\u303E]|[\u3041-\u3096]|[\u3099-\u30FF]|[\u3105-\u312D]|[\u3131-\u318E]|[\u3190-\u31BA]|[\u31C0-\u31E3]|[\u31F0-\u321E]|[\u3220-\u3247]|[\u3250-\u32FE]|[\u3300-\u4DBF]|[\u4E00-\uA48C]|[\uA490-\uA4C6]|[\uA960-\uA97C]|[\uAC00-\uD7A3]|[\uD7B0-\uD7C6]|[\uD7CB-\uD7FB]|[\uF900-\uFAFF]|[\uFE10-\uFE19]|[\uFE30-\uFE52]|[\uFE54-\uFE66]|[\uFE68-\uFE6B]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g;
var replaceFunc = function(c, a, b, tabIdx, idx4) {
if (c.charCodeAt(0) == 32) {
return new Array(c.length+1).join(" ");
} else if (c == "\t") {
var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx);
screenColumn += tabSize - 1;
return self.$tabStrings[tabSize];
} else if (c == "&") {
if (useragent.isOldGecko)
return "&";
else
return "&";
} else if (c == "<") {
return "<";
} else if (c.match(/[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]/)) {
if (self.showInvisibles) {
var space = new Array(c.length+1).join(self.SPACE_CHAR);
return "<span class='ace_invisible'>" + space + "</span>";
} else {
return " ";
}
} else {
screenColumn += 1;
return "<span class='ace_cjk' style='width:" +
(self.config.characterWidth * 2) +
"px'>" + c + "</span>";
}
};
var output = value.replace(replaceReg, replaceFunc);
if (!this.$textToken[token.type]) {
var classes = "ace_" + token.type.replace(/\./g, " ace_");
stringBuilder.push("<span class='", classes, "'>", output, "</span>");
}
else {
stringBuilder.push(output);
}
return screenColumn + value.length;
};
this.$renderLineCore = function(stringBuilder, lastRow, tokens, splits, onlyContents) {
var chars = 0;
var split = 0;
var splitChars;
var characterWidth = this.config.characterWidth;
var screenColumn = 0;
var self = this;
if (!splits || splits.length == 0)
splitChars = Number.MAX_VALUE;
else
splitChars = splits[0];
if (!onlyContents) {
stringBuilder.push("<div class='ace_line' style='height:",
this.config.lineHeight, "px",
"'>"
);
}
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
var value = token.value;
if (chars + value.length < splitChars) {
screenColumn = self.$renderToken(
stringBuilder, screenColumn, token, value
);
chars += value.length;
}
else {
while (chars + value.length >= splitChars) {
screenColumn = self.$renderToken(
stringBuilder, screenColumn,
token, value.substring(0, splitChars - chars)
);
value = value.substring(splitChars - chars);
chars = splitChars;
if (!onlyContents) {
stringBuilder.push("</div>",
"<div class='ace_line' style='height:",
this.config.lineHeight, "px",
"'>"
);
}
split ++;
screenColumn = 0;
splitChars = splits[split] || Number.MAX_VALUE;
}
if (value.length != 0) {
chars += value.length;
screenColumn = self.$renderToken(
stringBuilder, screenColumn, token, value
);
}
}
}
if (this.showInvisibles) {
if (lastRow !== this.session.getLength() - 1)
stringBuilder.push("<span class='ace_invisible'>" + this.EOL_CHAR + "</span>");
else
stringBuilder.push("<span class='ace_invisible'>" + this.EOF_CHAR + "</span>");
}
stringBuilder.push("</div>");
};
this.$renderLine = function(stringBuilder, row, tokens, onlyContents) {
// Check if the line to render is folded or not. If not, things are
// simple, otherwise, we need to fake some things...
if (!this.session.isRowFolded(row)) {
var splits = this.session.getRowSplitData(row);
this.$renderLineCore(stringBuilder, row, tokens, splits, onlyContents);
} else {
this.$renderFoldLine(stringBuilder, row, tokens, onlyContents);
}
};
this.$renderFoldLine = function(stringBuilder, row, tokens, onlyContents) {
var session = this.session,
foldLine = session.getFoldLine(row),
renderTokens = [];
function addTokens(tokens, from, to) {
var idx = 0, col = 0;
while ((col + tokens[idx].value.length) < from) {
col += tokens[idx].value.length;
idx++;
if (idx == tokens.length) {
return;
}
}
if (col != from) {
var value = tokens[idx].value.substring(from - col);
// Check if the token value is longer then the from...to spacing.
if (value.length > (to - from)) {
value = value.substring(0, to - from);
}
renderTokens.push({
type: tokens[idx].type,
value: value
});
col = from + value.length;
idx += 1;
}
while (col < to) {
var value = tokens[idx].value;
if (value.length + col > to) {
value = value.substring(0, to - col);
}
renderTokens.push({
type: tokens[idx].type,
value: value
});
col += value.length;
idx += 1;
}
}
foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
if (placeholder) {
renderTokens.push({
type: "fold",
value: placeholder
});
} else {
if (isNewRow) {
tokens = this.session.getTokens(row, row)[0].tokens;
}
if (tokens.length != 0) {
addTokens(tokens, lastColumn, column);
}
}
}.bind(this), foldLine.end.row, this.session.getLine(foldLine.end.row).length);
// TODO: Build a fake splits array!
var splits = this.session.$useWrapMode?this.session.$wrapData[row]:null;
this.$renderLineCore(stringBuilder, row, renderTokens, splits, onlyContents);
};
this.destroy = function() {
clearInterval(this.$pollSizeChangesTimer);
if (this.$measureNode)
this.$measureNode.parentNode.removeChild(this.$measureNode);
delete this.$measureNode;
};
}).call(Text.prototype);
exports.Text = Text;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/layer/cursor', ['require', 'exports', 'module' , 'pilot/dom'], function(require, exports, module) {
var dom = require("pilot/dom");
var Cursor = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_cursor-layer";
parentEl.appendChild(this.element);
this.cursor = dom.createElement("div");
this.cursor.className = "ace_cursor ace_hidden";
this.element.appendChild(this.cursor);
this.isVisible = false;
};
(function() {
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
};
this.setSession = function(session) {
this.session = session;
};
this.hideCursor = function() {
this.isVisible = false;
dom.addCssClass(this.cursor, "ace_hidden");
clearInterval(this.blinkId);
};
this.showCursor = function() {
this.isVisible = true;
dom.removeCssClass(this.cursor, "ace_hidden");
this.cursor.style.visibility = "visible";
this.restartTimer();
};
this.restartTimer = function() {
clearInterval(this.blinkId);
if (!this.isVisible) {
return;
}
var cursor = this.cursor;
this.blinkId = setInterval(function() {
cursor.style.visibility = "hidden";
setTimeout(function() {
cursor.style.visibility = "visible";
}, 400);
}, 1000);
};
this.getPixelPosition = function(onScreen) {
if (!this.config || !this.session) {
return {
left : 0,
top : 0
};
}
var position = this.session.selection.getCursor();
var pos = this.session.documentToScreenPosition(position);
var cursorLeft = Math.round(this.$padding +
pos.column * this.config.characterWidth);
var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) *
this.config.lineHeight;
return {
left : cursorLeft,
top : cursorTop
};
};
this.update = function(config) {
this.config = config;
this.pixelPos = this.getPixelPosition(true);
this.cursor.style.left = this.pixelPos.left + "px";
this.cursor.style.top = this.pixelPos.top + "px";
this.cursor.style.width = config.characterWidth + "px";
this.cursor.style.height = config.lineHeight + "px";
var overwrite = this.session.getOverwrite()
if (overwrite != this.overwrite) {
this.overwrite = overwrite;
if (overwrite)
dom.addCssClass(this.cursor, "ace_overwrite");
else
dom.removeCssClass(this.cursor, "ace_overwrite");
}
this.restartTimer();
};
this.destroy = function() {
clearInterval(this.blinkId);
}
}).call(Cursor.prototype);
exports.Cursor = Cursor;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/scrollbar', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/dom', 'pilot/event', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var dom = require("pilot/dom");
var event = require("pilot/event");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var ScrollBar = function(parent) {
this.element = dom.createElement("div");
this.element.className = "ace_sb";
this.inner = dom.createElement("div");
this.element.appendChild(this.inner);
parent.appendChild(this.element);
// in OSX lion the scrollbars appear to have no width. In this case resize
// the to show the scrollbar but still pretend that the scrollbar has a width
// of 0px
this.width = dom.scrollbarWidth();
this.element.style.width = (this.width || 15) + "px";
event.addListener(this.element, "scroll", this.onScroll.bind(this));
};
(function() {
oop.implement(this, EventEmitter);
this.onScroll = function() {
this._dispatchEvent("scroll", {data: this.element.scrollTop});
};
this.getWidth = function() {
return this.width;
};
this.setHeight = function(height) {
this.element.style.height = height + "px";
};
this.setInnerHeight = function(height) {
this.inner.style.height = height + "px";
};
this.setScrollTop = function(scrollTop) {
this.element.scrollTop = scrollTop;
};
}).call(ScrollBar.prototype);
exports.ScrollBar = ScrollBar;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/renderloop', ['require', 'exports', 'module' , 'pilot/event'], function(require, exports, module) {
var event = require("pilot/event");
var RenderLoop = function(onRender) {
this.onRender = onRender;
this.pending = false;
this.changes = 0;
};
(function() {
this.schedule = function(change) {
//this.onRender(change);
//return;
this.changes = this.changes | change;
if (!this.pending) {
this.pending = true;
var _self = this;
this.setTimeoutZero(function() {
_self.pending = false;
var changes = _self.changes;
_self.changes = 0;
_self.onRender(changes);
})
}
};
this.setTimeoutZero = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
if (this.setTimeoutZero) {
this.setTimeoutZero = this.setTimeoutZero.bind(window)
} else if (window.postMessage) {
this.messageName = "zero-timeout-message";
this.setTimeoutZero = function(callback) {
if (!this.attached) {
var _self = this;
event.addListener(window, "message", function(e) {
if (_self.callback && e.data == _self.messageName) {
event.stopPropagation(e);
_self.callback();
}
});
this.attached = true;
}
this.callback = callback;
window.postMessage(this.messageName, "*");
}
} else {
this.setTimeoutZero = function(callback) {
setTimeout(callback, 0);
}
}
}).call(RenderLoop.prototype);
exports.RenderLoop = RenderLoop;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/textmate', ['require', 'exports', 'module' , 'pilot/dom'], function(require, exports, module) {
var dom = require("pilot/dom");
var cssText = ".ace-tm .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-tm .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-tm .ace_gutter {\
width: 50px;\
background: #e8e8e8;\
color: #333;\
overflow : hidden;\
}\
\
.ace-tm .ace_gutter-layer {\
width: 100%;\
text-align: right;\
}\
\
.ace-tm .ace_gutter-layer .ace_gutter-cell {\
padding-right: 6px;\
}\
\
.ace-tm .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-tm .ace_text-layer {\
cursor: text;\
}\
\
.ace-tm .ace_cursor {\
border-left: 2px solid black;\
}\
\
.ace-tm .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid black;\
}\
\
.ace-tm .ace_line .ace_invisible {\
color: rgb(191, 191, 191);\
}\
\
.ace-tm .ace_line .ace_keyword {\
color: blue;\
}\
\
.ace-tm .ace_line .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
\
.ace-tm .ace_line .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
\
.ace-tm .ace_line .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
\
.ace-tm .ace_line .ace_invalid {\
background-color: rgb(153, 0, 0);\
color: white;\
}\
\
.ace-tm .ace_line .ace_fold {\
background-color: #E4E4E4;\
border-radius: 3px;\
}\
\
.ace-tm .ace_line .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
\
.ace-tm .ace_line .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
\
.ace-tm .ace_line .ace_support.ace_type,\
.ace-tm .ace_line .ace_support.ace_class {\
color: rgb(109, 121, 222);\
}\
\
.ace-tm .ace_line .ace_keyword.ace_operator {\
color: rgb(104, 118, 135);\
}\
\
.ace-tm .ace_line .ace_string {\
color: rgb(3, 106, 7);\
}\
\
.ace-tm .ace_line .ace_comment {\
color: rgb(76, 136, 107);\
}\
\
.ace-tm .ace_line .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
\
.ace-tm .ace_line .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
\
.ace-tm .ace_line .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
\
.ace-tm .ace_line .ace_variable {\
color: rgb(49, 132, 149);\
}\
\
.ace-tm .ace_line .ace_xml_pe {\
color: rgb(104, 104, 91);\
}\
\
.ace-tm .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
\
.ace-tm .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
\
.ace-tm .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
\
.ace-tm .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
\
.ace-tm .ace_marker-layer .ace_active_line {\
background: rgba(0, 0, 0, 0.07);\
}\
\
.ace-tm .ace_marker-layer .ace_selected_word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
\
.ace-tm .ace_string.ace_regex {\
color: rgb(255, 0, 0)\
}";
// import CSS once
dom.importCssString(cssText);
exports.cssClass = "ace-tm";
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is DomTemplate.
*
* The Initial Developer of the Original Code is Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com) (original author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/environment', ['require', 'exports', 'module' , 'pilot/settings'], function(require, exports, module) {
var settings = require("pilot/settings").settings;
/**
* Create an environment object
*/
function create() {
return {
settings: settings
};
};
exports.create = create;
});
define("text/cockpit/ui/cli_view.css", [], "" +
"#cockpitInput { padding-left: 16px; }" +
"" +
".cptOutput { overflow: auto; position: absolute; z-index: 999; display: none; }" +
"" +
".cptCompletion { padding: 0; position: absolute; z-index: -1000; }" +
".cptCompletion.VALID { background: #FFF; }" +
".cptCompletion.INCOMPLETE { background: #DDD; }" +
".cptCompletion.INVALID { background: #DDD; }" +
".cptCompletion span { color: #FFF; }" +
".cptCompletion span.INCOMPLETE { color: #DDD; border-bottom: 2px dotted #F80; }" +
".cptCompletion span.INVALID { color: #DDD; border-bottom: 2px dotted #F00; }" +
"span.cptPrompt { color: #66F; font-weight: bold; }" +
"" +
"" +
".cptHints {" +
" color: #000;" +
" position: absolute;" +
" border: 1px solid rgba(230, 230, 230, 0.8);" +
" background: rgba(250, 250, 250, 0.8);" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 10px; border-top-right-radius: 10px;" +
" z-index: 1000;" +
" padding: 8px;" +
" display: none;" +
"}" +
"" +
".cptFocusPopup { display: block; }" +
".cptFocusPopup.cptNoPopup { display: none; }" +
"" +
".cptHints ul { margin: 0; padding: 0 15px; }" +
"" +
".cptGt { font-weight: bold; font-size: 120%; }" +
"");
define("text/cockpit/ui/request_view.css", [], "" +
".cptRowIn {" +
" display: box; display: -moz-box; display: -webkit-box;" +
" box-orient: horizontal; -moz-box-orient: horizontal; -webkit-box-orient: horizontal;" +
" box-align: center; -moz-box-align: center; -webkit-box-align: center;" +
" color: #333;" +
" background-color: #EEE;" +
" width: 100%;" +
" font-family: consolas, courier, monospace;" +
"}" +
".cptRowIn > * { padding-left: 2px; padding-right: 2px; }" +
".cptRowIn > img { cursor: pointer; }" +
".cptHover { display: none; }" +
".cptRowIn:hover > .cptHover { display: block; }" +
".cptRowIn:hover > .cptHover.cptHidden { display: none; }" +
".cptOutTyped {" +
" box-flex: 1; -moz-box-flex: 1; -webkit-box-flex: 1;" +
" font-weight: bold; color: #000; font-size: 120%;" +
"}" +
".cptRowOutput { padding-left: 10px; line-height: 1.2em; }" +
".cptRowOutput strong," +
".cptRowOutput b," +
".cptRowOutput th," +
".cptRowOutput h1," +
".cptRowOutput h2," +
".cptRowOutput h3 { color: #000; }" +
".cptRowOutput a { font-weight: bold; color: #666; text-decoration: none; }" +
".cptRowOutput a: hover { text-decoration: underline; cursor: pointer; }" +
".cptRowOutput input[type=password]," +
".cptRowOutput input[type=text]," +
".cptRowOutput textarea {" +
" color: #000; font-size: 120%;" +
" background: transparent; padding: 3px;" +
" border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;" +
"}" +
".cptRowOutput table," +
".cptRowOutput td," +
".cptRowOutput th { border: 0; padding: 0 2px; }" +
".cptRowOutput .right { text-align: right; }" +
"");
define("text/ace/css/editor.css", [], ".ace_editor {" +
" position: absolute;" +
" overflow: hidden;" +
" font-family: Monaco, \"Menlo\", \"Courier New\", monospace;" +
" font-size: 12px;" +
"}" +
"" +
".ace_scroller {" +
" position: absolute;" +
" overflow-x: scroll;" +
" overflow-y: hidden;" +
"}" +
"" +
".ace_content {" +
" position: absolute;" +
" box-sizing: border-box;" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
"}" +
"" +
".ace_composition {" +
" position: absolute;" +
" background: #555;" +
" color: #DDD;" +
" z-index: 4;" +
"}" +
"" +
".ace_gutter {" +
" position: absolute;" +
" overflow-x: hidden;" +
" overflow-y: hidden;" +
" height: 100%;" +
"}" +
"" +
".ace_gutter-cell.ace_error {" +
" background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%F5or%F5%87%88%F5nr%F4ns%EBmq%F5z%7F%DDJT%DEKS%DFOW%F1Yc%F2ah%CE(7%CE)8%D18E%DD%40M%F2KZ%EBU%60%F4%60m%DCir%C8%16(%C8%19*%CE%255%F1%3FR%F1%3FS%E6%AB%B5%CA%5DI%CEn%5E%F7%A2%9A%C9G%3E%E0a%5B%F7%89%85%F5yy%F6%82%80%ED%82%80%FF%BF%BF%E3%C4%C4%FF%FF%FF%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%25%00%2C%00%00%00%00%10%00%10%00%00%06p%C0%92pH%2C%1A%8F%C8%D2H%93%E1d4%23%E4%88%D3%09mB%1DN%B48%F5%90%40%60%92G%5B%94%20%3E%22%D2%87%24%FA%20%24%C5%06A%00%20%B1%07%02B%A38%89X.v%17%82%11%13q%10%0Fi%24%0F%8B%10%7BD%12%0Ei%09%92%09%0EpD%18%15%24%0A%9Ci%05%0C%18F%18%0B%07%04%01%04%06%A0H%18%12%0D%14%0D%12%A1I%B3%B4%B5IA%00%3B\");" +
" background-repeat: no-repeat;" +
" background-position: 4px center;" +
"}" +
"" +
".ace_gutter-cell.ace_warning {" +
" background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%FF%DBr%FF%DE%81%FF%E2%8D%FF%E2%8F%FF%E4%96%FF%E3%97%FF%E5%9D%FF%E6%9E%FF%EE%C1%FF%C8Z%FF%CDk%FF%D0s%FF%D4%81%FF%D5%82%FF%D5%83%FF%DC%97%FF%DE%9D%FF%E7%B8%FF%CCl%7BQ%13%80U%15%82W%16%81U%16%89%5B%18%87%5B%18%8C%5E%1A%94d%1D%C5%83-%C9%87%2F%C6%84.%C6%85.%CD%8B2%C9%871%CB%8A3%CD%8B5%DC%98%3F%DF%9BB%E0%9CC%E1%A5U%CB%871%CF%8B5%D1%8D6%DB%97%40%DF%9AB%DD%99B%E3%B0p%E7%CC%AE%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%2F%00%2C%00%00%00%00%10%00%10%00%00%06a%C0%97pH%2C%1A%8FH%A1%ABTr%25%87%2B%04%82%F4%7C%B9X%91%08%CB%99%1C!%26%13%84*iJ9(%15G%CA%84%14%01%1A%97%0C%03%80%3A%9A%3E%81%84%3E%11%08%B1%8B%20%02%12%0F%18%1A%0F%0A%03'F%1C%04%0B%10%16%18%10%0B%05%1CF%1D-%06%07%9A%9A-%1EG%1B%A0%A1%A0U%A4%A5%A6BA%00%3B\");" +
" background-repeat: no-repeat;" +
" background-position: 4px center;" +
"}" +
"" +
".ace_editor .ace_sb {" +
" position: absolute;" +
" overflow-x: hidden;" +
" overflow-y: scroll;" +
" right: 0;" +
"}" +
"" +
".ace_editor .ace_sb div {" +
" position: absolute;" +
" width: 1px;" +
" left: 0;" +
"}" +
"" +
".ace_editor .ace_print_margin_layer {" +
" z-index: 0;" +
" position: absolute;" +
" overflow: hidden;" +
" margin: 0;" +
" left: 0;" +
" height: 100%;" +
" width: 100%;" +
"}" +
"" +
".ace_editor .ace_print_margin {" +
" position: absolute;" +
" height: 100%;" +
"}" +
"" +
".ace_editor textarea {" +
" position: fixed;" +
" z-index: -1;" +
" width: 10px;" +
" height: 30px;" +
" opacity: 0;" +
" background: transparent;" +
" appearance: none;" +
" -moz-appearance: none;" +
" border: none;" +
" resize: none;" +
" outline: none;" +
" overflow: hidden;" +
"}" +
"" +
".ace_layer {" +
" z-index: 1;" +
" position: absolute;" +
" overflow: hidden;" +
" white-space: nowrap;" +
" height: 100%;" +
" width: 100%;" +
"}" +
"" +
".ace_text-layer {" +
" color: black;" +
"}" +
"" +
".ace_cjk {" +
" display: inline-block;" +
" text-align: center;" +
"}" +
"" +
".ace_cursor-layer {" +
" z-index: 4;" +
" cursor: text;" +
" /* setting pointer-events: none; here will break mouse wheel scrolling in Safari */" +
"}" +
"" +
".ace_cursor {" +
" z-index: 4;" +
" position: absolute;" +
"}" +
"" +
".ace_cursor.ace_hidden {" +
" opacity: 0.2;" +
"}" +
"" +
".ace_line {" +
" white-space: nowrap;" +
"}" +
"" +
".ace_marker-layer {" +
" cursor: text;" +
" pointer-events: none;" +
"}" +
"" +
".ace_marker-layer .ace_step {" +
" position: absolute;" +
" z-index: 3;" +
"}" +
"" +
".ace_marker-layer .ace_selection {" +
" position: absolute;" +
" z-index: 4;" +
"}" +
"" +
".ace_marker-layer .ace_bracket {" +
" position: absolute;" +
" z-index: 5;" +
"}" +
"" +
".ace_marker-layer .ace_active_line {" +
" position: absolute;" +
" z-index: 2;" +
"}" +
"" +
".ace_marker-layer .ace_selected_word {" +
" position: absolute;" +
" z-index: 6;" +
" box-sizing: border-box;" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
"}" +
"" +
".ace_line .ace_fold {" +
" cursor: pointer;" +
"}" +
"" +
".ace_dragging .ace_marker-layer, .ace_dragging .ace_text-layer {" +
" cursor: move;" +
"}" +
"");
define("text/build/demo/styles.css", [], "html {" +
" height: 100%;" +
" width: 100%;" +
" overflow: hidden;" +
"}" +
"" +
"body {" +
" overflow: hidden;" +
" margin: 0;" +
" padding: 0;" +
" height: 100%;" +
" width: 100%;" +
" font-family: Arial, Helvetica, sans-serif, Tahoma, Verdana, sans-serif;" +
" font-size: 12px;" +
" background: rgb(14, 98, 165);" +
" color: white;" +
"}" +
"" +
"#logo {" +
" padding: 15px;" +
" margin-left: 65px;" +
"}" +
"" +
"#editor {" +
" position: absolute;" +
" top: 0px;" +
" left: 280px;" +
" bottom: 0px;" +
" right: 0px;" +
" background: white;" +
"}" +
"" +
"#controls {" +
" padding: 5px;" +
"}" +
"" +
"#controls td {" +
" text-align: right;" +
"}" +
"" +
"#controls td + td {" +
" text-align: left;" +
"}" +
"" +
"#cockpitInput {" +
" position: absolute;" +
" left: 280px;" +
" right: 0px;" +
" bottom: 0;" +
"" +
" border: none; outline: none;" +
" font-family: consolas, courier, monospace;" +
" font-size: 120%;" +
"}" +
"" +
"#cockpitOutput {" +
" padding: 10px;" +
" margin: 0 15px;" +
" border: 1px solid #AAA;" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 4px; border-top-right-radius: 4px;" +
" background: #DDD; color: #000;" +
"}");
define("text/build_support/style.css", [], "body {" +
" margin:0;" +
" padding:0;" +
" background-color:#e6f5fc;" +
" " +
"}" +
"" +
"H2, H3, H4 {" +
" font-family:Trebuchet MS;" +
" font-weight:bold;" +
" margin:0;" +
" padding:0;" +
"}" +
"" +
"H2 {" +
" font-size:28px;" +
" color:#263842;" +
" padding-bottom:6px;" +
"}" +
"" +
"H3 {" +
" font-family:Trebuchet MS;" +
" font-weight:bold;" +
" font-size:22px;" +
" color:#253741;" +
" margin-top:43px;" +
" margin-bottom:8px;" +
"}" +
"" +
"H4 {" +
" font-family:Trebuchet MS;" +
" font-weight:bold;" +
" font-size:21px;" +
" color:#222222;" +
" margin-bottom:4px;" +
"}" +
"" +
"P {" +
" padding:13px 0;" +
" margin:0;" +
" line-height:22px;" +
"}" +
"" +
"UL{" +
" line-height : 22px;" +
"}" +
"" +
"PRE{" +
" background : #333;" +
" color : white;" +
" padding : 10px;" +
"}" +
"" +
"#header {" +
" height : 227px;" +
" position:relative;" +
" overflow:hidden;" +
" background: url(images/background.png) repeat-x 0 0;" +
" border-bottom:1px solid #c9e8fa; " +
"}" +
"" +
"#header .content .signature {" +
" font-family:Trebuchet MS;" +
" font-size:11px;" +
" color:#ebe4d6;" +
" position:absolute;" +
" bottom:5px;" +
" right:42px;" +
" letter-spacing : 1px;" +
"}" +
"" +
".content {" +
" width:970px;" +
" position:relative;" +
" overflow:hidden;" +
" margin:0 auto;" +
"}" +
"" +
"#header .content {" +
" height:184px;" +
" margin-top:22px;" +
"}" +
"" +
"#header .content .logo {" +
" width : 282px;" +
" height : 184px;" +
" background:url(images/logo.png) no-repeat 0 0;" +
" position:absolute;" +
" top:0;" +
" left:0;" +
"}" +
"" +
"#header .content .title {" +
" width : 605px;" +
" height : 58px;" +
" background:url(images/ace.png) no-repeat 0 0;" +
" position:absolute;" +
" top:98px;" +
" left:329px;" +
"}" +
"" +
"#wrapper {" +
" background:url(images/body_background.png) repeat-x 0 0;" +
" min-height:250px;" +
"}" +
"" +
"#wrapper .content {" +
" font-family:Arial;" +
" font-size:14px;" +
" color:#222222;" +
" width:1000px;" +
"}" +
"" +
"#wrapper .content .column1 {" +
" position:relative;" +
" overflow:hidden;" +
" float:left;" +
" width:315px;" +
" margin-right:31px;" +
"}" +
"" +
"#wrapper .content .column2 {" +
" position:relative;" +
" overflow:hidden;" +
" float:left;" +
" width:600px;" +
" padding-top:47px;" +
"}" +
"" +
".fork_on_github {" +
" width:310px;" +
" height:80px;" +
" background:url(images/fork_on_github.png) no-repeat 0 0;" +
" position:relative;" +
" overflow:hidden;" +
" margin-top:49px;" +
" cursor:pointer;" +
"}" +
"" +
".fork_on_github:hover {" +
" background-position:0 -80px;" +
"}" +
"" +
".divider {" +
" height:3px;" +
" background-color:#bedaea;" +
" margin-bottom:3px;" +
"}" +
"" +
".menu {" +
" padding:23px 0 0 24px;" +
"}" +
"" +
"UL.content-list {" +
" padding:15px;" +
" margin:0;" +
"}" +
"" +
"UL.menu-list {" +
" padding:0;" +
" margin:0 0 20px 0;" +
" list-style-type:none;" +
" line-height : 16px;" +
"}" +
"" +
"UL.menu-list LI {" +
" color:#2557b4;" +
" font-family:Trebuchet MS;" +
" font-size:14px;" +
" padding:7px 0;" +
" border-bottom:1px dotted #d6e2e7;" +
"}" +
"" +
"UL.menu-list LI:last-child {" +
" border-bottom:0;" +
"}" +
"" +
"A {" +
" color:#2557b4;" +
" text-decoration:none;" +
"}" +
"" +
"A:hover {" +
" text-decoration:underline;" +
"}" +
"" +
"P#first{" +
" background : rgba(255,255,255,0.5);" +
" padding : 20px;" +
" font-size : 16px;" +
" line-height : 24px;" +
" margin : 0 0 20px 0;" +
"}" +
"" +
"#footer {" +
" height:40px;" +
" position:relative;" +
" overflow:hidden;" +
" background:url(images/bottombar.png) repeat-x 0 0;" +
" position:relative;" +
" margin-top:40px;" +
"}" +
"" +
"UL.menu-footer {" +
" padding:0;" +
" margin:8px 11px 0 0;" +
" list-style-type:none;" +
" float:right;" +
"}" +
"" +
"UL.menu-footer LI {" +
" color:white;" +
" font-family:Arial;" +
" font-size:12px;" +
" display:inline-block;" +
" margin:0 1px;" +
"}" +
"" +
"UL.menu-footer LI A {" +
" color:#8dd0ff;" +
" text-decoration:none;" +
"}" +
"" +
"UL.menu-footer LI A:hover {" +
" text-decoration:underline;" +
"}" +
"" +
"" +
"" +
"" +
"");
define("text/demo/styles.css", [], "html {" +
" height: 100%;" +
" width: 100%;" +
" overflow: hidden;" +
"}" +
"" +
"body {" +
" overflow: hidden;" +
" margin: 0;" +
" padding: 0;" +
" height: 100%;" +
" width: 100%;" +
" font-family: Arial, Helvetica, sans-serif, Tahoma, Verdana, sans-serif;" +
" font-size: 12px;" +
" background: rgb(14, 98, 165);" +
" color: white;" +
"}" +
"" +
"#logo {" +
" padding: 15px;" +
" margin-left: 65px;" +
"}" +
"" +
"#editor {" +
" position: absolute;" +
" top: 0px;" +
" left: 280px;" +
" bottom: 0px;" +
" right: 0px;" +
" background: white;" +
"}" +
"" +
"#controls {" +
" padding: 5px;" +
"}" +
"" +
"#controls td {" +
" text-align: right;" +
"}" +
"" +
"#controls td + td {" +
" text-align: left;" +
"}" +
"" +
"#cockpitInput {" +
" position: absolute;" +
" left: 280px;" +
" right: 0px;" +
" bottom: 0;" +
"" +
" border: none; outline: none;" +
" font-family: consolas, courier, monospace;" +
" font-size: 120%;" +
"}" +
"" +
"#cockpitOutput {" +
" padding: 10px;" +
" margin: 0 15px;" +
" border: 1px solid #AAA;" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 4px; border-top-right-radius: 4px;" +
" background: #DDD; color: #000;" +
"}");
define("text/deps/csslint/demos/demo.css", [], "@charset \"UTF-8\";" +
"" +
"@import url(\"booya.css\") print,screen;" +
"@import \"whatup.css\" screen;" +
"@import \"wicked.css\";" +
"" +
"@namespace \"http://www.w3.org/1999/xhtml\";" +
"@namespace svg \"http://www.w3.org/2000/svg\";" +
"" +
"li.inline #foo {" +
" background: url(\"something.png\");" +
" display: inline;" +
" padding-left: 3px;" +
" padding-right: 7px;" +
" border-right: 1px dotted #066;" +
"}" +
"" +
"li.last.first {" +
" display: inline;" +
" padding-left: 3px !important;" +
" padding-right: 3px;" +
" border-right: 0px;" +
"}" +
"" +
"@media print {" +
" li.inline {" +
" color: black;" +
" }" +
"" +
"" +
"@charset \"UTF-8\"; " +
"" +
"@page {" +
" margin: 10%;" +
" counter-increment: page;" +
"" +
" @top-center {" +
" font-family: sans-serif;" +
" font-weight: bold;" +
" font-size: 2em;" +
" content: counter(page);" +
" }" +
"}");
define("text/deps/requirejs/dist/ie.css", [], "" +
"body .sect {" +
" display: none;" +
"}" +
"" +
"" +
"#content ul.index {" +
" list-style: none;" +
"}" +
"");
define("text/deps/requirejs/dist/main.css", [], "@font-face {" +
" font-family: Inconsolata;" +
" src: url(\"fonts/Inconsolata.ttf\");" +
"}" +
"" +
"* {" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
" box-sizing: border-box;" +
" margin: 0;" +
" padding: 0;" +
"}" +
"" +
"body {" +
" font-size: 12px;" +
" line-height: 21px;" +
" background-color: #fff;" +
" font-family: \"Helvetica Neue\", Helvetica, Arial, Verdana, sans-serif;" +
" color: #0a0a0a;" +
"}" +
"" +
"#wrapper {" +
" margin: 0;" +
"}" +
"" +
"#grid {" +
" position: fixed;" +
" top: 0;" +
" left: 0;" +
" width: 796px;" +
" background-image: url(\"i/grid.png\");" +
" z-index: 100;" +
"}" +
"" +
"pre {" +
" line-height: 18px;" +
" font-size: 13px;" +
" margin: 7px 0 21px;" +
" padding: 5px 10px;" +
" overflow: auto;" +
" background-color: #fafafa;" +
" border: 1px solid #e6e6e6;" +
" -moz-border-radius: 5px;" +
" -webkit-border-radius: 5px;" +
" border-radius: 5px;" +
" -moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);" +
" -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);" +
" box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);" +
"}" +
"" +
"/*" +
" typography stuff" +
"*/" +
".mono {" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
"}" +
"" +
".sans {" +
" font-family: \"Helvetica Neue\", Helvetica, Arial, Verdana, sans-serif;" +
"}" +
"" +
".serif {" +
" font-family: \"Georgia\", Times New Roman, Times, serif;" +
"}" +
"" +
"a {" +
" color: #2e87dd;" +
" text-decoration: none;" +
"}" +
"" +
"a:hover {" +
" text-decoration: underline;" +
"}" +
"" +
"/*" +
" navigation" +
"*/" +
"" +
"#navBg {" +
" background-color: #f2f2f2;" +
" background-image: url(\"i/shadow.png\");" +
" background-position: right top;" +
" background-repeat: repeat-y;" +
" width: 220px;" +
" position: fixed;" +
" top: 0;" +
" left: 0;" +
" z-index: 0;" +
"}" +
"" +
"#nav {" +
" background-image: url(\"i/logo.png\");" +
" background-repeat: no-repeat;" +
" background-position: center 10px;" +
" width: 220px;" +
" float: left;" +
" margin: 0;" +
" padding: 150px 20px 0;" +
" font-size: 13px;" +
" text-shadow: 1px 1px #fff;" +
" position: relative;" +
" z-index: 1;" +
"}" +
"" +
"#nav .homeImageLink {" +
" position: absolute;" +
" display: block;" +
" top: 10px;" +
" left: 0;" +
" width: 220px;" +
" height: 138px;" +
"}" +
"#nav ul {" +
" list-style-type:none;" +
" padding: 0;" +
" margin: 21px 0 0 0;" +
"}" +
"" +
"#nav ul li {" +
" width: 100%;" +
"}" +
"" +
"#nav ul li.version {" +
" text-align: center;" +
" color: #4d4d4d;" +
"}" +
"" +
"#nav h1 {" +
" color: #4d4d4d;" +
" text-align: center;" +
" font-size: 15px;" +
" font-weight: normal;" +
" text-transform: uppercase;" +
" letter-spacing: 3px;" +
"}" +
"" +
"span.spacer {" +
" color: #2e87dd;" +
" margin: 0 3px 0 5px;" +
" background-image: url(\"i/dot.png\");" +
" background-repeat: repeat-x;" +
" background-position: left 13px;" +
"}" +
"" +
"/*" +
" icons" +
"*/" +
"" +
"span.icon {" +
" width: 16px;" +
" display: block;" +
" background-image: url(\"i/sprite.png\");" +
" background-repeat: no-repeat;" +
"}" +
"" +
"span.icon.home {" +
" background-position: center 5px;" +
"}" +
"" +
"span.icon.start {" +
" background-position: center -27px;" +
"}" +
"" +
"span.icon.download {" +
" background-position: center -59px;" +
"}" +
"" +
"span.icon.api {" +
" background-position: center -89px;" +
"}" +
"" +
"span.icon.optimize {" +
" background-position: center -119px;" +
"}" +
"" +
"span.icon.script {" +
" background-position: center -150px;" +
"}" +
"" +
"span.icon.question {" +
" background-position: center -182px;" +
"}" +
"" +
"span.icon.requirement {" +
" background-position: center -214px;" +
"}" +
"" +
"span.icon.history {" +
" background-position: center -247px;" +
"}" +
"" +
"span.icon.help {" +
" background-position: center -279px;" +
"}" +
"" +
"span.icon.blog {" +
" background-position: center -311px;" +
"}" +
"" +
"span.icon.twitter {" +
" background-position: center -343px;" +
"}" +
"" +
"span.icon.git {" +
" background-position: center -375px;" +
"}" +
"" +
"span.icon.fork {" +
" background-position: center -407px;" +
"}" +
"" +
"/*" +
" content" +
"*/" +
"" +
"#content {" +
" margin: 0 0 0 220px;" +
" padding: 0 20px;" +
" background-color: #fff;" +
" font-family: \"Georgia\", Times New Roman, Times, serif;" +
" position: relative;" +
"}" +
"" +
"#content p {" +
" padding: 7px 0;" +
" color: #333;" +
" font-size: 14px;" +
"}" +
"" +
"#content h1," +
"#content h2," +
"#content h3," +
"#content h4," +
"#content h5 {" +
" font-weight: normal;" +
" padding: 21px 0 7px;" +
"}" +
"" +
"#content h1 {" +
" font-size: 21px;" +
"}" +
"" +
"#content h2 {" +
" padding: 0 0 18px 0;" +
" margin: 0 0 7px 0;" +
" font-weight: normal;" +
" font-size: 21px;" +
" line-height: 24px;" +
" text-align: center;" +
" color: #222;" +
" background-image: url(\"i/arrow.png\");" +
" background-repeat: no-repeat;" +
" background-position: center bottom;" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
" text-transform: uppercase;" +
" letter-spacing: 2px;" +
" text-shadow: 1px 1px 0 #fff;" +
"}" +
"" +
"#content h2 a {" +
" color: #222;" +
"}" +
"" +
"#content h2 a:hover," +
"#content h3 a:hover," +
"#content h4 a:hover {" +
" text-decoration: none;" +
"}" +
"" +
"span.sectionMark {" +
" display: block;" +
" color: #aaa;" +
" text-shadow: 1px 1px 0 #fff;" +
" font-size: 15px;" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
"}" +
"" +
"#content h3 {" +
" font-size: 17px;" +
"}" +
"" +
"#content h4 {" +
" padding-top: 0;" +
" font-size: 15px;" +
"}" +
"" +
"#content h5 {" +
" font-size: 10px;" +
"}" +
"" +
"#content ul {" +
" list-style-type: disc;" +
"}" +
"" +
"#content ul," +
"#content ol {" +
" /* border-left: 1px solid #333; */" +
" color: #333;" +
" font-size: 14px;" +
" list-style-position: outside;" +
" margin: 7px 0 21px 0;" +
" /* padding: 0 0 0 28px; */" +
"}" +
"" +
"#content ul {" +
" font-style: italic;" +
"}" +
"" +
"#content ol {" +
" border: none;" +
" list-style-position: inside;" +
" padding: 0;" +
" font-family: \"Georgia\", Times New Roman, Times, serif;" +
"}" +
"" +
"#content ul ul," +
"#content ol ol {" +
" border: none;" +
" padding: 0;" +
" margin: 0 0 0 28px;" +
"}" +
"" +
"#content .section {" +
" padding: 48px 0;" +
" background-image: url(\"i/line.png\");" +
" background-repeat: no-repeat;" +
" background-position: center bottom;" +
" width: 576px;" +
" margin: 0 auto;" +
"}" +
"" +
"#content .section .subSection {" +
" padding: 0 0 0 48px;" +
" margin: 28px 0 0 0;" +
" display: block;" +
" border-left: 2px solid #ddd;" +
"}" +
"" +
"#content .section:last-child {" +
" background-image: none;" +
"}" +
"" +
"#content .note {" +
" color: #222;" +
" background-color: #ffff99;" +
" padding: 5px 10px;" +
" margin: 7px 0;" +
" display: inline-block;" +
"}" +
"" +
"/*" +
" page directory" +
"*/" +
"" +
"#content #directory.section {" +
" background-color: #fff;" +
" width: 576px;" +
"}" +
"" +
"#content #directory.section ul ul ul {" +
" margin: 0 0 0 48px;" +
"}" +
"" +
"#content #directory.section ul ul li {" +
" background-image: url(\"i/sprite.png\");" +
" background-repeat: no-repeat;" +
" background-position: left -437px;" +
" padding-left: 18px;" +
" font-style: normal;" +
"}" +
"" +
"#content #directory h1 {" +
" padding: 0 0 65px 0;" +
" margin: 0 0 14px 0;" +
" font-weight: normal;" +
" font-size: 21px;" +
" text-align: center;" +
" text-transform: uppercase;" +
" letter-spacing: 2px;" +
" color: #222;" +
" background-image: url(\"i/arrow-x.png\");" +
" background-repeat: no-repeat;" +
" background-position: center bottom;" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
"}" +
"" +
"" +
"#content ul.index {" +
" padding: 0;" +
" background-color: transparent;" +
" border: none;" +
" -moz-box-shadow: none;" +
" font-style: normal;" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
"}" +
"" +
"#content ul.index li {" +
" width: 100%;" +
" font-size: 15px;" +
" color: #333;" +
" padding: 0 0 7px 0;" +
"}" +
"" +
"" +
"/*" +
" intro page specific" +
"*/" +
"" +
"#content #intro {" +
" width: 576px;" +
" margin: 0 auto;" +
" padding: 21px 0;" +
"}" +
"" +
"#content #intro p," +
"#content #intro h1 {" +
" font-size: 19px;" +
" line-height: 28px;" +
" color: green;" +
" letter-spacing: 2px;" +
" padding: 0 0 28px 0;" +
"}" +
"" +
"#content #intro p:last-child," +
"#content #intro h1:last-child {" +
" padding: 0;" +
"}" +
"" +
"#content #intro p a {" +
" color: green;" +
" text-decoration: underline;" +
"}" +
"" +
"/*" +
" download page" +
"*/" +
"" +
"#content h4 a.download {" +
" -webkit-border-radius: 5px;" +
" -moz-border-radius: 5px;" +
" background-color: #F2F2F2;" +
" background-image: url(\"i/sprite.png\"), -moz-linear-gradient(center top , #FAFAFA 0%, #F2F2F2 100%);" +
" background-image: url(\"i/sprite.png\"), -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fafafa), color-stop(100%, #f2f2f2));" +
" background-position: 7px -58px, center center;" +
" background-repeat: no-repeat, no-repeat;" +
" border: 1px solid #CCCCCC;" +
" color: #333333;" +
" font-size: 12px;" +
" margin: 0 0 0 5px;" +
" padding: 0 10px 0 25px;" +
" text-shadow: 1px 1px 0 #FFFFFF;" +
"}" +
"" +
"/*" +
" footer" +
"*/" +
"#footer {" +
" color: #4d4d4d;" +
" padding: 65px 20px 20px;" +
" margin: 20px 0 0 220px;" +
" text-align: center;" +
" display: block;" +
" font-size: 13px;" +
" background-image: url(\"i/arrow-x.png\");" +
" background-repeat: no-repeat;" +
" background-position: center top;" +
" background-color: #fff;" +
"}" +
"" +
"#footer .line {" +
" display: block;" +
"}" +
"" +
"#footer .line a {" +
" color: #4d4d4d;" +
" text-decoration: underline;" +
"}" +
"" +
"/*" +
" Pygments manni style" +
"*/" +
"" +
"code {background-color: #fafafa; color: #333;}" +
"" +
"code .comment {color: green; font-style: italic}" +
"code .comment.preproc {color: #099; font-style: normal}" +
"code .comment.special {font-weight: bold}" +
"" +
"code .keyword {color: #069; font-weight: bold}" +
"code .keyword.pseudo {font-weight: normal}" +
"code .keyword.type {color: #078}" +
"" +
"code .operator {color: #555}" +
"code .operator.word {color: #000; font-weight: bold}" +
"" +
"code .name.builtin {color: #366}" +
"code .name.function {color: #c0f}" +
"code .name.class {color: #0a8; font-weight: bold}" +
"code .name.namespace {color: #0cf; font-weight: bold}" +
"code .name.exception {color: #c00; font-weight: bold}" +
"code .name.variable {color: #033}" +
"code .name.constant {color: #360}" +
"code .name.label {color: #99f}" +
"code .name.entity {color: #999; font-weight: bold}" +
"code .name.attribute {color: #309}" +
"code .name.tag {color: #309; font-weight: bold}" +
"code .name.decorator {color: #99f}" +
"" +
"code .string {color: #c30}" +
"code .string.doc {font-style: italic}" +
"code .string.interpol {color: #a00}" +
"code .string.escape {color: #c30; font-weight: bold}" +
"code .string.regex {color: #3aa}" +
"code .string.symbol {color: #fc3}" +
"code .string.other {color: #c30}" +
"" +
"code .number {color: #f60}" +
"" +
"" +
"/*" +
" webkit scroll bars" +
"*/" +
"" +
"pre::-webkit-scrollbar {" +
" width: 6px;" +
" height: 6px;" +
"}" +
"" +
"pre::-webkit-scrollbar-button:start:decrement," +
"pre::-webkit-scrollbar-button:end:increment {" +
" display: block;" +
" height: 0;" +
" width: 0;" +
"}" +
"" +
"pre::-webkit-scrollbar-button:vertical:increment," +
"pre::-webkit-scrollbar-button:horizontal:increment {" +
" background-color: transparent;" +
" display: block;" +
" height: 0;" +
" width: 0;" +
"}" +
"" +
"pre::-webkit-scrollbar-track-piece {" +
" -webkit-border-radius: 3px;" +
"}" +
"" +
"pre::-webkit-scrollbar-thumb:vertical {" +
" background-color: #aaa;" +
" -webkit-border-radius: 3px;" +
"" +
"}" +
"" +
"pre::-webkit-scrollbar-thumb:horizontal {" +
" background-color: #aaa;" +
" -webkit-border-radius: 3px;" +
"}" +
"" +
"/*" +
" hbox" +
"*/" +
"" +
".hbox {" +
" display: -webkit-box;" +
" -webkit-box-orient: horizontal;" +
" -webkit-box-align: stretch;" +
"" +
" display: -moz-box;" +
" -moz-box-orient: horizontal;" +
" -moz-box-align: stretch;" +
"" +
" display: box;" +
" box-orient: horizontal;" +
" box-align: stretch;" +
"" +
" width: 100%;" +
"}" +
"" +
".hbox > * {" +
" -webkit-box-flex: 0;" +
" -moz-box-flex: 0;" +
" box-flex: 0;" +
" display: block;" +
"}" +
"" +
".vbox {" +
" display: -webkit-box;" +
" -webkit-box-orient: vertical;" +
" -webkit-box-align: stretch;" +
"" +
" display: -moz-box;" +
" -moz-box-orient: vertical;" +
" -moz-box-align: stretch;" +
"" +
" display: box;" +
" box-orient: vertical;" +
" box-align: stretch;" +
"}" +
"" +
".vbox > * {" +
" -webkit-box-flex: 0;" +
" -moz-box-flex: 0;" +
" box-flex: 0;" +
" display: block;" +
"}" +
"" +
".spacer {" +
" -webkit-box-flex: 1;" +
" -moz-box-flex: 1;" +
" box-flex: 1;" +
"}" +
"" +
".reverse {" +
" -webkit-box-direction: reverse;" +
" -moz-box-direction: reverse;" +
" box-direction: reverse;" +
"}" +
"" +
".boxFlex0 {" +
" -webkit-box-flex: 0;" +
" -moz-box-flex: 0;" +
" box-flex: 0;" +
"}" +
"" +
".boxFlex1, .boxFlex {" +
" -webkit-box-flex: 1;" +
" -moz-box-flex: 1;" +
" box-flex: 1;" +
"}" +
"" +
".boxFlex2 {" +
" -webkit-box-flex: 2;" +
" -moz-box-flex: 2;" +
" box-flex: 2;" +
"}" +
"" +
".boxGroup1 {" +
" -webkit-box-flex-group: 1;" +
" -moz-box-flex-group: 1;" +
" box-flex-group: 1;" +
"}" +
"" +
".boxGroup2 {" +
" -webkit-box-flex-group: 2;" +
" -moz-box-flex-group: 2;" +
" box-flex-group: 2;" +
"}" +
"" +
".start {" +
" -webkit-box-pack: start;" +
" -moz-box-pack: start;" +
" box-pack: start;" +
"}" +
"" +
".end {" +
" -webkit-box-pack: end;" +
" -moz-box-pack: end;" +
" box-pack: end;" +
"}" +
"" +
".center {" +
" -webkit-box-pack: center;" +
" -moz-box-pack: center;" +
" box-pack: center;" +
"}" +
"" +
"/*" +
" clearfix" +
"*/" +
"" +
".clearfix:after {" +
" content: \".\";" +
" display: block;" +
" clear: both;" +
" visibility: hidden;" +
" line-height: 0;" +
" height: 0;" +
"}" +
"" +
"html[xmlns] .clearfix {" +
" display: block;" +
"}" +
"" +
"* html .clearfix {" +
" height: 1%;" +
"}");
define("text/lib/ace/css/editor.css", [], ".ace_editor {" +
" position: absolute;" +
" overflow: hidden;" +
" font-family: Monaco, \"Menlo\", \"Courier New\", monospace;" +
" font-size: 12px;" +
"}" +
"" +
".ace_scroller {" +
" position: absolute;" +
" overflow-x: scroll;" +
" overflow-y: hidden;" +
"}" +
"" +
".ace_content {" +
" position: absolute;" +
" box-sizing: border-box;" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
"}" +
"" +
".ace_composition {" +
" position: absolute;" +
" background: #555;" +
" color: #DDD;" +
" z-index: 4;" +
"}" +
"" +
".ace_gutter {" +
" position: absolute;" +
" overflow-x: hidden;" +
" overflow-y: hidden;" +
" height: 100%;" +
"}" +
"" +
".ace_gutter-cell.ace_error {" +
" background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%F5or%F5%87%88%F5nr%F4ns%EBmq%F5z%7F%DDJT%DEKS%DFOW%F1Yc%F2ah%CE(7%CE)8%D18E%DD%40M%F2KZ%EBU%60%F4%60m%DCir%C8%16(%C8%19*%CE%255%F1%3FR%F1%3FS%E6%AB%B5%CA%5DI%CEn%5E%F7%A2%9A%C9G%3E%E0a%5B%F7%89%85%F5yy%F6%82%80%ED%82%80%FF%BF%BF%E3%C4%C4%FF%FF%FF%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%25%00%2C%00%00%00%00%10%00%10%00%00%06p%C0%92pH%2C%1A%8F%C8%D2H%93%E1d4%23%E4%88%D3%09mB%1DN%B48%F5%90%40%60%92G%5B%94%20%3E%22%D2%87%24%FA%20%24%C5%06A%00%20%B1%07%02B%A38%89X.v%17%82%11%13q%10%0Fi%24%0F%8B%10%7BD%12%0Ei%09%92%09%0EpD%18%15%24%0A%9Ci%05%0C%18F%18%0B%07%04%01%04%06%A0H%18%12%0D%14%0D%12%A1I%B3%B4%B5IA%00%3B\");" +
" background-repeat: no-repeat;" +
" background-position: 4px center;" +
"}" +
"" +
".ace_gutter-cell.ace_warning {" +
" background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%FF%DBr%FF%DE%81%FF%E2%8D%FF%E2%8F%FF%E4%96%FF%E3%97%FF%E5%9D%FF%E6%9E%FF%EE%C1%FF%C8Z%FF%CDk%FF%D0s%FF%D4%81%FF%D5%82%FF%D5%83%FF%DC%97%FF%DE%9D%FF%E7%B8%FF%CCl%7BQ%13%80U%15%82W%16%81U%16%89%5B%18%87%5B%18%8C%5E%1A%94d%1D%C5%83-%C9%87%2F%C6%84.%C6%85.%CD%8B2%C9%871%CB%8A3%CD%8B5%DC%98%3F%DF%9BB%E0%9CC%E1%A5U%CB%871%CF%8B5%D1%8D6%DB%97%40%DF%9AB%DD%99B%E3%B0p%E7%CC%AE%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%2F%00%2C%00%00%00%00%10%00%10%00%00%06a%C0%97pH%2C%1A%8FH%A1%ABTr%25%87%2B%04%82%F4%7C%B9X%91%08%CB%99%1C!%26%13%84*iJ9(%15G%CA%84%14%01%1A%97%0C%03%80%3A%9A%3E%81%84%3E%11%08%B1%8B%20%02%12%0F%18%1A%0F%0A%03'F%1C%04%0B%10%16%18%10%0B%05%1CF%1D-%06%07%9A%9A-%1EG%1B%A0%A1%A0U%A4%A5%A6BA%00%3B\");" +
" background-repeat: no-repeat;" +
" background-position: 4px center;" +
"}" +
"" +
".ace_editor .ace_sb {" +
" position: absolute;" +
" overflow-x: hidden;" +
" overflow-y: scroll;" +
" right: 0;" +
"}" +
"" +
".ace_editor .ace_sb div {" +
" position: absolute;" +
" width: 1px;" +
" left: 0;" +
"}" +
"" +
".ace_editor .ace_print_margin_layer {" +
" z-index: 0;" +
" position: absolute;" +
" overflow: hidden;" +
" margin: 0;" +
" left: 0;" +
" height: 100%;" +
" width: 100%;" +
"}" +
"" +
".ace_editor .ace_print_margin {" +
" position: absolute;" +
" height: 100%;" +
"}" +
"" +
".ace_editor textarea {" +
" position: fixed;" +
" z-index: -1;" +
" width: 10px;" +
" height: 30px;" +
" opacity: 0;" +
" background: transparent;" +
" appearance: none;" +
" -moz-appearance: none;" +
" border: none;" +
" resize: none;" +
" outline: none;" +
" overflow: hidden;" +
"}" +
"" +
".ace_layer {" +
" z-index: 1;" +
" position: absolute;" +
" overflow: hidden;" +
" white-space: nowrap;" +
" height: 100%;" +
" width: 100%;" +
"}" +
"" +
".ace_text-layer {" +
" color: black;" +
"}" +
"" +
".ace_cjk {" +
" display: inline-block;" +
" text-align: center;" +
"}" +
"" +
".ace_cursor-layer {" +
" z-index: 4;" +
" cursor: text;" +
" /* setting pointer-events: none; here will break mouse wheel scrolling in Safari */" +
"}" +
"" +
".ace_cursor {" +
" z-index: 4;" +
" position: absolute;" +
"}" +
"" +
".ace_cursor.ace_hidden {" +
" opacity: 0.2;" +
"}" +
"" +
".ace_line {" +
" white-space: nowrap;" +
"}" +
"" +
".ace_marker-layer {" +
" cursor: text;" +
" pointer-events: none;" +
"}" +
"" +
".ace_marker-layer .ace_step {" +
" position: absolute;" +
" z-index: 3;" +
"}" +
"" +
".ace_marker-layer .ace_selection {" +
" position: absolute;" +
" z-index: 4;" +
"}" +
"" +
".ace_marker-layer .ace_bracket {" +
" position: absolute;" +
" z-index: 5;" +
"}" +
"" +
".ace_marker-layer .ace_active_line {" +
" position: absolute;" +
" z-index: 2;" +
"}" +
"" +
".ace_marker-layer .ace_selected_word {" +
" position: absolute;" +
" z-index: 6;" +
" box-sizing: border-box;" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
"}" +
"" +
".ace_line .ace_fold {" +
" cursor: pointer;" +
"}" +
"" +
".ace_dragging .ace_marker-layer, .ace_dragging .ace_text-layer {" +
" cursor: move;" +
"}" +
"");
define("text/node_modules/uglify-js/docstyle.css", [], "html { font-family: \"Lucida Grande\",\"Trebuchet MS\",sans-serif; font-size: 12pt; }" +
"body { max-width: 60em; }" +
".title { text-align: center; }" +
".todo { color: red; }" +
".done { color: green; }" +
".tag { background-color:lightblue; font-weight:normal }" +
".target { }" +
".timestamp { color: grey }" +
".timestamp-kwd { color: CadetBlue }" +
"p.verse { margin-left: 3% }" +
"pre {" +
" border: 1pt solid #AEBDCC;" +
" background-color: #F3F5F7;" +
" padding: 5pt;" +
" font-family: monospace;" +
" font-size: 90%;" +
" overflow:auto;" +
"}" +
"pre.src {" +
" background-color: #eee; color: #112; border: 1px solid #000;" +
"}" +
"table { border-collapse: collapse; }" +
"td, th { vertical-align: top; }" +
"dt { font-weight: bold; }" +
"div.figure { padding: 0.5em; }" +
"div.figure p { text-align: center; }" +
".linenr { font-size:smaller }" +
".code-highlighted {background-color:#ffff00;}" +
".org-info-js_info-navigation { border-style:none; }" +
"#org-info-js_console-label { font-size:10px; font-weight:bold;" +
" white-space:nowrap; }" +
".org-info-js_search-highlight {background-color:#ffff00; color:#000000;" +
" font-weight:bold; }" +
"" +
"sup {" +
" vertical-align: baseline;" +
" position: relative;" +
" top: -0.5em;" +
" font-size: 80%;" +
"}" +
"" +
"sup a:link, sup a:visited {" +
" text-decoration: none;" +
" color: #c00;" +
"}" +
"" +
"sup a:before { content: \"[\"; color: #999; }" +
"sup a:after { content: \"]\"; color: #999; }" +
"" +
"h1.title { border-bottom: 4px solid #000; padding-bottom: 5px; margin-bottom: 2em; }" +
"" +
"#postamble {" +
" color: #777;" +
" font-size: 90%;" +
" padding-top: 1em; padding-bottom: 1em; border-top: 1px solid #999;" +
" margin-top: 2em;" +
" padding-left: 2em;" +
" padding-right: 2em;" +
" text-align: right;" +
"}" +
"" +
"#postamble p { margin: 0; }" +
"" +
"#footnotes { border-top: 1px solid #000; }" +
"" +
"h1 { font-size: 200% }" +
"h2 { font-size: 175% }" +
"h3 { font-size: 150% }" +
"h4 { font-size: 125% }" +
"" +
"h1, h2, h3, h4 { font-family: \"Bookman\",Georgia,\"Times New Roman\",serif; font-weight: normal; }" +
"" +
"@media print {" +
" html { font-size: 11pt; }" +
"}" +
"");
define("text/support/cockpit/lib/cockpit/ui/cli_view.css", [], "" +
"#cockpitInput { padding-left: 16px; }" +
"" +
".cptOutput { overflow: auto; position: absolute; z-index: 999; display: none; }" +
"" +
".cptCompletion { padding: 0; position: absolute; z-index: -1000; }" +
".cptCompletion.VALID { background: #FFF; }" +
".cptCompletion.INCOMPLETE { background: #DDD; }" +
".cptCompletion.INVALID { background: #DDD; }" +
".cptCompletion span { color: #FFF; }" +
".cptCompletion span.INCOMPLETE { color: #DDD; border-bottom: 2px dotted #F80; }" +
".cptCompletion span.INVALID { color: #DDD; border-bottom: 2px dotted #F00; }" +
"span.cptPrompt { color: #66F; font-weight: bold; }" +
"" +
"" +
".cptHints {" +
" color: #000;" +
" position: absolute;" +
" border: 1px solid rgba(230, 230, 230, 0.8);" +
" background: rgba(250, 250, 250, 0.8);" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 10px; border-top-right-radius: 10px;" +
" z-index: 1000;" +
" padding: 8px;" +
" display: none;" +
"}" +
"" +
".cptFocusPopup { display: block; }" +
".cptFocusPopup.cptNoPopup { display: none; }" +
"" +
".cptHints ul { margin: 0; padding: 0 15px; }" +
"" +
".cptGt { font-weight: bold; font-size: 120%; }" +
"");
define("text/support/cockpit/lib/cockpit/ui/request_view.css", [], "" +
".cptRowIn {" +
" display: box; display: -moz-box; display: -webkit-box;" +
" box-orient: horizontal; -moz-box-orient: horizontal; -webkit-box-orient: horizontal;" +
" box-align: center; -moz-box-align: center; -webkit-box-align: center;" +
" color: #333;" +
" background-color: #EEE;" +
" width: 100%;" +
" font-family: consolas, courier, monospace;" +
"}" +
".cptRowIn > * { padding-left: 2px; padding-right: 2px; }" +
".cptRowIn > img { cursor: pointer; }" +
".cptHover { display: none; }" +
".cptRowIn:hover > .cptHover { display: block; }" +
".cptRowIn:hover > .cptHover.cptHidden { display: none; }" +
".cptOutTyped {" +
" box-flex: 1; -moz-box-flex: 1; -webkit-box-flex: 1;" +
" font-weight: bold; color: #000; font-size: 120%;" +
"}" +
".cptRowOutput { padding-left: 10px; line-height: 1.2em; }" +
".cptRowOutput strong," +
".cptRowOutput b," +
".cptRowOutput th," +
".cptRowOutput h1," +
".cptRowOutput h2," +
".cptRowOutput h3 { color: #000; }" +
".cptRowOutput a { font-weight: bold; color: #666; text-decoration: none; }" +
".cptRowOutput a: hover { text-decoration: underline; cursor: pointer; }" +
".cptRowOutput input[type=password]," +
".cptRowOutput input[type=text]," +
".cptRowOutput textarea {" +
" color: #000; font-size: 120%;" +
" background: transparent; padding: 3px;" +
" border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;" +
"}" +
".cptRowOutput table," +
".cptRowOutput td," +
".cptRowOutput th { border: 0; padding: 0 2px; }" +
".cptRowOutput .right { text-align: right; }" +
"");
define("text/tool/Theme.tmpl.css", [], ".%cssClass% .ace_editor {" +
" border: 2px solid rgb(159, 159, 159);" +
"}" +
"" +
".%cssClass% .ace_editor.ace_focus {" +
" border: 2px solid #327fbd;" +
"}" +
"" +
".%cssClass% .ace_gutter {" +
" width: 50px;" +
" background: #e8e8e8;" +
" color: #333;" +
" overflow : hidden;" +
"}" +
"" +
".%cssClass% .ace_gutter-layer {" +
" width: 100%;" +
" text-align: right;" +
"}" +
"" +
".%cssClass% .ace_gutter-layer .ace_gutter-cell {" +
" padding-right: 6px;" +
"}" +
"" +
".%cssClass% .ace_print_margin {" +
" width: 1px;" +
" background: %printMargin%;" +
"}" +
"" +
".%cssClass% .ace_scroller {" +
" background-color: %background%;" +
"}" +
"" +
".%cssClass% .ace_text-layer {" +
" cursor: text;" +
" color: %foreground%;" +
"}" +
"" +
".%cssClass% .ace_cursor {" +
" border-left: 2px solid %cursor%;" +
"}" +
"" +
".%cssClass% .ace_cursor.ace_overwrite {" +
" border-left: 0px;" +
" border-bottom: 1px solid %overwrite%;" +
"}" +
" " +
".%cssClass% .ace_marker-layer .ace_selection {" +
" background: %selection%;" +
"}" +
"" +
".%cssClass% .ace_marker-layer .ace_step {" +
" background: %step%;" +
"}" +
"" +
".%cssClass% .ace_marker-layer .ace_bracket {" +
" margin: -1px 0 0 -1px;" +
" border: 1px solid %bracket%;" +
"}" +
"" +
".%cssClass% .ace_marker-layer .ace_active_line {" +
" background: %active_line%;" +
"}" +
"" +
" " +
".%cssClass% .ace_invisible {" +
" %invisible%" +
"}" +
"" +
".%cssClass% .ace_keyword {" +
" %keyword%" +
"}" +
"" +
".%cssClass% .ace_keyword.ace_operator {" +
" %keyword.operator%" +
"}" +
"" +
".%cssClass% .ace_constant {" +
" %constant%" +
"}" +
"" +
".%cssClass% .ace_constant.ace_language {" +
" %constant.language%" +
"}" +
"" +
".%cssClass% .ace_constant.ace_library {" +
" %constant.library%" +
"}" +
"" +
".%cssClass% .ace_constant.ace_numeric {" +
" %constant.numeric%" +
"}" +
"" +
".%cssClass% .ace_invalid {" +
" %invalid%" +
"}" +
"" +
".%cssClass% .ace_invalid.ace_illegal {" +
" %invalid.illegal%" +
"}" +
"" +
".%cssClass% .ace_invalid.ace_deprecated {" +
" %invalid.deprecated%" +
"}" +
"" +
".%cssClass% .ace_support {" +
" %support%" +
"}" +
"" +
".%cssClass% .ace_support.ace_function {" +
" %support.function%" +
"}" +
"" +
".%cssClass% .ace_function.ace_buildin {" +
" %function.buildin%" +
"}" +
"" +
".%cssClass% .ace_string {" +
" %string%" +
"}" +
"" +
".%cssClass% .ace_string.ace_regexp {" +
" %string.regexp%" +
"}" +
"" +
".%cssClass% .ace_comment {" +
" %comment%" +
"}" +
"" +
".%cssClass% .ace_comment.ace_doc {" +
" %comment.doc%" +
"}" +
"" +
".%cssClass% .ace_comment.ace_doc.ace_tag {" +
" %comment.doc.tag%" +
"}" +
"" +
".%cssClass% .ace_variable {" +
" %variable%" +
"}" +
"" +
".%cssClass% .ace_variable.ace_language {" +
" %variable.language%" +
"}" +
"" +
".%cssClass% .ace_xml_pe {" +
" %xml_pe%" +
"}" +
"" +
".%cssClass% .ace_collab.ace_user1 {" +
" %collab.user1% " +
"}");
define("text/styles.css", [], "html {" +
" height: 100%;" +
" width: 100%;" +
" overflow: hidden;" +
"}" +
"" +
"body {" +
" overflow: hidden;" +
" margin: 0;" +
" padding: 0;" +
" height: 100%;" +
" width: 100%;" +
" font-family: Arial, Helvetica, sans-serif, Tahoma, Verdana, sans-serif;" +
" font-size: 12px;" +
" background: rgb(14, 98, 165);" +
" color: white;" +
"}" +
"" +
"#logo {" +
" padding: 15px;" +
" margin-left: 65px;" +
"}" +
"" +
"#editor {" +
" position: absolute;" +
" top: 0px;" +
" left: 280px;" +
" bottom: 0px;" +
" right: 0px;" +
" background: white;" +
"}" +
"" +
"#controls {" +
" padding: 5px;" +
"}" +
"" +
"#controls td {" +
" text-align: right;" +
"}" +
"" +
"#controls td + td {" +
" text-align: left;" +
"}" +
"" +
"#cockpitInput {" +
" position: absolute;" +
" left: 280px;" +
" right: 0px;" +
" bottom: 0;" +
"" +
" border: none; outline: none;" +
" font-family: consolas, courier, monospace;" +
" font-size: 120%;" +
"}" +
"" +
"#cockpitOutput {" +
" padding: 10px;" +
" margin: 0 15px;" +
" border: 1px solid #AAA;" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 4px; border-top-right-radius: 4px;" +
" background: #DDD; color: #000;" +
"}");
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
require(["ace/ace"], function(ace) {
window.ace = ace;
}); | zzangtest123-google-drive-sdk-samples | ruby/public/ace/ace-uncompressed.js | JavaScript | asf20 | 582,900 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/index', ['require', 'exports', 'module' , 'pilot/index', 'cockpit/cli', 'cockpit/ui/settings', 'cockpit/ui/cli_view', 'cockpit/commands/basic'], function(require, exports, module) {
exports.startup = function(data, reason) {
require('pilot/index');
require('cockpit/cli').startup(data, reason);
// window.testCli = require('cockpit/test/testCli');
require('cockpit/ui/settings').startup(data, reason);
require('cockpit/ui/cli_view').startup(data, reason);
require('cockpit/commands/basic').startup(data, reason);
};
/*
exports.shutdown(data, reason) {
};
*/
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/cli', ['require', 'exports', 'module' , 'pilot/console', 'pilot/lang', 'pilot/oop', 'pilot/event_emitter', 'pilot/types', 'pilot/canon'], function(require, exports, module) {
var console = require('pilot/console');
var lang = require('pilot/lang');
var oop = require('pilot/oop');
var EventEmitter = require('pilot/event_emitter').EventEmitter;
//var keyboard = require('keyboard/keyboard');
var types = require('pilot/types');
var Status = require('pilot/types').Status;
var Conversion = require('pilot/types').Conversion;
var canon = require('pilot/canon');
/**
* Normally type upgrade is done when the owning command is registered, but
* out commandParam isn't part of a command, so it misses out.
*/
exports.startup = function(data, reason) {
canon.upgradeType('command', commandParam);
};
/**
* The information required to tell the user there is a problem with their
* input.
* TODO: There a several places where {start,end} crop up. Perhaps we should
* have a Cursor object.
*/
function Hint(status, message, start, end, predictions) {
this.status = status;
this.message = message;
if (typeof start === 'number') {
this.start = start;
this.end = end;
this.predictions = predictions;
}
else {
var arg = start;
this.start = arg.start;
this.end = arg.end;
this.predictions = arg.predictions;
}
}
Hint.prototype = {
};
/**
* Loop over the array of hints finding the one we should display.
* @param hints array of hints
*/
Hint.sort = function(hints, cursor) {
// Calculate 'distance from cursor'
if (cursor !== undefined) {
hints.forEach(function(hint) {
if (hint.start === Argument.AT_CURSOR) {
hint.distance = 0;
}
else if (cursor < hint.start) {
hint.distance = hint.start - cursor;
}
else if (cursor > hint.end) {
hint.distance = cursor - hint.end;
}
else {
hint.distance = 0;
}
}, this);
}
// Sort
hints.sort(function(hint1, hint2) {
// Compare first based on distance from cursor
if (cursor !== undefined) {
var diff = hint1.distance - hint2.distance;
if (diff != 0) {
return diff;
}
}
// otherwise go with hint severity
return hint2.status - hint1.status;
});
// tidy-up
if (cursor !== undefined) {
hints.forEach(function(hint) {
delete hint.distance;
}, this);
}
return hints;
};
exports.Hint = Hint;
/**
* A Hint that arose as a result of a Conversion
*/
function ConversionHint(conversion, arg) {
this.status = conversion.status;
this.message = conversion.message;
if (arg) {
this.start = arg.start;
this.end = arg.end;
}
else {
this.start = 0;
this.end = 0;
}
this.predictions = conversion.predictions;
};
oop.inherits(ConversionHint, Hint);
/**
* We record where in the input string an argument comes so we can report errors
* against those string positions.
* We publish a 'change' event when-ever the text changes
* @param emitter Arguments use something else to pass on change events.
* Currently this will be the creating Requisition. This prevents dependency
* loops and prevents us from needing to merge listener lists.
* @param text The string (trimmed) that contains the argument
* @param start The position of the text in the original input string
* @param end See start
* @param prefix Knowledge of quotation marks and whitespace used prior to the
* text in the input string allows us to re-generate the original input from
* the arguments.
* @param suffix Any quotation marks and whitespace used after the text.
* Whitespace is normally placed in the prefix to the succeeding argument, but
* can be used here when this is the last argument.
* @constructor
*/
function Argument(emitter, text, start, end, prefix, suffix) {
this.emitter = emitter;
this.setText(text);
this.start = start;
this.end = end;
this.prefix = prefix;
this.suffix = suffix;
}
Argument.prototype = {
/**
* Return the result of merging these arguments.
* TODO: What happens when we're merging arguments for the single string
* case and some of the arguments are in quotation marks?
*/
merge: function(following) {
if (following.emitter != this.emitter) {
throw new Error('Can\'t merge Arguments from different EventEmitters');
}
return new Argument(
this.emitter,
this.text + this.suffix + following.prefix + following.text,
this.start, following.end,
this.prefix,
following.suffix);
},
/**
* See notes on events in Assignment. We might need to hook changes here
* into a CliRequisition so they appear of the command line.
*/
setText: function(text) {
if (text == null) {
throw new Error('Illegal text for Argument: ' + text);
}
var ev = { argument: this, oldText: this.text, text: text };
this.text = text;
this.emitter._dispatchEvent('argumentChange', ev);
},
/**
* Helper when we're putting arguments back together
*/
toString: function() {
// TODO: There is a bug here - we should re-escape escaped characters
// But can we do that reliably?
return this.prefix + this.text + this.suffix;
}
};
/**
* Merge an array of arguments into a single argument.
* All Arguments in the array are expected to have the same emitter
*/
Argument.merge = function(argArray, start, end) {
start = (start === undefined) ? 0 : start;
end = (end === undefined) ? argArray.length : end;
var joined;
for (var i = start; i < end; i++) {
var arg = argArray[i];
if (!joined) {
joined = arg;
}
else {
joined = joined.merge(arg);
}
}
return joined;
};
/**
* We sometimes need a way to say 'this error occurs where ever the cursor is'
*/
Argument.AT_CURSOR = -1;
/**
* A link between a parameter and the data for that parameter.
* The data for the parameter is available as in the preferred type and as
* an Argument for the CLI.
* <p>We also record validity information where applicable.
* <p>For values, null and undefined have distinct definitions. null means
* that a value has been provided, undefined means that it has not.
* Thus, null is a valid default value, and common because it identifies an
* parameter that is optional. undefined means there is no value from
* the command line.
* @constructor
*/
function Assignment(param, requisition) {
this.param = param;
this.requisition = requisition;
this.setValue(param.defaultValue);
};
Assignment.prototype = {
/**
* The parameter that we are assigning to
* @readonly
*/
param: undefined,
/**
* Report on the status of the last parse() conversion.
* @see types.Conversion
*/
conversion: undefined,
/**
* The current value in a type as specified by param.type
*/
value: undefined,
/**
* The string version of the current value
*/
arg: undefined,
/**
* The current value (i.e. not the string representation)
* Use setValue() to mutate
*/
value: undefined,
setValue: function(value) {
if (this.value === value) {
return;
}
if (value === undefined) {
this.value = this.param.defaultValue;
this.conversion = this.param.getDefault ?
this.param.getDefault() :
this.param.type.getDefault();
this.arg = undefined;
} else {
this.value = value;
this.conversion = undefined;
var text = (value == null) ? '' : this.param.type.stringify(value);
if (this.arg) {
this.arg.setText(text);
}
}
this.requisition._assignmentChanged(this);
},
/**
* The textual representation of the current value
* Use setValue() to mutate
*/
arg: undefined,
setArgument: function(arg) {
if (this.arg === arg) {
return;
}
this.arg = arg;
this.conversion = this.param.type.parse(arg.text);
this.conversion.arg = arg; // TODO: make this automatic?
this.value = this.conversion.value;
this.requisition._assignmentChanged(this);
},
/**
* Create a list of the hints associated with this parameter assignment.
* Generally there will be only one hint generated because we're currently
* only displaying one hint at a time, ordering by distance from cursor
* and severity. Since distance from cursor will be the same for all hints
* from this assignment all but the most severe will ever be used. It might
* make sense with more experience to alter this to function to be getHint()
*/
getHint: function() {
// Allow the parameter to provide documentation
if (this.param.getCustomHint && this.value && this.arg) {
var hint = this.param.getCustomHint(this.value, this.arg);
if (hint) {
return hint;
}
}
// If there is no argument, use the cursor position
var message = '<strong>' + this.param.name + '</strong>: ';
if (this.param.description) {
// TODO: This should be a short description - do we need to trim?
message += this.param.description.trim();
// Ensure the help text ends with '. '
if (message.charAt(message.length - 1) !== '.') {
message += '.';
}
if (message.charAt(message.length - 1) !== ' ') {
message += ' ';
}
}
var status = Status.VALID;
var start = this.arg ? this.arg.start : Argument.AT_CURSOR;
var end = this.arg ? this.arg.end : Argument.AT_CURSOR;
var predictions;
// Non-valid conversions will have useful information to pass on
if (this.conversion) {
status = this.conversion.status;
if (this.conversion.message) {
message += this.conversion.message;
}
predictions = this.conversion.predictions;
}
// Hint if the param is required, but not provided
var argProvided = this.arg && this.arg.text !== '';
var dataProvided = this.value !== undefined || argProvided;
if (this.param.defaultValue === undefined && !dataProvided) {
status = Status.INVALID;
message += '<strong>Required<\strong>';
}
return new Hint(status, message, start, end, predictions);
},
/**
* Basically <tt>setValue(conversion.predictions[0])</tt> done in a safe
* way.
*/
complete: function() {
if (this.conversion && this.conversion.predictions &&
this.conversion.predictions.length > 0) {
this.setValue(this.conversion.predictions[0]);
}
},
/**
* If the cursor is at 'position', do we have sufficient data to start
* displaying the next hint. This is both complex and important.
* For example, if the user has just typed:<ul>
* <li>'set tabstop ' then they clearly want to know about the valid
* values for the tabstop setting, so the hint is based on the next
* parameter.
* <li>'set tabstop' (without trailing space) - they will probably still
* want to know about the valid values for the tabstop setting because
* there is no confusion about the setting in question.
* <li>'set tabsto' they've not finished typing a setting name so the hint
* should be based on the current parameter.
* <li>'set tabstop' (when there is an additional tabstopstyle setting) we
* can't make assumptions about the setting - we're not finished.
* </ul>
* <p>Note that the input for 2 and 4 is identical, only the configuration
* has changed, so hint display is environmental.
*
* <p>This function works out if the cursor is before the end of this
* assignment (assuming that we've asked the same thing of the previous
* assignment) and then attempts to work out if we should use the hint from
* the next assignment even though technically the cursor is still inside
* this one due to the rules above.
*/
isPositionCaptured: function(position) {
if (!this.arg) {
return false;
}
// Note we don't check if position >= this.arg.start because that's
// implied by the fact that we're asking the assignments in turn, and
// we want to avoid thing falling between the cracks, but we do need
// to check that the argument does have a position
if (this.arg.start === -1) {
return false;
}
// We're clearly done if the position is past the end of the text
if (position > this.arg.end) {
return false;
}
// If we're AT the end, the position is captured if either the status
// is not valid or if there are other valid options including current
if (position === this.arg.end) {
return this.conversion.status !== Status.VALID ||
this.conversion.predictions.length !== 0;
}
// Otherwise we're clearly inside
return true;
},
/**
* Replace the current value with the lower value if such a concept
* exists.
*/
decrement: function() {
var replacement = this.param.type.decrement(this.value);
if (replacement != null) {
this.setValue(replacement);
}
},
/**
* Replace the current value with the higher value if such a concept
* exists.
*/
increment: function() {
var replacement = this.param.type.increment(this.value);
if (replacement != null) {
this.setValue(replacement);
}
},
/**
* Helper when we're rebuilding command lines.
*/
toString: function() {
return this.arg ? this.arg.toString() : '';
}
};
exports.Assignment = Assignment;
/**
* This is a special parameter to reflect the command itself.
*/
var commandParam = {
name: '__command',
type: 'command',
description: 'The command to execute',
/**
* Provide some documentation for a command.
*/
getCustomHint: function(command, arg) {
var docs = [];
docs.push('<strong><tt> > ');
docs.push(command.name);
if (command.params && command.params.length > 0) {
command.params.forEach(function(param) {
if (param.defaultValue === undefined) {
docs.push(' [' + param.name + ']');
}
else {
docs.push(' <em>[' + param.name + ']</em>');
}
}, this);
}
docs.push('</tt></strong><br/>');
docs.push(command.description ? command.description : '(No description)');
docs.push('<br/>');
if (command.params && command.params.length > 0) {
docs.push('<ul>');
command.params.forEach(function(param) {
docs.push('<li>');
docs.push('<strong><tt>' + param.name + '</tt></strong>: ');
docs.push(param.description ? param.description : '(No description)');
if (param.defaultValue === undefined) {
docs.push(' <em>[Required]</em>');
}
else if (param.defaultValue === null) {
docs.push(' <em>[Optional]</em>');
}
else {
docs.push(' <em>[Default: ' + param.defaultValue + ']</em>');
}
docs.push('</li>');
}, this);
docs.push('</ul>');
}
return new Hint(Status.VALID, docs.join(''), arg);
}
};
/**
* A Requisition collects the information needed to execute a command.
* There is no point in a requisition for parameter-less commands because there
* is no information to collect. A Requisition is a collection of assignments
* of values to parameters, each handled by an instance of Assignment.
* CliRequisition adds functions for parsing input from a command line to this
* class.
* <h2>Events<h2>
* We publish the following events:<ul>
* <li>argumentChange: The text of some argument has changed. It is likely that
* any UI component displaying this argument will need to be updated. (Note that
* this event is actually published by the Argument itself - see the docs for
* Argument for more details)
* The event object looks like: { argument: A, oldText: B, text: B }
* <li>commandChange: The command has changed. It is likely that a UI
* structure will need updating to match the parameters of the new command.
* The event object looks like { command: A }
* @constructor
*/
function Requisition(env) {
this.env = env;
this.commandAssignment = new Assignment(commandParam, this);
}
Requisition.prototype = {
/**
* The command that we are about to execute.
* @see setCommandConversion()
* @readonly
*/
commandAssignment: undefined,
/**
* The count of assignments. Excludes the commandAssignment
* @readonly
*/
assignmentCount: undefined,
/**
* The object that stores of Assignment objects that we are filling out.
* The Assignment objects are stored under their param.name for named
* lookup. Note: We make use of the property of Javascript objects that
* they are not just hashmaps, but linked-list hashmaps which iterate in
* insertion order.
* Excludes the commandAssignment.
*/
_assignments: undefined,
/**
* The store of hints generated by the assignments. We are trying to prevent
* the UI from needing to access this in broad form, but instead use
* methods that query part of this structure.
*/
_hints: undefined,
/**
* When the command changes, we need to keep a bunch of stuff in sync
*/
_assignmentChanged: function(assignment) {
// This is all about re-creating Assignments
if (assignment.param.name !== '__command') {
return;
}
this._assignments = {};
if (assignment.value) {
assignment.value.params.forEach(function(param) {
this._assignments[param.name] = new Assignment(param, this);
}, this);
}
this.assignmentCount = Object.keys(this._assignments).length;
this._dispatchEvent('commandChange', { command: assignment.value });
},
/**
* Assignments have an order, so we need to store them in an array.
* But we also need named access ...
*/
getAssignment: function(nameOrNumber) {
var name = (typeof nameOrNumber === 'string') ?
nameOrNumber :
Object.keys(this._assignments)[nameOrNumber];
return this._assignments[name];
},
/**
* Where parameter name == assignment names - they are the same.
*/
getParameterNames: function() {
return Object.keys(this._assignments);
},
/**
* A *shallow* clone of the assignments.
* This is useful for systems that wish to go over all the assignments
* finding values one way or another and wish to trim an array as they go.
*/
cloneAssignments: function() {
return Object.keys(this._assignments).map(function(name) {
return this._assignments[name];
}, this);
},
/**
* Collect the statuses from the Assignments.
* The hints returned are sorted by severity
*/
_updateHints: function() {
// TODO: work out when to clear this out for the plain Requisition case
// this._hints = [];
this.getAssignments(true).forEach(function(assignment) {
this._hints.push(assignment.getHint());
}, this);
Hint.sort(this._hints);
// We would like to put some initial help here, but for anyone but
// a complete novice a 'type help' message is very annoying, so we
// need to find a way to only display this message once, or for
// until the user click a 'close' button or similar
// TODO: Add special case for '' input
},
/**
* Returns the most severe status
*/
getWorstHint: function() {
return this._hints[0];
},
/**
* Extract the names and values of all the assignments, and return as
* an object.
*/
getArgsObject: function() {
var args = {};
this.getAssignments().forEach(function(assignment) {
args[assignment.param.name] = assignment.value;
}, this);
return args;
},
/**
* Access the arguments as an array.
* @param includeCommand By default only the parameter arguments are
* returned unless (includeCommand === true), in which case the list is
* prepended with commandAssignment.arg
*/
getAssignments: function(includeCommand) {
var args = [];
if (includeCommand === true) {
args.push(this.commandAssignment);
}
Object.keys(this._assignments).forEach(function(name) {
args.push(this.getAssignment(name));
}, this);
return args;
},
/**
* Reset all the assignments to their default values
*/
setDefaultValues: function() {
this.getAssignments().forEach(function(assignment) {
assignment.setValue(undefined);
}, this);
},
/**
* Helper to call canon.exec
*/
exec: function() {
canon.exec(this.commandAssignment.value,
this.env,
"cli",
this.getArgsObject(),
this.toCanonicalString());
},
/**
* Extract a canonical version of the input
*/
toCanonicalString: function() {
var line = [];
line.push(this.commandAssignment.value.name);
Object.keys(this._assignments).forEach(function(name) {
var assignment = this._assignments[name];
var type = assignment.param.type;
// TODO: This will cause problems if there is a non-default value
// after a default value. Also we need to decide when to use
// named parameters in place of positional params. Both can wait.
if (assignment.value !== assignment.param.defaultValue) {
line.push(' ');
line.push(type.stringify(assignment.value));
}
}, this);
return line.join('');
}
};
oop.implement(Requisition.prototype, EventEmitter);
exports.Requisition = Requisition;
/**
* An object used during command line parsing to hold the various intermediate
* data steps.
* <p>The 'output' of the update is held in 2 objects: input.hints which is an
* array of hints to display to the user. In the future this will become a
* single value.
* <p>The other output value is input.requisition which gives access to an
* args object for use in executing the final command.
*
* <p>The majority of the functions in this class are called in sequence by the
* constructor. Their task is to add to <tt>hints</tt> fill out the requisition.
* <p>The general sequence is:<ul>
* <li>_tokenize(): convert _typed into _parts
* <li>_split(): convert _parts into _command and _unparsedArgs
* <li>_assign(): convert _unparsedArgs into requisition
* </ul>
*
* @param typed {string} The instruction as typed by the user so far
* @param options {object} A list of optional named parameters. Can be any of:
* <b>flags</b>: Flags for us to check against the predicates specified with the
* commands. Defaulted to <tt>keyboard.buildFlags({ });</tt>
* if not specified.
* @constructor
*/
function CliRequisition(env, options) {
Requisition.call(this, env);
if (options && options.flags) {
/**
* TODO: We were using a default of keyboard.buildFlags({ });
* This allowed us to have commands that only existed in certain contexts
* - i.e. Javascript specific commands.
*/
this.flags = options.flags;
}
}
oop.inherits(CliRequisition, Requisition);
(function() {
/**
* Called by the UI when ever the user interacts with a command line input
* @param input A structure that details the state of the input field.
* It should look something like: { typed:a, cursor: { start:b, end:c } }
* Where a is the contents of the input field, and b and c are the start
* and end of the cursor/selection respectively.
*/
CliRequisition.prototype.update = function(input) {
this.input = input;
this._hints = [];
var args = this._tokenize(input.typed);
this._split(args);
if (this.commandAssignment.value) {
this._assign(args);
}
this._updateHints();
};
/**
* Return an array of Status scores so we can create a marked up
* version of the command line input.
*/
CliRequisition.prototype.getInputStatusMarkup = function() {
// 'scores' is an array which tells us what chars are errors
// Initialize with everything VALID
var scores = this.toString().split('').map(function(ch) {
return Status.VALID;
});
// For all chars in all hints, check and upgrade the score
this._hints.forEach(function(hint) {
for (var i = hint.start; i <= hint.end; i++) {
if (hint.status > scores[i]) {
scores[i] = hint.status;
}
}
}, this);
return scores;
};
/**
* Reconstitute the input from the args
*/
CliRequisition.prototype.toString = function() {
return this.getAssignments(true).map(function(assignment) {
return assignment.toString();
}, this).join('');
};
var superUpdateHints = CliRequisition.prototype._updateHints;
/**
* Marks up hints in a number of ways:
* - Makes INCOMPLETE hints that are not near the cursor INVALID since
* they can't be completed by typing
* - Finds the most severe hint, and annotates the array with it
* - Finds the hint to display, and also annotates the array with it
* TODO: I'm wondering if array annotation is evil and we should replace
* this with an object. Need to find out more.
*/
CliRequisition.prototype._updateHints = function() {
superUpdateHints.call(this);
// Not knowing about cursor positioning, the requisition and assignments
// can't know this, but anything they mark as INCOMPLETE is actually
// INVALID unless the cursor is actually inside that argument.
var c = this.input.cursor;
this._hints.forEach(function(hint) {
var startInHint = c.start >= hint.start && c.start <= hint.end;
var endInHint = c.end >= hint.start && c.end <= hint.end;
var inHint = startInHint || endInHint;
if (!inHint && hint.status === Status.INCOMPLETE) {
hint.status = Status.INVALID;
}
}, this);
Hint.sort(this._hints);
};
/**
* Accessor for the hints array.
* While we could just use the hints property, using getHints() is
* preferred for symmetry with Requisition where it needs a function due to
* lack of an atomic update system.
*/
CliRequisition.prototype.getHints = function() {
return this._hints;
};
/**
* Look through the arguments attached to our assignments for the assignment
* at the given position.
*/
CliRequisition.prototype.getAssignmentAt = function(position) {
var assignments = this.getAssignments(true);
for (var i = 0; i < assignments.length; i++) {
var assignment = assignments[i];
if (!assignment.arg) {
// There is no argument in this assignment, we've fallen off
// the end of the obvious answers - it must be this one.
return assignment;
}
if (assignment.isPositionCaptured(position)) {
return assignment;
}
}
return assignment;
};
/**
* Split up the input taking into account ' and "
*/
CliRequisition.prototype._tokenize = function(typed) {
// For blank input, place a dummy empty argument into the list
if (typed == null || typed.length === 0) {
return [ new Argument(this, '', 0, 0, '', '') ];
}
var OUTSIDE = 1; // The last character was whitespace
var IN_SIMPLE = 2; // The last character was part of a parameter
var IN_SINGLE_Q = 3; // We're inside a single quote: '
var IN_DOUBLE_Q = 4; // We're inside double quotes: "
var mode = OUTSIDE;
// First we un-escape. This list was taken from:
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Unicode
// We are generally converting to their real values except for \', \"
// and '\ ' which we are converting to unicode private characters so we
// can distinguish them from ', " and ' ', which have special meaning.
// They need swapping back post-split - see unescape2()
typed = typed
.replace(/\\\\/g, '\\')
.replace(/\\b/g, '\b')
.replace(/\\f/g, '\f')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\t/g, '\t')
.replace(/\\v/g, '\v')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\ /g, '\uF000')
.replace(/\\'/g, '\uF001')
.replace(/\\"/g, '\uF002');
function unescape2(str) {
return str
.replace(/\uF000/g, ' ')
.replace(/\uF001/g, '\'')
.replace(/\uF002/g, '"');
}
var i = 0;
var start = 0; // Where did this section start?
var prefix = '';
var args = [];
while (true) {
if (i >= typed.length) {
// There is nothing else to read - tidy up
if (mode !== OUTSIDE) {
var str = unescape2(typed.substring(start, i));
args.push(new Argument(this, str, start, i, prefix, ''));
}
else {
if (i !== start) {
// There's a bunch of whitespace at the end of the
// command add it to the last argument's suffix,
// creating an empty argument if needed.
var extra = typed.substring(start, i);
var lastArg = args[args.length - 1];
if (!lastArg) {
lastArg = new Argument(this, '', i, i, extra, '');
args.push(lastArg);
}
else {
lastArg.suffix += extra;
}
}
}
break;
}
var c = typed[i];
switch (mode) {
case OUTSIDE:
if (c === '\'') {
prefix = typed.substring(start, i + 1);
mode = IN_SINGLE_Q;
start = i + 1;
}
else if (c === '"') {
prefix = typed.substring(start, i + 1);
mode = IN_DOUBLE_Q;
start = i + 1;
}
else if (/ /.test(c)) {
// Still whitespace, do nothing
}
else {
prefix = typed.substring(start, i);
mode = IN_SIMPLE;
start = i;
}
break;
case IN_SIMPLE:
// There is an edge case of xx'xx which we are assuming to
// be a single parameter (and same with ")
if (c === ' ') {
var str = unescape2(typed.substring(start, i));
args.push(new Argument(this, str,
start, i, prefix, ''));
mode = OUTSIDE;
start = i;
prefix = '';
}
break;
case IN_SINGLE_Q:
if (c === '\'') {
var str = unescape2(typed.substring(start, i));
args.push(new Argument(this, str,
start - 1, i + 1, prefix, c));
mode = OUTSIDE;
start = i + 1;
prefix = '';
}
break;
case IN_DOUBLE_Q:
if (c === '"') {
var str = unescape2(typed.substring(start, i));
args.push(new Argument(this, str,
start - 1, i + 1, prefix, c));
mode = OUTSIDE;
start = i + 1;
prefix = '';
}
break;
}
i++;
}
return args;
};
/**
* Looks in the canon for a command extension that matches what has been
* typed at the command line.
*/
CliRequisition.prototype._split = function(args) {
var argsUsed = 1;
var arg;
while (argsUsed <= args.length) {
var arg = Argument.merge(args, 0, argsUsed);
this.commandAssignment.setArgument(arg);
if (!this.commandAssignment.value) {
// Not found. break with value == null
break;
}
/*
// Previously we needed a way to hide commands depending context.
// We have not resurrected that feature yet.
if (!keyboard.flagsMatch(command.predicates, this.flags)) {
// If the predicates say 'no match' then go LA LA LA
command = null;
break;
}
*/
if (this.commandAssignment.value.exec) {
// Valid command, break with command valid
for (var i = 0; i < argsUsed; i++) {
args.shift();
}
break;
}
argsUsed++;
}
};
/**
* Work out which arguments are applicable to which parameters.
* <p>This takes #_command.params and #_unparsedArgs and creates a map of
* param names to 'assignment' objects, which have the following properties:
* <ul>
* <li>param - The matching parameter.
* <li>index - Zero based index into where the match came from on the input
* <li>value - The matching input
* </ul>
*/
CliRequisition.prototype._assign = function(args) {
if (args.length === 0) {
this.setDefaultValues();
return;
}
// Create an error if the command does not take parameters, but we have
// been given them ...
if (this.assignmentCount === 0) {
// TODO: previously we were doing some extra work to avoid this if
// we determined that we had args that were all whitespace, but
// probably given our tighter tokenize() this won't be an issue?
this._hints.push(new Hint(Status.INVALID,
this.commandAssignment.value.name +
' does not take any parameters',
Argument.merge(args)));
return;
}
// Special case: if there is only 1 parameter, and that's of type
// text we put all the params into the first param
if (this.assignmentCount === 1) {
var assignment = this.getAssignment(0);
if (assignment.param.type.name === 'text') {
assignment.setArgument(Argument.merge(args));
return;
}
}
var assignments = this.cloneAssignments();
var names = this.getParameterNames();
// Extract all the named parameters
var used = [];
assignments.forEach(function(assignment) {
var namedArgText = '--' + assignment.name;
var i = 0;
while (true) {
var arg = args[i];
if (namedArgText !== arg.text) {
i++;
if (i >= args.length) {
break;
}
continue;
}
// boolean parameters don't have values, default to false
if (assignment.param.type.name === 'boolean') {
assignment.setValue(true);
}
else {
if (i + 1 < args.length) {
// Missing value portion of this named param
this._hints.push(new Hint(Status.INCOMPLETE,
'Missing value for: ' + namedArgText,
args[i]));
}
else {
args.splice(i + 1, 1);
assignment.setArgument(args[i + 1]);
}
}
lang.arrayRemove(names, assignment.name);
args.splice(i, 1);
// We don't need to i++ if we splice
}
}, this);
// What's left are positional parameters assign in order
names.forEach(function(name) {
var assignment = this.getAssignment(name);
if (args.length === 0) {
// No more values
assignment.setValue(undefined); // i.e. default
}
else {
var arg = args[0];
args.splice(0, 1);
assignment.setArgument(arg);
}
}, this);
if (args.length > 0) {
var remaining = Argument.merge(args);
this._hints.push(new Hint(Status.INVALID,
'Input \'' + remaining.text + '\' makes no sense.',
remaining));
}
};
})();
exports.CliRequisition = CliRequisition;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/ui/settings', ['require', 'exports', 'module' , 'pilot/types', 'pilot/types/basic'], function(require, exports, module) {
var types = require("pilot/types");
var SelectionType = require('pilot/types/basic').SelectionType;
var direction = new SelectionType({
name: 'direction',
data: [ 'above', 'below' ]
});
var hintDirectionSetting = {
name: "hintDirection",
description: "Are hints shown above or below the command line?",
type: "direction",
defaultValue: "above"
};
var outputDirectionSetting = {
name: "outputDirection",
description: "Is the output window shown above or below the command line?",
type: "direction",
defaultValue: "above"
};
var outputHeightSetting = {
name: "outputHeight",
description: "What height should the output panel be?",
type: "number",
defaultValue: 300
};
exports.startup = function(data, reason) {
types.registerType(direction);
data.env.settings.addSetting(hintDirectionSetting);
data.env.settings.addSetting(outputDirectionSetting);
data.env.settings.addSetting(outputHeightSetting);
};
exports.shutdown = function(data, reason) {
types.unregisterType(direction);
data.env.settings.removeSetting(hintDirectionSetting);
data.env.settings.removeSetting(outputDirectionSetting);
data.env.settings.removeSetting(outputHeightSetting);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/ui/cli_view', ['require', 'exports', 'module' , 'text!cockpit/ui/cli_view.css', 'pilot/event', 'pilot/dom', 'pilot/keys', 'pilot/canon', 'pilot/types', 'cockpit/cli', 'cockpit/ui/request_view'], function(require, exports, module) {
var editorCss = require("text!cockpit/ui/cli_view.css");
var event = require("pilot/event");
var dom = require("pilot/dom");
dom.importCssString(editorCss);
var event = require("pilot/event");
var keys = require("pilot/keys");
var canon = require("pilot/canon");
var Status = require('pilot/types').Status;
var CliRequisition = require('cockpit/cli').CliRequisition;
var Hint = require('cockpit/cli').Hint;
var RequestView = require('cockpit/ui/request_view').RequestView;
var NO_HINT = new Hint(Status.VALID, '', 0, 0);
/**
* On startup we need to:
* 1. Add 3 sets of elements to the DOM for:
* - command line output
* - input hints
* - completion
* 2. Attach a set of events so the command line works
*/
exports.startup = function(data, reason) {
var cli = new CliRequisition(data.env);
var cliView = new CliView(cli, data.env);
data.env.cli = cli;
};
/**
* A class to handle the simplest UI implementation
*/
function CliView(cli, env) {
cli.cliView = this;
this.cli = cli;
this.doc = document;
this.win = dom.getParentWindow(this.doc);
this.env = env;
// TODO: we should have a better way to specify command lines???
this.element = this.doc.getElementById('cockpitInput');
if (!this.element) {
// console.log('No element with an id of cockpit. Bailing on cli');
return;
}
this.settings = env.settings;
this.hintDirection = this.settings.getSetting('hintDirection');
this.outputDirection = this.settings.getSetting('outputDirection');
this.outputHeight = this.settings.getSetting('outputHeight');
// If the requisition tells us something has changed, we use this to know
// if we should ignore it
this.isUpdating = false;
this.createElements();
this.update();
}
CliView.prototype = {
/**
* Create divs for completion, hints and output
*/
createElements: function() {
var input = this.element;
this.element.spellcheck = false;
this.output = this.doc.getElementById('cockpitOutput');
this.popupOutput = (this.output == null);
if (!this.output) {
this.output = this.doc.createElement('div');
this.output.id = 'cockpitOutput';
this.output.className = 'cptOutput';
input.parentNode.insertBefore(this.output, input.nextSibling);
var setMaxOutputHeight = function() {
this.output.style.maxHeight = this.outputHeight.get() + 'px';
}.bind(this);
this.outputHeight.addEventListener('change', setMaxOutputHeight);
setMaxOutputHeight();
}
this.completer = this.doc.createElement('div');
this.completer.className = 'cptCompletion VALID';
this.completer.style.color = dom.computedStyle(input, "color");
this.completer.style.fontSize = dom.computedStyle(input, "fontSize");
this.completer.style.fontFamily = dom.computedStyle(input, "fontFamily");
this.completer.style.fontWeight = dom.computedStyle(input, "fontWeight");
this.completer.style.fontStyle = dom.computedStyle(input, "fontStyle");
input.parentNode.insertBefore(this.completer, input.nextSibling);
// Transfer background styling to the completer.
this.completer.style.backgroundColor = input.style.backgroundColor;
input.style.backgroundColor = 'transparent';
this.hinter = this.doc.createElement('div');
this.hinter.className = 'cptHints';
input.parentNode.insertBefore(this.hinter, input.nextSibling);
var resizer = this.resizer.bind(this);
event.addListener(this.win, 'resize', resizer);
this.hintDirection.addEventListener('change', resizer);
this.outputDirection.addEventListener('change', resizer);
resizer();
canon.addEventListener('output', function(ev) {
new RequestView(ev.request, this);
}.bind(this));
event.addCommandKeyListener(input, this.onCommandKey.bind(this));
event.addListener(input, 'keyup', this.onKeyUp.bind(this));
// cursor position affects hint severity. TODO: shortcuts for speed
event.addListener(input, 'mouseup', function(ev) {
this.isUpdating = true;
this.update();
this.isUpdating = false;
}.bind(this));
this.cli.addEventListener('argumentChange', this.onArgChange.bind(this));
event.addListener(input, "focus", function() {
dom.addCssClass(this.output, "cptFocusPopup");
dom.addCssClass(this.hinter, "cptFocusPopup");
}.bind(this));
function hideOutput() {
dom.removeCssClass(this.output, "cptFocusPopup");
dom.removeCssClass(this.hinter, "cptFocusPopup");
};
event.addListener(input, "blur", hideOutput.bind(this));
hideOutput.call(this);
},
/**
* We need to see the output of the latest command entered
*/
scrollOutputToBottom: function() {
// Certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(this.output.scrollHeight, this.output.clientHeight);
this.output.scrollTop = scrollHeight - this.output.clientHeight;
},
/**
* To be called on window resize or any time we want to align the elements
* with the input box.
*/
resizer: function() {
var rect = this.element.getClientRects()[0];
this.completer.style.top = rect.top + 'px';
var height = rect.bottom - rect.top;
this.completer.style.height = height + 'px';
this.completer.style.lineHeight = height + 'px';
this.completer.style.left = rect.left + 'px';
var width = rect.right - rect.left;
this.completer.style.width = width + 'px';
if (this.hintDirection.get() === 'below') {
this.hinter.style.top = rect.bottom + 'px';
this.hinter.style.bottom = 'auto';
}
else {
this.hinter.style.top = 'auto';
this.hinter.style.bottom = (this.doc.documentElement.clientHeight - rect.top) + 'px';
}
this.hinter.style.left = (rect.left + 30) + 'px';
this.hinter.style.maxWidth = (width - 110) + 'px';
if (this.popupOutput) {
if (this.outputDirection.get() === 'below') {
this.output.style.top = rect.bottom + 'px';
this.output.style.bottom = 'auto';
}
else {
this.output.style.top = 'auto';
this.output.style.bottom = (this.doc.documentElement.clientHeight - rect.top) + 'px';
}
this.output.style.left = rect.left + 'px';
this.output.style.width = (width - 80) + 'px';
}
},
/**
* Ensure that TAB isn't handled by the browser
*/
onCommandKey: function(ev, hashId, keyCode) {
var stopEvent;
if (keyCode === keys.TAB ||
keyCode === keys.UP ||
keyCode === keys.DOWN) {
stopEvent = true;
} else if (hashId != 0 || keyCode != 0) {
stopEvent = canon.execKeyCommand(this.env, 'cli', hashId, keyCode);
}
stopEvent && event.stopEvent(ev);
},
/**
* The main keyboard processing loop
*/
onKeyUp: function(ev) {
var handled;
/*
var handled = keyboardManager.processKeyEvent(ev, this, {
isCommandLine: true, isKeyUp: true
});
*/
// RETURN does a special exec/highlight thing
if (ev.keyCode === keys.RETURN) {
var worst = this.cli.getWorstHint();
// Deny RETURN unless the command might work
if (worst.status === Status.VALID) {
this.cli.exec();
this.element.value = '';
}
else {
// If we've denied RETURN because the command was not VALID,
// select the part of the command line that is causing problems
// TODO: if there are 2 errors are we picking the right one?
dom.setSelectionStart(this.element, worst.start);
dom.setSelectionEnd(this.element, worst.end);
}
}
this.update();
// Special actions which delegate to the assignment
var current = this.cli.getAssignmentAt(dom.getSelectionStart(this.element));
if (current) {
// TAB does a special complete thing
if (ev.keyCode === keys.TAB) {
current.complete();
this.update();
}
// UP/DOWN look for some history
if (ev.keyCode === keys.UP) {
current.increment();
this.update();
}
if (ev.keyCode === keys.DOWN) {
current.decrement();
this.update();
}
}
return handled;
},
/**
* Actually parse the input and make sure we're all up to date
*/
update: function() {
this.isUpdating = true;
var input = {
typed: this.element.value,
cursor: {
start: dom.getSelectionStart(this.element),
end: dom.getSelectionEnd(this.element.selectionEnd)
}
};
this.cli.update(input);
var display = this.cli.getAssignmentAt(input.cursor.start).getHint();
// 1. Update the completer with prompt/error marker/TAB info
dom.removeCssClass(this.completer, Status.VALID.toString());
dom.removeCssClass(this.completer, Status.INCOMPLETE.toString());
dom.removeCssClass(this.completer, Status.INVALID.toString());
var completion = '<span class="cptPrompt">></span> ';
if (this.element.value.length > 0) {
var scores = this.cli.getInputStatusMarkup();
completion += this.markupStatusScore(scores);
}
// Display the "-> prediction" at the end of the completer
if (this.element.value.length > 0 &&
display.predictions && display.predictions.length > 0) {
var tab = display.predictions[0];
completion += ' ⇥ ' + (tab.name ? tab.name : tab);
}
this.completer.innerHTML = completion;
dom.addCssClass(this.completer, this.cli.getWorstHint().status.toString());
// 2. Update the hint element
var hint = '';
if (this.element.value.length !== 0) {
hint += display.message;
if (display.predictions && display.predictions.length > 0) {
hint += ': [ ';
display.predictions.forEach(function(prediction) {
hint += (prediction.name ? prediction.name : prediction);
hint += ' | ';
}, this);
hint = hint.replace(/\| $/, ']');
}
}
this.hinter.innerHTML = hint;
if (hint.length === 0) {
dom.addCssClass(this.hinter, 'cptNoPopup');
}
else {
dom.removeCssClass(this.hinter, 'cptNoPopup');
}
this.isUpdating = false;
},
/**
* Markup an array of Status values with spans
*/
markupStatusScore: function(scores) {
var completion = '';
// Create mark-up
var i = 0;
var lastStatus = -1;
while (true) {
if (lastStatus !== scores[i]) {
completion += '<span class=' + scores[i].toString() + '>';
lastStatus = scores[i];
}
completion += this.element.value[i];
i++;
if (i === this.element.value.length) {
completion += '</span>';
break;
}
if (lastStatus !== scores[i]) {
completion += '</span>';
}
}
return completion;
},
/**
* Update the input element to reflect the changed argument
*/
onArgChange: function(ev) {
if (this.isUpdating) {
return;
}
var prefix = this.element.value.substring(0, ev.argument.start);
var suffix = this.element.value.substring(ev.argument.end);
var insert = typeof ev.text === 'string' ? ev.text : ev.text.name;
this.element.value = prefix + insert + suffix;
// Fix the cursor.
var insertEnd = (prefix + insert).length;
this.element.selectionStart = insertEnd;
this.element.selectionEnd = insertEnd;
}
};
exports.CliView = CliView;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/ui/request_view', ['require', 'exports', 'module' , 'pilot/dom', 'pilot/event', 'text!cockpit/ui/request_view.html', 'pilot/domtemplate', 'text!cockpit/ui/request_view.css'], function(require, exports, module) {
var dom = require("pilot/dom");
var event = require("pilot/event");
var requestViewHtml = require("text!cockpit/ui/request_view.html");
var Templater = require("pilot/domtemplate").Templater;
var requestViewCss = require("text!cockpit/ui/request_view.css");
dom.importCssString(requestViewCss);
/**
* Pull the HTML into the DOM, but don't add it to the document
*/
var templates = document.createElement('div');
templates.innerHTML = requestViewHtml;
var row = templates.querySelector('.cptRow');
/**
* Work out the path for images.
* TODO: This should probably live in some utility area somewhere
*/
function imageUrl(path) {
var dataUrl;
try {
dataUrl = require('text!cockpit/ui/' + path);
} catch (e) { }
if (dataUrl) {
return dataUrl;
}
var filename = module.id.split('/').pop() + '.js';
var imagePath;
if (module.uri.substr(-filename.length) !== filename) {
console.error('Can\'t work out path from module.uri/module.id');
return path;
}
if (module.uri) {
var end = module.uri.length - filename.length - 1;
return module.uri.substr(0, end) + "/" + path;
}
return filename + path;
}
/**
* Adds a row to the CLI output display
*/
function RequestView(request, cliView) {
this.request = request;
this.cliView = cliView;
this.imageUrl = imageUrl;
// Elements attached to this by the templater. For info only
this.rowin = null;
this.rowout = null;
this.output = null;
this.hide = null;
this.show = null;
this.duration = null;
this.throb = null;
new Templater().processNode(row.cloneNode(true), this);
this.cliView.output.appendChild(this.rowin);
this.cliView.output.appendChild(this.rowout);
this.request.addEventListener('output', this.onRequestChange.bind(this));
};
RequestView.prototype = {
/**
* A single click on an invocation line in the console copies the command to
* the command line
*/
copyToInput: function() {
this.cliView.element.value = this.request.typed;
},
/**
* A double click on an invocation line in the console executes the command
*/
executeRequest: function(ev) {
this.cliView.cli.update({
typed: this.request.typed,
cursor: { start:0, end:0 }
});
this.cliView.cli.exec();
},
hideOutput: function(ev) {
this.output.style.display = 'none';
dom.addCssClass(this.hide, 'cmd_hidden');
dom.removeCssClass(this.show, 'cmd_hidden');
event.stopPropagation(ev);
},
showOutput: function(ev) {
this.output.style.display = 'block';
dom.removeCssClass(this.hide, 'cmd_hidden');
dom.addCssClass(this.show, 'cmd_hidden');
event.stopPropagation(ev);
},
remove: function(ev) {
this.cliView.output.removeChild(this.rowin);
this.cliView.output.removeChild(this.rowout);
event.stopPropagation(ev);
},
onRequestChange: function(ev) {
this.duration.innerHTML = this.request.duration ?
'completed in ' + (this.request.duration / 1000) + ' sec ' :
'';
this.output.innerHTML = '';
this.request.outputs.forEach(function(output) {
var node;
if (typeof output == 'string') {
node = document.createElement('p');
node.innerHTML = output;
} else {
node = output;
}
this.output.appendChild(node);
}, this);
this.cliView.scrollOutputToBottom();
dom.setCssClass(this.output, 'cmd_error', this.request.error);
this.throb.style.display = this.request.completed ? 'none' : 'block';
}
};
exports.RequestView = RequestView;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is DomTemplate.
*
* The Initial Developer of the Original Code is Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com) (original author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/domtemplate', ['require', 'exports', 'module' ], function(require, exports, module) {
// WARNING: do not 'use_strict' without reading the notes in envEval;
/**
* A templater that allows one to quickly template DOM nodes.
*/
function Templater() {
this.scope = [];
};
/**
* Recursive function to walk the tree processing the attributes as it goes.
* @param node the node to process. If you pass a string in instead of a DOM
* element, it is assumed to be an id for use with document.getElementById()
* @param data the data to use for node processing.
*/
Templater.prototype.processNode = function(node, data) {
if (typeof node === 'string') {
node = document.getElementById(node);
}
if (data === null || data === undefined) {
data = {};
}
this.scope.push(node.nodeName + (node.id ? '#' + node.id : ''));
try {
// Process attributes
if (node.attributes && node.attributes.length) {
// We need to handle 'foreach' and 'if' first because they might stop
// some types of processing from happening, and foreach must come first
// because it defines new data on which 'if' might depend.
if (node.hasAttribute('foreach')) {
this.processForEach(node, data);
return;
}
if (node.hasAttribute('if')) {
if (!this.processIf(node, data)) {
return;
}
}
// Only make the node available once we know it's not going away
data.__element = node;
// It's good to clean up the attributes when we've processed them,
// but if we do it straight away, we mess up the array index
var attrs = Array.prototype.slice.call(node.attributes);
for (var i = 0; i < attrs.length; i++) {
var value = attrs[i].value;
var name = attrs[i].name;
this.scope.push(name);
try {
if (name === 'save') {
// Save attributes are a setter using the node
value = this.stripBraces(value);
this.property(value, data, node);
node.removeAttribute('save');
} else if (name.substring(0, 2) === 'on') {
// Event registration relies on property doing a bind
value = this.stripBraces(value);
var func = this.property(value, data);
if (typeof func !== 'function') {
this.handleError('Expected ' + value +
' to resolve to a function, but got ' + typeof func);
}
node.removeAttribute(name);
var capture = node.hasAttribute('capture' + name.substring(2));
node.addEventListener(name.substring(2), func, capture);
if (capture) {
node.removeAttribute('capture' + name.substring(2));
}
} else {
// Replace references in all other attributes
var self = this;
var newValue = value.replace(/\$\{[^}]*\}/g, function(path) {
return self.envEval(path.slice(2, -1), data, value);
});
// Remove '_' prefix of attribute names so the DOM won't try
// to use them before we've processed the template
if (name.charAt(0) === '_') {
node.removeAttribute(name);
node.setAttribute(name.substring(1), newValue);
} else if (value !== newValue) {
attrs[i].value = newValue;
}
}
} finally {
this.scope.pop();
}
}
}
// Loop through our children calling processNode. First clone them, so the
// set of nodes that we visit will be unaffected by additions or removals.
var childNodes = Array.prototype.slice.call(node.childNodes);
for (var j = 0; j < childNodes.length; j++) {
this.processNode(childNodes[j], data);
}
if (node.nodeType === Node.TEXT_NODE) {
this.processTextNode(node, data);
}
} finally {
this.scope.pop();
}
};
/**
* Handle <x if="${...}">
* @param node An element with an 'if' attribute
* @param data The data to use with envEval
* @returns true if processing should continue, false otherwise
*/
Templater.prototype.processIf = function(node, data) {
this.scope.push('if');
try {
var originalValue = node.getAttribute('if');
var value = this.stripBraces(originalValue);
var recurse = true;
try {
var reply = this.envEval(value, data, originalValue);
recurse = !!reply;
} catch (ex) {
this.handleError('Error with \'' + value + '\'', ex);
recurse = false;
}
if (!recurse) {
node.parentNode.removeChild(node);
}
node.removeAttribute('if');
return recurse;
} finally {
this.scope.pop();
}
};
/**
* Handle <x foreach="param in ${array}"> and the special case of
* <loop foreach="param in ${array}">
* @param node An element with a 'foreach' attribute
* @param data The data to use with envEval
*/
Templater.prototype.processForEach = function(node, data) {
this.scope.push('foreach');
try {
var originalValue = node.getAttribute('foreach');
var value = originalValue;
var paramName = 'param';
if (value.charAt(0) === '$') {
// No custom loop variable name. Use the default: 'param'
value = this.stripBraces(value);
} else {
// Extract the loop variable name from 'NAME in ${ARRAY}'
var nameArr = value.split(' in ');
paramName = nameArr[0].trim();
value = this.stripBraces(nameArr[1].trim());
}
node.removeAttribute('foreach');
try {
var self = this;
// Process a single iteration of a loop
var processSingle = function(member, clone, ref) {
ref.parentNode.insertBefore(clone, ref);
data[paramName] = member;
self.processNode(clone, data);
delete data[paramName];
};
// processSingle is no good for <loop> nodes where we want to work on
// the childNodes rather than the node itself
var processAll = function(scope, member) {
self.scope.push(scope);
try {
if (node.nodeName === 'LOOP') {
for (var i = 0; i < node.childNodes.length; i++) {
var clone = node.childNodes[i].cloneNode(true);
processSingle(member, clone, node);
}
} else {
var clone = node.cloneNode(true);
clone.removeAttribute('foreach');
processSingle(member, clone, node);
}
} finally {
self.scope.pop();
}
};
var reply = this.envEval(value, data, originalValue);
if (Array.isArray(reply)) {
reply.forEach(function(data, i) {
processAll('' + i, data);
}, this);
} else {
for (var param in reply) {
if (reply.hasOwnProperty(param)) {
processAll(param, param);
}
}
}
node.parentNode.removeChild(node);
} catch (ex) {
this.handleError('Error with \'' + value + '\'', ex);
}
} finally {
this.scope.pop();
}
};
/**
* Take a text node and replace it with another text node with the ${...}
* sections parsed out. We replace the node by altering node.parentNode but
* we could probably use a DOM Text API to achieve the same thing.
* @param node The Text node to work on
* @param data The data to use in calls to envEval
*/
Templater.prototype.processTextNode = function(node, data) {
// Replace references in other attributes
var value = node.data;
// We can't use the string.replace() with function trick (see generic
// attribute processing in processNode()) because we need to support
// functions that return DOM nodes, so we can't have the conversion to a
// string.
// Instead we process the string as an array of parts. In order to split
// the string up, we first replace '${' with '\uF001$' and '}' with '\uF002'
// We can then split using \uF001 or \uF002 to get an array of strings
// where scripts are prefixed with $.
// \uF001 and \uF002 are just unicode chars reserved for private use.
value = value.replace(/\$\{([^}]*)\}/g, '\uF001$$$1\uF002');
var parts = value.split(/\uF001|\uF002/);
if (parts.length > 1) {
parts.forEach(function(part) {
if (part === null || part === undefined || part === '') {
return;
}
if (part.charAt(0) === '$') {
part = this.envEval(part.slice(1), data, node.data);
}
// It looks like this was done a few lines above but see envEval
if (part === null) {
part = "null";
}
if (part === undefined) {
part = "undefined";
}
// if (isDOMElement(part)) { ... }
if (typeof part.cloneNode !== 'function') {
part = node.ownerDocument.createTextNode(part.toString());
}
node.parentNode.insertBefore(part, node);
}, this);
node.parentNode.removeChild(node);
}
};
/**
* Warn of string does not begin '${' and end '}'
* @param str the string to check.
* @return The string stripped of ${ and }, or untouched if it does not match
*/
Templater.prototype.stripBraces = function(str) {
if (!str.match(/\$\{.*\}/g)) {
this.handleError('Expected ' + str + ' to match ${...}');
return str;
}
return str.slice(2, -1);
};
/**
* Combined getter and setter that works with a path through some data set.
* For example:
* <ul>
* <li>property('a.b', { a: { b: 99 }}); // returns 99
* <li>property('a', { a: { b: 99 }}); // returns { b: 99 }
* <li>property('a', { a: { b: 99 }}, 42); // returns 99 and alters the
* input data to be { a: { b: 42 }}
* </ul>
* @param path An array of strings indicating the path through the data, or
* a string to be cut into an array using <tt>split('.')</tt>
* @param data An object to look in for the <tt>path</tt> argument
* @param newValue (optional) If defined, this value will replace the
* original value for the data at the path specified.
* @return The value pointed to by <tt>path</tt> before any
* <tt>newValue</tt> is applied.
*/
Templater.prototype.property = function(path, data, newValue) {
this.scope.push(path);
try {
if (typeof path === 'string') {
path = path.split('.');
}
var value = data[path[0]];
if (path.length === 1) {
if (newValue !== undefined) {
data[path[0]] = newValue;
}
if (typeof value === 'function') {
return function() {
return value.apply(data, arguments);
};
}
return value;
}
if (!value) {
this.handleError('Can\'t find path=' + path);
return null;
}
return this.property(path.slice(1), value, newValue);
} finally {
this.scope.pop();
}
};
/**
* Like eval, but that creates a context of the variables in <tt>env</tt> in
* which the script is evaluated.
* WARNING: This script uses 'with' which is generally regarded to be evil.
* The alternative is to create a Function at runtime that takes X parameters
* according to the X keys in the env object, and then call that function using
* the values in the env object. This is likely to be slow, but workable.
* @param script The string to be evaluated.
* @param env The environment in which to eval the script.
* @param context Optional debugging string in case of failure
* @return The return value of the script, or the error message if the script
* execution failed.
*/
Templater.prototype.envEval = function(script, env, context) {
with (env) {
try {
this.scope.push(context);
return eval(script);
} catch (ex) {
this.handleError('Template error evaluating \'' + script + '\'', ex);
return script;
} finally {
this.scope.pop();
}
}
};
/**
* A generic way of reporting errors, for easy overloading in different
* environments.
* @param message the error message to report.
* @param ex optional associated exception.
*/
Templater.prototype.handleError = function(message, ex) {
this.logError(message);
this.logError('In: ' + this.scope.join(' > '));
if (ex) {
this.logError(ex);
}
};
/**
* A generic way of reporting errors, for easy overloading in different
* environments.
* @param message the error message to report.
*/
Templater.prototype.logError = function(message) {
window.console && window.console.log && console.log(message);
};
exports.Templater = Templater;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Skywriter Team (skywriter@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/commands/basic', ['require', 'exports', 'module' , 'pilot/canon'], function(require, exports, module) {
var canon = require('pilot/canon');
/**
* '!' command
*/
var bangCommandSpec = {
name: 'sh',
description: 'Execute a system command (requires server support)',
params: [
{
name: 'command',
type: 'text',
description: 'The string to send to the os shell.'
}
],
exec: function(env, args, request) {
var req = new XMLHttpRequest();
req.open('GET', '/exec?args=' + args.command, true);
req.onreadystatechange = function(ev) {
if (req.readyState == 4) {
if (req.status == 200) {
request.done('<pre>' + req.responseText + '</pre>');
}
}
};
req.send(null);
}
};
var canon = require('pilot/canon');
exports.startup = function(data, reason) {
canon.addCommand(bangCommandSpec);
};
exports.shutdown = function(data, reason) {
canon.removeCommand(bangCommandSpec);
};
});
define("text!cockpit/ui/cli_view.css", [], "" +
"#cockpitInput { padding-left: 16px; }" +
"" +
".cptOutput { overflow: auto; position: absolute; z-index: 999; display: none; }" +
"" +
".cptCompletion { padding: 0; position: absolute; z-index: -1000; }" +
".cptCompletion.VALID { background: #FFF; }" +
".cptCompletion.INCOMPLETE { background: #DDD; }" +
".cptCompletion.INVALID { background: #DDD; }" +
".cptCompletion span { color: #FFF; }" +
".cptCompletion span.INCOMPLETE { color: #DDD; border-bottom: 2px dotted #F80; }" +
".cptCompletion span.INVALID { color: #DDD; border-bottom: 2px dotted #F00; }" +
"span.cptPrompt { color: #66F; font-weight: bold; }" +
"" +
"" +
".cptHints {" +
" color: #000;" +
" position: absolute;" +
" border: 1px solid rgba(230, 230, 230, 0.8);" +
" background: rgba(250, 250, 250, 0.8);" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 10px; border-top-right-radius: 10px;" +
" z-index: 1000;" +
" padding: 8px;" +
" display: none;" +
"}" +
"" +
".cptFocusPopup { display: block; }" +
".cptFocusPopup.cptNoPopup { display: none; }" +
"" +
".cptHints ul { margin: 0; padding: 0 15px; }" +
"" +
".cptGt { font-weight: bold; font-size: 120%; }" +
"");
define("text!cockpit/ui/request_view.css", [], "" +
".cptRowIn {" +
" display: box; display: -moz-box; display: -webkit-box;" +
" box-orient: horizontal; -moz-box-orient: horizontal; -webkit-box-orient: horizontal;" +
" box-align: center; -moz-box-align: center; -webkit-box-align: center;" +
" color: #333;" +
" background-color: #EEE;" +
" width: 100%;" +
" font-family: consolas, courier, monospace;" +
"}" +
".cptRowIn > * { padding-left: 2px; padding-right: 2px; }" +
".cptRowIn > img { cursor: pointer; }" +
".cptHover { display: none; }" +
".cptRowIn:hover > .cptHover { display: block; }" +
".cptRowIn:hover > .cptHover.cptHidden { display: none; }" +
".cptOutTyped {" +
" box-flex: 1; -moz-box-flex: 1; -webkit-box-flex: 1;" +
" font-weight: bold; color: #000; font-size: 120%;" +
"}" +
".cptRowOutput { padding-left: 10px; line-height: 1.2em; }" +
".cptRowOutput strong," +
".cptRowOutput b," +
".cptRowOutput th," +
".cptRowOutput h1," +
".cptRowOutput h2," +
".cptRowOutput h3 { color: #000; }" +
".cptRowOutput a { font-weight: bold; color: #666; text-decoration: none; }" +
".cptRowOutput a: hover { text-decoration: underline; cursor: pointer; }" +
".cptRowOutput input[type=password]," +
".cptRowOutput input[type=text]," +
".cptRowOutput textarea {" +
" color: #000; font-size: 120%;" +
" background: transparent; padding: 3px;" +
" border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;" +
"}" +
".cptRowOutput table," +
".cptRowOutput td," +
".cptRowOutput th { border: 0; padding: 0 2px; }" +
".cptRowOutput .right { text-align: right; }" +
"");
define("text!cockpit/ui/request_view.html", [], "" +
"<div class=cptRow>" +
" <!-- The div for the input (i.e. what was typed) -->" +
" <div class=\"cptRowIn\" save=\"${rowin}\"" +
" onclick=\"${copyToInput}\"" +
" ondblclick=\"${executeRequest}\">" +
"" +
" <!-- What the user actually typed -->" +
" <div class=\"cptGt\">> </div>" +
" <div class=\"cptOutTyped\">${request.typed}</div>" +
"" +
" <!-- The extra details that appear on hover -->" +
" <div class=cptHover save=\"${duration}\"></div>" +
" <img class=cptHover onclick=\"${hideOutput}\" save=\"${hide}\"" +
" alt=\"Hide command output\" _src=\"${imageUrl('images/minus.png')}\"/>" +
" <img class=\"cptHover cptHidden\" onclick=\"${showOutput}\" save=\"${show}\"" +
" alt=\"Show command output\" _src=\"${imageUrl('images/plus.png')}\"/>" +
" <img class=cptHover onclick=\"${remove}\"" +
" alt=\"Remove this command from the history\"" +
" _src=\"${imageUrl('images/closer.png')}\"/>" +
"" +
" </div>" +
"" +
" <!-- The div for the command output -->" +
" <div class=\"cptRowOut\" save=\"${rowout}\">" +
" <div class=\"cptRowOutput\" save=\"${output}\"></div>" +
" <img _src=\"${imageUrl('images/throbber.gif')}\" save=\"${throb}\"/>" +
" </div>" +
"</div>" +
"");
define("text!cockpit/ui/images/closer.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAj9JREFUeNp0ks+LUlEUx7/vV1o8Z8wUx3IEHcQmiBiQlomjRNCiZpEuEqF/oEUwq/6EhvoHggmRcJUQBM1CRJAW0aLIaGQimZJxJsWxyV/P9/R1zzWlFl04vPvOPZ9z7rnnK5imidmKRCIq+zxgdoPZ1T/ut8xeM3tcKpW6s1hhBkaj0Qj7bDebTX+324WmadxvsVigqipcLleN/d4rFoulORiLxTZY8ItOp8MBCpYkiYPj8Xjus9vtlORWoVB4KcTjcQc732dLpSRXvCZaAws6Q4WDdqsO52kNH+oCRFGEz+f7ydwBKRgMPmTXi49GI1x2D/DsznesB06ws2eDbI7w9HYN6bVjvGss4KAjwDAMq81mM2SW5Wa/3weBbz42UL9uYnVpiO2Nr9ANHSGXib2Wgm9tCYIggGKJEVkvlwgi5/FQRmTLxO6hgJVzI1x0T/fJrBtHJxPeL6tI/fsZLA6ot8lkQi8HRVbw94gkWYI5MaHrOjcCGSNRxZosy9y5cErDzn0Dqx7gcwO8WtBp4PndI35GMYqiUMUvBL5yOBz8yRfFNpbPmqgcCFh/IuHa1nR/YXGM8+oUpFhihEQiwcdRLpfVRqOBtWXWq34Gra6AXq8Hp2piZcmKT4cKnE4nwuHwdByVSmWQz+d32WCTlHG/qaHHREN9kgi0sYQfv0R4PB4EAgESQDKXy72fSy6VSnHJVatVf71eR7vd5n66mtfrRSgU4pLLZrOlf7RKK51Ok8g3/yPyR5lMZi7y3wIMAME4EigHWgKnAAAAAElFTkSuQmCC");
define("text!cockpit/ui/images/dot_clear.gif", [], "data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAEBMgA7");
define("text!cockpit/ui/images/minus.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAAXNSR0IArs4c6QAAAAZiS0dEANIA0gDS7KbF4AAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9kFGw4xMrIJw5EAAAHcSURBVCjPhZIxSxtxGMZ/976XhJA/RA5EAyJcFksnp64hjUPBoXRyCYLQTyD0UxScu0nFwalCQSgFCVk7dXAwUAiBDA2RO4W7yN1x9+9gcyhU+pteHt4H3pfncay1LOl0OgY4BN4Ar/7KP4BvwNFwOIyWu87S2O12O8DxfD73oygiSRIAarUaxhhWV1fHwMFgMBiWxl6v9y6Koi+3t7ckSUKtVkNVAcjzvNRWVlYwxry9vLz86uzs7HjAZDKZGGstjUaDfxHHMSLC5ubmHdB2VfVwNpuZ5clxHPMcRVFwc3PTXFtbO3RFZHexWJCmabnweAaoVqvlv4vFAhHZdVX1ZZqmOI5DURR8fz/lxbp9Yrz+7bD72SfPcwBU1XdF5N5aWy2KgqIoeBzPEnWVLMseYnAcRERdVR27rrsdxzGqyutP6898+GBsNBqo6i9XVS88z9sOggAR4X94noeqXoiIHPm+H9XrdYIgIAxDwjAkTVPCMESzBy3LMprNJr7v34nIkV5dXd2fn59fG2P2siwjSRIqlQrWWlSVJFcqlQqtVot2u40xZu/s7OxnWbl+v98BjkejkT+dTgmCoDxtY2ODra2tMXBweno6fNJVgP39fQN8eKbkH09OTsqS/wHFRdHPfTSfjwAAAABJRU5ErkJggg==");
define("text!cockpit/ui/images/pinaction.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGFVM9rE0EU/jZuqdAiCFprDrJ4kCJJWatoRdQ2/RFiawzbH7ZFkGQzSdZuNuvuJrWliOTi0SreRe2hB/+AHnrwZC9KhVpFKN6rKGKhFy3xzW5MtqXqwM5+8943731vdt8ADXLSNPWABOQNx1KiEWlsfEJq/IgAjqIJQTQlVdvsTiQGQYNz+Xvn2HoPgVtWw3v7d7J3rZrStpoHhP1A4Eea2Sqw7xdxClkSAog836Epx3QI3+PY8uyPOU55eMG1Dys9xFkifEA1Lc5/TbhTzSXTQINIOJT1cVI+nNeLlNcdB2luZsbIEL1PkKa7zO6rYqGcTvYOkL2d9H5Os94+wiHCCxmtP0a4jZ71jNU/4mHhpObEhj0cGDX0+GAVtxqp+DXCFF8QTSeiVHHZLg3xmK79VvJKgnCQOMpkYYBzWkhP10xu+LqHBX0m1xOv4ndWUeF5jxNn3tTd70XaAq8wDh0MGgyaDUhQEEUEYZiwUECGPBoxNLJyPyOrBhuTezJ1JGq7dGJEsUF7Ntw9t1Gk3Tz+KCJxlEO1CJL8Qf4qr8lP5Xn5y1yw2Fb3lK2bmrry4DvF5Zm5Gh7X08jjc01efJXUdpNXR5aseXq8muwaP+xXlzHmgjWPxHOw+/EtX5XMlymMFMXjVfPqS4R1WjE3359sfzs94i7PLrXWc62JizdWm5dn/WpI++6qvJPmVflPXvXx/GfNxGPiKTEmdornIYmXxS7xkthLqwviYG3HCJ2VhinSbZH6JNVgYJq89S9dP1t4vUZ/DPVRlBnM0lSJ93/CKmQ0nbkOb/qP28f8F+T3iuefKAIvbODImbptU3HvEKFlpW5zrgIXv9F98LZua6N+OPwEWDyrFq1SNZ8gvAEcdod6HugpmNOWls05Uocsn5O66cpiUsxQ20NSUtcl12VLFrOZVWLpdtiZ0x1uHKE5QvfEp0plk/qv8RGw/bBS+fmsUtl+ThrWgZf6b8C8/UXAeIuJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAClklEQVQ4EX1TXUhUQRQ+Z3Zmd+9uN1q2P3UpZaEwcikKekkqLKggKHJ96MHe9DmLkCDa9U198Id8kErICmIlRAN96UdE6QdBW/tBA5Uic7E0zN297L17p5mb1zYjD3eYc+d83zlnON8g5xzWNUSEdUBkHTJasRWySPP7fw3hfwkk2GoNsc0vOaJRHo1GV/GiMctkTIJRFlpZli8opK+htmf83gXeG63oteOtra0u25e7TYJIJELb26vYCACTgUe1lXV86BTn745l+MsyHqs53S/Aq4VEUa9Y6ko14eYY4u3AyM3HYwdKU35DZyblGR2+qq6W0X2Nnh07xynnVYpHORx/E1/GvvqaAZUayjMjdM2f/Lgr5E+fV93zR4u3zKCLughsZqKwAzAxaz6dPY6JgjLUF+eSP5OpjmAw2E8DvldHSvJMKPg08aRor1tc4BuALu6mOwGWdQC3mKIqRsC8mKd8wYfD78/earzSYzdMDW9QgKb0Is8CBY1mQXOiaXAHEpMDE5XTJqIq4EiyxUqKlpfkF0pyV1OTAoFAhmTmyCCoDsZNZvIkUjELQpipo0sQqYZAswZHwsEEE10M0pq2SSZY9HqNcDicJcNTpBvQJz40UbSOTh1B8bDpuY0w9Hb3kkn9lPAlBLfhfD39XTtX/blFJqiqrjbkTi63Hbofj2uL4GMsmzFgbDJ/vmMgv/lB4syJ0oXO7d3j++vio6GFsYmD6cHJreWc3/jRVVHhsOYvM8iZ36mtjPDBk/xDZE8CoHlbrlAssbTxDdDJvdb536L7I6S7Vy++6Gi4Xi9BsUthJRaLOYSPz4XALKI4j4iObd/e5UtDKUjZzYyYRyGAJv01Zj8kC5cbs5WY83hQnv0DzCXl+r8APElkq0RU6oMAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/pinin.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGFVM9rE0EU/jZuqdAiCFprDrJ4kCJJWatoRdQ2/RFiawzbH7ZFkGQzSdZuNuvuJrWliOTi0SreRe2hB/+AHnrwZC9KhVpFKN6rKGKhFy3xzW5MtqXqwM5+8943731vdt8ADXLSNPWABOQNx1KiEWlsfEJq/IgAjqIJQTQlVdvsTiQGQYNz+Xvn2HoPgVtWw3v7d7J3rZrStpoHhP1A4Eea2Sqw7xdxClkSAog836Epx3QI3+PY8uyPOU55eMG1Dys9xFkifEA1Lc5/TbhTzSXTQINIOJT1cVI+nNeLlNcdB2luZsbIEL1PkKa7zO6rYqGcTvYOkL2d9H5Os94+wiHCCxmtP0a4jZ71jNU/4mHhpObEhj0cGDX0+GAVtxqp+DXCFF8QTSeiVHHZLg3xmK79VvJKgnCQOMpkYYBzWkhP10xu+LqHBX0m1xOv4ndWUeF5jxNn3tTd70XaAq8wDh0MGgyaDUhQEEUEYZiwUECGPBoxNLJyPyOrBhuTezJ1JGq7dGJEsUF7Ntw9t1Gk3Tz+KCJxlEO1CJL8Qf4qr8lP5Xn5y1yw2Fb3lK2bmrry4DvF5Zm5Gh7X08jjc01efJXUdpNXR5aseXq8muwaP+xXlzHmgjWPxHOw+/EtX5XMlymMFMXjVfPqS4R1WjE3359sfzs94i7PLrXWc62JizdWm5dn/WpI++6qvJPmVflPXvXx/GfNxGPiKTEmdornIYmXxS7xkthLqwviYG3HCJ2VhinSbZH6JNVgYJq89S9dP1t4vUZ/DPVRlBnM0lSJ93/CKmQ0nbkOb/qP28f8F+T3iuefKAIvbODImbptU3HvEKFlpW5zrgIXv9F98LZua6N+OPwEWDyrFq1SNZ8gvAEcdod6HugpmNOWls05Uocsn5O66cpiUsxQ20NSUtcl12VLFrOZVWLpdtiZ0x1uHKE5QvfEp0plk/qv8RGw/bBS+fmsUtl+ThrWgZf6b8C8/UXAeIuJAAAACXBIWXMAAAsTAAALEwEAmpwYAAABZ0lEQVQ4Ea2TPUsDQRCGZ89Eo4FACkULEQs1CH4Uamfjn7GxEYJFIFXgChFsbPwzNnZioREkaiHBQtEiEEiMRm/dZ8OEGAxR4sBxx877Pju7M2estTJIxLrNuVwuMxQEx0ZkzcFHyRtjXt02559RtB2GYanTYzoryOfz+6l4Nbszf2niwffKmpGRo9sVW22mDgqFwp5C2gDMm+P32a3JB1N+n5JifUGeP9JeNxGryPLYjcwMP8rJ07Q9fZltQzyAstOJ2vVu5sKc1ZZkRBrOcKeb+HexPidvkpCN5JUcllZtpZFc5DgBWc5M2eysZuMuofMBSA4NWjx4PUCsXefMlI0QY3ewRg4NWi4ZTQsgrjYXema+e4VqtEMK6KXvu+4B9Bklt90vVKMeD2BI6DOt4rZ/Gk7WyKFBi4fNPIAJY0joM61SCCZ9tI1o0OIB8D+DBIkYaJRbCBH9mZgNt+bb++ufSSF/eX8BYcDeAzuQJVUAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/pinout.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGFVM9rE0EU/jZuqdAiCFprDrJ4kCJJWatoRdQ2/RFiawzbH7ZFkGQzSdZuNuvuJrWliOTi0SreRe2hB/+AHnrwZC9KhVpFKN6rKGKhFy3xzW5MtqXqwM5+8943731vdt8ADXLSNPWABOQNx1KiEWlsfEJq/IgAjqIJQTQlVdvsTiQGQYNz+Xvn2HoPgVtWw3v7d7J3rZrStpoHhP1A4Eea2Sqw7xdxClkSAog836Epx3QI3+PY8uyPOU55eMG1Dys9xFkifEA1Lc5/TbhTzSXTQINIOJT1cVI+nNeLlNcdB2luZsbIEL1PkKa7zO6rYqGcTvYOkL2d9H5Os94+wiHCCxmtP0a4jZ71jNU/4mHhpObEhj0cGDX0+GAVtxqp+DXCFF8QTSeiVHHZLg3xmK79VvJKgnCQOMpkYYBzWkhP10xu+LqHBX0m1xOv4ndWUeF5jxNn3tTd70XaAq8wDh0MGgyaDUhQEEUEYZiwUECGPBoxNLJyPyOrBhuTezJ1JGq7dGJEsUF7Ntw9t1Gk3Tz+KCJxlEO1CJL8Qf4qr8lP5Xn5y1yw2Fb3lK2bmrry4DvF5Zm5Gh7X08jjc01efJXUdpNXR5aseXq8muwaP+xXlzHmgjWPxHOw+/EtX5XMlymMFMXjVfPqS4R1WjE3359sfzs94i7PLrXWc62JizdWm5dn/WpI++6qvJPmVflPXvXx/GfNxGPiKTEmdornIYmXxS7xkthLqwviYG3HCJ2VhinSbZH6JNVgYJq89S9dP1t4vUZ/DPVRlBnM0lSJ93/CKmQ0nbkOb/qP28f8F+T3iuefKAIvbODImbptU3HvEKFlpW5zrgIXv9F98LZua6N+OPwEWDyrFq1SNZ8gvAEcdod6HugpmNOWls05Uocsn5O66cpiUsxQ20NSUtcl12VLFrOZVWLpdtiZ0x1uHKE5QvfEp0plk/qv8RGw/bBS+fmsUtl+ThrWgZf6b8C8/UXAeIuJAAAACXBIWXMAAAsTAAALEwEAmpwYAAACyUlEQVQ4EW1TXUgUURQ+Z3ZmnVV3QV2xJbVSEIowQbAfLQx8McLoYX2qjB58MRSkP3vZppceYhGxgrZaIughlYpE7CHFWiiKyj9II0qxWmwlNh1Xtp2f27mz7GDlZX7uuXO+73zfuXeQMQYIgAyALppgyBtse32stsw86txkHhATn+FbfPfzxnPB+vR3RMJYuTwW6bbB4a6WS5O3Yu2VlXIesDiAamiQNKVlVXfx5I0GJ7DY7p0/+erU4dgeMJIA31WNxZmAgibOreXDqF55sY4SFUURqbi+nkjgwTyAbHhLX8yOLsSM2QRA3JRAAgd4RGPbVhkKEp8qeJ7PFyW3fw++YHtC7CkaD0amqyqihSwlMQQ0wa07IjPVI/vbexreIUrVaQV2D4RMQ/o7m12Mdfx4H3PfB9FNzTR1U2cO0Bi45aV6xNvFBNaoIAfbSiwLlqi9/hR/R3Nrhua+Oqi9TEKiB02C7YXz+Pba4MTDrpbLiMAxNgmXb+HpwVkZdoIrkn9isW7nRw/TZYaagZArAWyhfqsSDL/c9aTx7JUjGZCtYExRqCzAwGblwr6aFQ84nTo6qZ7XCeCVQNckE/KSWolvoQnxeoFFgIh8G/nA+kBAxxuQO5m9eFrwLIGJHgcyM63VFMhRSgNVyJr7og8y1vbTQpH8DIEVgxuYuexw0QECIalq5FYgEmpkgoFYltU/lnrqDz5osirSFpF7lrHAFKSWHYfEs+mY/82UnAStyMlW8sUPsVIciTZgz3jV1ebg0CEOpgPF22s1z1YQYKSXPJ1hbAhR8T26WdLhkuVfAzPR+YO1Ox5n58SmCcF6e3uzAoHA77RkevJdWH/3+f2O9TGf3w3fWQ2Hw5F/13mcsWAT+vv6DK4kFApJ/d3d1k+kJtbCrmxXHS3n8ER6b3CQbAqaEHVra6sGxcXW4SovLx+empxapS//FfwD9kpMJjMMBBAAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/pins.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAQCAYAAABQrvyxAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGYklEQVRIDbVWe0yURxCf/R735o6DO0FBe0RFsaL4iLXGIKa2SY3P6JGa2GpjlJjUV9NosbU++tYUbEnaQIrVaKJBG7WiNFQFUWO1UUEsVg2CAgoeHHLewcH32O58cBdQsX9Y5+7LfrszOzO/2ZnZj1BKgTBiIwVGVvKd49OVVYunDlXn6wdBKh+ogXrv+DOz1melIb+3LM5fNv2XPYE5EHY+L3PJljN5zavHpJjsQNsA/JJEgyC2+WTjy3b0GfoJW8O4aoHtDwiHQrj5lw1LLyyb1bp5zAjJTus9klrVpdD6TqH2ngVO+0dsRJnp06cLIYU4fx7NnRI3bu7UIYOeJ/McnuY88q3k62gc0S4Dgf5qhICQtIXS2lqD7BhSduPk3YfyzXaANhBBJDxYdUqCywB2qS4RdyUuSkTF/VJxcbH5j8N7/75RuFrN3Zh8OS8zqf5m4UpPeenOyP42dbtBeuvVnCdkK1e4PfPouX03mo9se+c33M8wqDk5Ofqed8REUTicQhbySUxp9u3KlMSHTtrFU6Kyn03lz15PPpW25vsZeYSIKyiVURcqeZJOH9lTNZLfnxRjU/uwrjbEUBWsapcSO2Hq4k0VfZg9EzxdDNCEjDxgNqRDme9umz/btwlsHRIEePHgAf73RdnHZ6LTuIUBN7OBQ+c1Fdnp6cZ1BQUdeRuWZi97o3ktDQQkVeFFzqJARd1A5a0Vr7ta6Kp6TZjtZ+NTIOoKF6qDrL7e0QQIUCiqMMKk8Z1Q/SCSKvzocf2B6NEN0SQn/kTO6fKJ0zqjZUlQBSpJ0GjR77w0aoc1Pr6S5/kVJrNpakV5hR+LWKN4t7sLX+p0rx2vqSta64olIulUKUgCSXLWE1R4KPPSj+5vhm2hdDOG+CkQBmhhyyKq6SaFYWTn5bB3QJRNz54AuXKn8TJjhu0Wbv+wNEKQjVhnmKopjo4FxXmetCRnC4F7BhCiCUepqAepRh0TM/gjjzOOSK2NgWZPc05qampRWJHb7dbOffep2ednzLzgczlbrQA6gHYF9BYDh9GY+FjddMweHMscmMuep07gXlMQoqw9ALoYu5MJsak9QmJA2IvAgVmoCRciooyPujJtNCv1uHt3TmK9gegFKrG9kh6oXwZiIEAtBIjORGKNTWR/WeW8XVkbjuJepLAyloM8LmTN//njKZPbraATZaLjCHEww9Ei4FFiPg6Ja5gT6gxYgLgnRDHRQwJXbz2GOw0d4A3K4GXlUtMahJjYVxiYbrwOmxIS10bFnIBOSi6Tl9Jgs0zbOEX18wyEwgLPMrxD1Y4aCK8kmTpgYcpAF27Mzs42Hjx4kA8BICUlJfKArR7LcEvTB1xEC9AoEw9OPagWkVU/D1oesmK6U911zEczMVe01oZjiMggg6ux2Qk379qh4rYKet4GjrhhwEteBgBrH8BssoXEtbHzPpSBRRSpqlNpgAiUoxzHKxLRszoVuggIisxaDQWZqkQvQjAoax3NbDbLLGuUEABNGedXqSyLRupXgDT5JfAGZNLio9B0X8Uiwk4w77MDc1D4yejjWtykPS3DX01UDCY/GPQcVDe0QYT0CIxGFvUorfvBxZsRfVrUuWruMBAb/lXCUofoFNZfzGJtowXOX0vwUSFK4BgyMKm6P6s9wQUZld+jrYyMDC0iIQDaJdG4IyZQfL3RfbFcCBIlRgc+u3CjaTApuZ9KsANgG8PNzHlWWD3tCxd6kafNNiFp5HAalAkkJ0SCV2H3CgOD9Nc/FqrXuyb0Eocvfhq171p5eyuJ1omKJEP5rQGe/FOOnXtq335z8YmvYo9cHb2t8spIb3lVSseZW46FlGY/Sk9P50P2w20UlWJUkUHIushfc5PXGAzCo0PlD2pnpCYfCXga3lu+fPlevEhWrVrFyrN/Orfv87FOW9tlqb2Kc9pV8DzioMk3UNUbXM+8B/ATBr8C8CKdvGXWGD/9sqm3dkxtzA4McMjHMB8D2ftheYXo+qzt3pXvz8/PP/vk+v8537V+yYW87Zu+RZ1ZbrexoKAA/SBpaWn4+aL5w5zGk+/jW59JiMkESW5urpiVlWXENRb1H/Yf2I9txIxz5IdkX3TsraukpsbQjz6090yb4XsAvQoRE0YvJdamtIIbOnRoUVlZ2ftsLVQzIdEXHntsaZdimssVfCpFui109+BnWPsXaWLI/zactygAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/plus.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAAXNSR0IArs4c6QAAAAZiS0dEANIA0gDS7KbF4AAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9kFGw4yFTwuJTkAAAH7SURBVCjPdZKxa1NRFMZ/956XZMgFyyMlCZRA4hBx6lBcQ00GoYi4tEstFPwLAs7iLDi7FWuHThaUggihBDI5OWRoQAmBQFISQgvvpbwX3rsOaR4K+o2H8zvfOZxPWWtZqVarGaAJPAEe3ZW/A1+Bd+1221v1qhW4vb1dA44mk0nZ8zyCIAAgk8lgjGF9fb0PHF5cXLQTsF6vP/c879P19TVBEJDJZBARAKIoSmpra2sYY561Wq3PqtFouMBgMBgYay3ZbJZ/yfd9tNaUSqUboOKISPPq6sqsVvZ9H4AvL34B8PTj/QSO45jpdHovn883Ha31znw+JwzDpCEMQx4UloM8zyOdTif3zudztNY7jog8DMMQpRRxHPPt5TCBAEZvxlyOFTsfykRRBICIlB2t9a21Nh3HMXEc8+d7VhJHWCwWyzcohdZaHBHpO46z6fs+IsLj94XECaD4unCHL8FsNouI/HRE5Nx13c3ZbIbWOnG5HKtl+53TSq7rIiLnand31wUGnU7HjEYjlFLJZN/3yRnL1FMYY8jlcmxtbd0AFel2u7dnZ2eXxpi9xWJBEASkUimstYgIQSSkUimKxSKVSgVjzN7p6emPJHL7+/s14KjX65WHwyGz2SxZbWNjg2q12gcOT05O2n9lFeDg4MAAr/4T8rfHx8dJyH8DvvbYGzKvWukAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/throbber.gif", [], "data:image/gif;base64,R0lGODlh3AATAPQAAP///wAAAL6+vqamppycnLi4uLKyssjIyNjY2MTExNTU1Nzc3ODg4OTk5LCwsLy8vOjo6Ozs7MrKyvLy8vT09M7Ozvb29sbGxtDQ0O7u7tbW1sLCwqqqqvj4+KCgoJaWliH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAA3AATAAAF/yAgjmRpnmiqrmzrvnAsz3Rt33iu73zv/8CgcEgECAaEpHLJbDqf0Kh0Sq1ar9isdjoQtAQFg8PwKIMHnLF63N2438f0mv1I2O8buXjvaOPtaHx7fn96goR4hmuId4qDdX95c4+RG4GCBoyAjpmQhZN0YGYFXitdZBIVGAoKoq4CG6Qaswi1CBtkcG6ytrYJubq8vbfAcMK9v7q7D8O1ycrHvsW6zcTKsczNz8HZw9vG3cjTsMIYqQgDLAQGCQoLDA0QCwUHqfYSFw/xEPz88/X38Onr14+Bp4ADCco7eC8hQYMAEe57yNCew4IVBU7EGNDiRn8Z831cGLHhSIgdE/9chIeBgDoB7gjaWUWTlYAFE3LqzDCTlc9WOHfm7PkTqNCh54rePDqB6M+lR536hCpUqs2gVZM+xbrTqtGoWqdy1emValeXKwgcWABB5y1acFNZmEvXwoJ2cGfJrTv3bl69Ffj2xZt3L1+/fw3XRVw4sGDGcR0fJhxZsF3KtBTThZxZ8mLMgC3fRatCLYMIFCzwLEprg84OsDus/tvqdezZf13Hvr2B9Szdu2X3pg18N+68xXn7rh1c+PLksI/Dhe6cuO3ow3NfV92bdArTqC2Ebc3A8vjf5QWf15Bg7Nz17c2fj69+fnq+8N2Lty+fuP78/eV2X13neIcCeBRwxorbZrAxAJoCDHbgoG8RTshahQ9iSKEEzUmYIYfNWViUhheCGJyIP5E4oom7WWjgCeBBAJNv1DVV01MZdJhhjdkplWNzO/5oXI846njjVEIqR2OS2B1pE5PVscajkxhMycqLJgxQCwT40PjfAV4GqNSXYdZXJn5gSkmmmmJu1aZYb14V51do+pTOCmA00AqVB4hG5IJ9PvYnhIFOxmdqhpaI6GeHCtpooisuutmg+Eg62KOMKuqoTaXgicQWoIYq6qiklmoqFV0UoeqqrLbq6quwxirrrLTWauutJ4QAACH5BAkKAAAALAAAAADcABMAAAX/ICCOZGmeaKqubOu+cCzPdG3feK7vfO//wKBwSAQIBoSkcslsOp/QqHRKrVqv2Kx2OhC0BAXHx/EoCzboAcdhcLDdgwJ6nua03YZ8PMFPoBMca215eg98G36IgYNvDgOGh4lqjHd7fXOTjYV9nItvhJaIfYF4jXuIf4CCbHmOBZySdoOtj5eja59wBmYFXitdHhwSFRgKxhobBgUPAmdoyxoI0tPJaM5+u9PaCQZzZ9gP2tPcdM7L4tLVznPn6OQb18nh6NV0fu3i5OvP8/nd1qjwaasHcIPAcf/gBSyAAMMwBANYEAhWYQGDBhAyLihwYJiEjx8fYMxIcsGDAxVA/yYIOZIkBAaGPIK8INJlRpgrPeasaRPmx5QgJfB0abLjz50tSeIM+pFmUo0nQQIV+vRlTJUSnNq0KlXCSq09ozIFexEBAYkeNiwgOaEtn2LFpGEQsKCtXbcSjOmVlqDuhAx3+eg1Jo3u37sZBA9GoMAw4MB5FyMwfLht4sh7G/utPGHlYAV8Nz9OnOBz4c2VFWem/Pivar0aKCP2LFn2XwhnVxBwsPbuBAQbEGiIFg1BggoWkidva5z4cL7IlStfkED48OIYoiufYIH68+cKPkqfnsB58ePjmZd3Dj199/XE20tv6/27XO3S6z9nPCz9BP3FISDefL/Bt192/uWmAv8BFzAQAQUWWFaaBgqA11hbHWTIXWIVXifNhRlq6FqF1sm1QQYhdiAhbNEYc2KKK1pXnAIvhrjhBh0KxxiINlqQAY4UXjdcjSJyeAx2G2BYJJD7NZQkjCPKuCORKnbAIXsuKhlhBxEomAIBBzgIYXIfHfmhAAyMR2ZkHk62gJoWlNlhi33ZJZ2cQiKTJoG05Wjcm3xith9dcOK5X51tLRenoHTuud2iMnaolp3KGXrdBo7eKYF5p/mXgJcogClmcgzAR5gCKymXYqlCgmacdhp2UCqL96mq4nuDBTmgBasaCFp4sHaQHHUsGvNRiiGyep1exyIra2mS7dprrtA5++z/Z8ZKYGuGsy6GqgTIDvupRGE+6CO0x3xI5Y2mOTkBjD4ySeGU79o44mcaSEClhglgsKyJ9S5ZTGY0Bnzrj+3SiKK9Rh5zjAALCywZBk/ayCWO3hYM5Y8Dn6qxxRFsgAGoJwwgDQRtYXAAragyQOmaLKNZKGaEuUlpyiub+ad/KtPqpntypvvnzR30DBtjMhNodK6Eqrl0zU0/GjTUgG43wdN6Ra2pAhGtAAZGE5Ta8TH6wknd2IytNKaiZ+Or79oR/tcvthIcAPe7DGAs9Edwk6r3qWoTaNzY2fb9HuHh2S343Hs1VIHhYtOt+Hh551rh24vP5YvXSGzh+eeghy76GuikU9FFEainrvrqrLfu+uuwxy777LTXfkIIACH5BAkKAAAALAAAAADcABMAAAX/ICCOZGmeaKqubOu+cCzPdG3feK7vfO//wKBwSAQIBoSkcslsOp/QqHRKrVqv2Kx2OhC0BAWHB2l4CDZo9IDjcBja7UEhTV+3DXi3PJFA8xMcbHiDBgMPG31pgHBvg4Z9iYiBjYx7kWocb26OD398mI2EhoiegJlud4UFiZ5sm6Kdn2mBr5t7pJ9rlG0cHg5gXitdaxwFGArIGgoaGwYCZ3QFDwjU1AoIzdCQzdPV1c0bZ9vS3tUJBmjQaGXl1OB0feze1+faiBvk8wjnimn55e/o4OtWjp+4NPIKogsXjaA3g/fiGZBQAcEAFgQGOChgYEEDCCBBLihwQILJkxIe/3wMKfJBSQkJYJpUyRIkgwcVUJq8QLPmTYoyY6ZcyfJmTp08iYZc8MBkhZgxk9aEcPOlzp5FmwI9KdWn1qASurJkClRoWKwhq6IUqpJBAwQEMBYroAHkhLt3+RyzhgCDgAV48Wbgg+waAnoLMgTOm6DwQ8CLBzdGdvjw38V5JTg2lzhyTMeUEwBWHPgzZc4TSOM1bZia6LuqJxCmnOxv7NSsl1mGHHiw5tOuIWeAEHcFATwJME/ApgFBc3MVLEgPvE+Ddb4JokufPmFBAuvPXWu3MIF89wTOmxvOvp179evQtwf2nr6aApPyzVd3jn089e/8xdfeXe/xdZ9/d1ngHf98lbHH3V0LMrgPgsWpcFwBEFBgHmyNXWeYAgLc1UF5sG2wTHjIhNjBiIKZCN81GGyQwYq9uajeMiBOQGOLJ1KjTI40kmfBYNfc2NcGIpI4pI0vyrhjiT1WFqOOLEIZnjVOVpmajYfBiCSNLGbA5YdOkjdihSkQwIEEEWg4nQUmvYhYe+bFKaFodN5lp3rKvJYfnBKAJ+gGDMi3mmbwWYfng7IheuWihu5p32XcSWdSj+stkF95dp64jJ+RBipocHkCCp6PCiRQ6INookCAAwy0yd2CtNET3Yo7RvihBjFZAOaKDHT43DL4BQnsZMo8xx6uI1oQrHXXhHZrB28G62n/YSYxi+uzP2IrgbbHbiaer7hCiOxDFWhrbmGnLVuus5NFexhFuHLX6gkEECorlLpZo0CWJG4pLjIACykmBsp0eSSVeC15TDJeUhlkowlL+SWLNJpW2WEF87urXzNWSZ6JOEb7b8g1brZMjCg3ezBtWKKc4MvyEtwybPeaMAA1ECRoAQYHYLpbeYYCLfQ+mtL5c9CnfQpYpUtHOSejEgT9ogZ/GSqd0f2m+LR5WzOtHqlQX1pYwpC+WbXKqSYtpJ5Mt4a01lGzS3akF60AxkcTaLgAyRBPWCoDgHfJqwRuBuzdw/1ml3iCwTIeLUWJN0v4McMe7uasCTxseNWPSxc5RbvIgD7geZLbGrqCG3jepUmbbze63Y6fvjiOylbwOITPfIHEFsAHL/zwxBdvPBVdFKH88sw37/zz0Ecv/fTUV2/99SeEAAAh+QQJCgAAACwAAAAA3AATAAAF/yAgjmRpnmiqrmzrvnAsz3Rt33iu73zv/8CgcEgECAaEpHLJbDqf0Kh0Sq1ar9isdjoQtAQFh2cw8BQEm3T6yHEYHHD4oKCuD9qGvNsxT6QTgAkcHHmFeX11fm17hXwPG35qgnhxbwMPkXaLhgZ9gWp3bpyegX4DcG+inY+Qn6eclpiZkHh6epetgLSUcBxlD2csXXdvBQrHGgoaGhsGaIkFDwjTCArTzX+QadHU3c1ofpHc3dcGG89/4+TYktvS1NYI7OHu3fEJ5tpqBu/k+HX7+nXDB06SuoHm0KXhR65cQT8P3FRAMIAFgVMPwDCAwLHjggIHJIgceeFBg44eC/+ITCCBZYKSJ1FCWPBgpE2YMmc+qNCypwScMmnaXAkUJYOaFVyKLOqx5tCXJnMelcBzJNSYKIX2ZPkzqsyjPLku9Zr1QciVErYxaICAgEUOBRJIgzChbt0MLOPFwyBggV27eCUcmxZvg9+/dfPGo5bg8N/Ag61ZM4w4seDF1fpWhizZmoa+GSortgcaMWd/fkP/HY0MgWbTipVV++wY8GhvqSG4XUEgoYTKE+Qh0OCvggULiBckWEZ4Ggbjx5HXVc58IPQJ0idQJ66XanTpFraTe348+XLizRNcz658eHMN3rNPT+C+G/nodqk3t6a+fN3j+u0Xn3nVTQPfdRPspkL/b+dEIN8EeMm2GAYbTNABdrbJ1hyFFv5lQYTodSZABhc+loCEyhxTYYkZopdMMiNeiBxyIFajV4wYHpfBBspUl8yKHu6ooV5APsZjQxyyeNeJ3N1IYod38cgdPBUid6GCKfRWgAYU4IccSyHew8B3doGJHmMLkGkZcynKk2Z50Ym0zJzLbDCmfBbI6eIyCdyJmJmoqZmnBAXy9+Z/yOlZDZpwYihnj7IZpuYEevrYJ5mJEuqiof4l+NYDEXQpXQcMnNjZNDx1oGqJ4S2nF3EsqWrhqqVWl6JIslpAK5MaIqDeqjJq56qN1aTaQaPbHTPYr8Be6Gsyyh6Da7OkmmqP/7GyztdrNVQBm5+pgw3X7aoYKhfZosb6hyUKBHCgQKij1rghkOAJuZg1SeYIIY+nIpDvf/sqm4yNG5CY64f87qdAwSXKGqFkhPH1ZHb2EgYtw3bpKGVkPz5pJAav+gukjB1UHE/HLNJobWcSX8jiuicMMBFd2OmKwQFs2tjXpDfnPE1j30V3c7iRHlrzBD2HONzODyZtsQJMI4r0AUNaE3XNHQw95c9GC001MpIxDacFQ+ulTNTZlU3O1eWVHa6vb/pnQUUrgHHSBKIuwG+bCPyEqbAg25gMVV1iOB/IGh5YOKLKIQ6xBAcUHmzjIcIqgajZ+Ro42DcvXl7j0U4WOUd+2IGu7DWjI1pt4DYq8BPm0entuGSQY/4tBi9Ss0HqfwngBQtHbCH88MQXb/zxyFfRRRHMN+/889BHL/301Fdv/fXYZ39CCAAh+QQJCgAAACwAAAAA3AATAAAF/yAgjmRpnmiqrmzrvnAsz3Rt33iu73zv/8CgcEgECAaEpHLJbDqf0Kh0Sq1ar9isdjoQtAQFh2fAKXsKm7R6Q+Y43vABep0mGwwOPH7w2CT+gHZ3d3lyagl+CQNvg4yGh36LcHoGfHR/ZYOElQ9/a4ocmoRygIiRk5p8pYmZjXePaYBujHoOqp5qZHBlHAUFXitddg8PBg8KGsgayxvGkAkFDwgICtPTzX2mftHW3QnOpojG3dbYkNjk1waxsdDS1N7ga9zw1t/aifTk35fu6Qj3numL14fOuHTNECHqU4DDgQEsCCwidiHBAwYQMmpcUOCAhI8gJVzUuLGThAQnP/9abEAyI4MCIVOKZNnyJUqUJxNcGNlywYOQgHZirGkSJ8gHNEky+AkS58qWEJYC/bMzacmbQHkqNdlUJ1KoSz2i9COhmQYCEXtVrCBgwYS3cCf8qTcNQ9u4cFFOq2bPLV65Cf7dxZthbjW+CgbjnWtNgWPFcAsHdoxgWWK/iyV045sAc2S96SDn1exYw17REwpLQEYt2eW/qtPZRQAB7QoC61RW+GsBwYZ/CXb/XRCYLsAKFizEtUAc+G7lcZsjroscOvTmsoUvx15PwccJ0N8yL17N9PG/E7jv9S4hOV7pdIPDdZ+ePDzv2qMXn2b5+wTbKuAWnF3oZbABZY0lVmD/ApQd9thybxno2GGuCVDggaUpoyBsB1bGGgIYbJCBcuFJiOAyGohIInQSmmdeiBnMF2GHfNUlIoc1rncjYRjW6NgGf3VQGILWwNjBfxEZcAFbC7gHXQcfUYOYdwzQNxo5yUhQZXhvRYlMeVSuSOJHKJa5AQMQThBlZWZ6Bp4Fa1qzTAJbijcBlJrtxeaZ4lnnpZwpukWieGQmYx5ATXIplwTL8DdNZ07CtWYybNIJF4Ap4NZHe0920AEDk035kafieQrqXofK5ympn5JHKYjPrfoWcR8WWQGp4Ul32KPVgXdnqxM6OKqspjIYrGPDrlrsZtRIcOuR86nHFwbPvmes/6PH4frrqbvySh+mKGhaAARPzjjdhCramdoGGOhp44i+zogBkSDuWC5KlE4r4pHJkarXrj++Raq5iLmWLlxHBteavjG+6amJrUkJJI4Ro5sBv9AaOK+jAau77sbH7nspCwNIYIACffL7J4JtWQnen421nNzMcB6AqpRa9klonmBSiR4GNi+cJZpvwgX0ejj71W9yR+eIgaVvQgf0l/A8nWjUFhwtZYWC4hVnkZ3p/PJqNQ5NnwUQrQCGBBBMQIGTtL7abK+5JjAv1fi9bS0GLlJHgdjEgYzzARTwC1fgEWdJuKKBZzj331Y23qB3i9v5aY/rSUC4w7PaLeWXmr9NszMFoN79eeiM232o33EJAIzaSGwh++y012777bhT0UURvPfu++/ABy/88MQXb/zxyCd/QggAIfkECQoAAAAsAAAAANwAEwAABf8gII5kaZ5oqq5s675wLM90bd94ru987//AoHBIBAgGhKRyyWw6n9CodEqtWq/YrHY6ELQEBY5nwCk7xIWNer0hO95wziC9Ttg5b4ND/+Y87IBqZAaEe29zGwmJigmDfHoGiImTjXiQhJEPdYyWhXwDmpuVmHwOoHZqjI6kZ3+MqhyemJKAdo6Ge3OKbEd4ZRwFBV4rc4MPrgYPChrMzAgbyZSJBcoI1tfQoYsJydfe2amT3d7W0OGp1OTl0YtqyQrq0Lt11PDk3KGoG+nxBpvTD9QhwCctm0BzbOyMIwdOUwEDEgawIOCB2oMLgB4wgMCx44IHBySIHClBY0ePfyT/JCB5weRJCAwejFw58kGDlzBTqqTZcuPLmCIBiWx58+VHmiRLFj0JVCVLl0xl7qSZwCbOo0lFWv0pdefQrVFDJtr5gMBEYBgxqBWwYILbtxPsqMPAFu7blfa81bUbN4HAvXAzyLWnoDBguHIRFF6m4LBbwQngMYPXuC3fldbyPrMcGLM3w5wRS1iWWUNlvnElKDZtz/EEwaqvYahQoexEfyILi4RrYYKFZwJ3810QWZ2ECrx9Ew+O3K6F5Yq9zXbb+y30a7olJJ+wnLC16W97Py+uwdtx1NcLWzs/3G9e07stVPc9kHJ0BcLtQp+c3ewKAgYkUAFpCaAmmHqKLSYA/18WHEiZPRhsQF1nlLFWmIR8ZbDBYs0YZuCGpGXWmG92aWiPMwhEOOEEHXRwIALlwXjhio+BeE15IzpnInaLbZBBhhti9x2GbnVQo2Y9ZuCfCgBeMCB+DJDIolt4iVhOaNSJdCOBUfIlkmkyMpPAAvKJ59aXzTQzJo0WoJnmQF36Jp6W1qC4gWW9GZladCiyJd+KnsHImgRRVjfnaDEKuiZvbcYWo5htzefbl5LFWNeSKQAo1QXasdhiiwwUl2B21H3aQaghXnPcp1NagCqYslXAqnV+zYWcpNwVp9l5eepJnHqL4SdBi56CGlmw2Zn6aaiZjZqfb8Y2m+Cz1O0n3f+tnvrGbF6kToApCgAWoNWPeh754JA0vmajiAr4iOuOW7abQXVGNriBWoRdOK8FxNqLwX3oluubhv8yluRbegqGb536ykesuoXhyJqPQJIGbLvQhkcwjKs1zBvBwSZIsbcsDCCBAAf4ya+UEhyQoIiEJtfoZ7oxUOafE2BwgMWMqUydfC1LVtiArk0QtGkWEopzlqM9aJrKHfw5c6wKjFkmXDrbhwFockodtMGFLWpXy9JdiXN1ZDNszV4WSLQCGBKoQYHUyonqrHa4ErewAgMmcAAF7f2baIoVzC2p3gUvJtLcvIWqloy6/R04mIpLwDhciI8qLOB5yud44pHPLbA83hFDWPjNbuk9KnySN57Av+TMBvgEAgzzNhJb5K777rz37vvvVHRRxPDEF2/88cgnr/zyzDfv/PPQnxACACH5BAkKAAAALAAAAADcABMAAAX/ICCOZGmeaKqubOu+cCzPdG3feK7vfO//wKBwSAQIBoSkcslsOp/QqHRKrVqv2Kx2OhC0BIUCwcMpO84OT2HDbm8GHLQjnn6wE3g83SA3DB55G3llfHxnfnZ4gglvew6Gf4ySgmYGlpCJknochWiId3kJcZZyDn93i6KPl4eniopwq6SIoZKxhpenbhtHZRxhXisDopwPgHkGDxrLGgjLG8mC0gkFDwjX2AgJ0bXJ2djbgNJsAtbfCNB2oOnn6MmKbeXt226K1fMGi6j359D69ua+QZskjd+3cOvY9XNgp4ABCQNYEDBl7EIeCQkeMIDAseOCBwckiBSZ4ILGjh4B/40kaXIjSggMHmBcifHky5gYE6zM2OAlzGM6Z5rs+fIjTZ0tfcYMSlLCUJ8fL47kCVXmTjwPiKJkUCDnyqc3CxzQmYeAxAEGLGJYiwCDgAUT4sqdgOebArdw507IUNfuW71xdZ7DC5iuhGsKErf9CxhPYgUaEhPWyzfBMgUIJDPW6zhb5M1y+R5GjFkBaLmCM0dOfHqvztXYJnMejaFCBQlmVxAYsEGkYnQV4lqYMNyCtnYSggNekAC58uJxmTufW5w55mwKkg+nLp105uTC53a/nhg88fMTmDfDVl65Xum/IZt/3/zaag3a5W63nll1dvfiWbaaZLmpQIABCVQA2f9lAhTG112PQWYadXE9+FtmEwKWwQYQJrZagxomsOCAGVImInsSbpCBhhwug6KKcXXQQYUcYuDMggrASFmNzjjzzIrh7cUhhhHqONeGpSEW2QYxHsmjhxpgUGAKB16g4IIbMNCkXMlhaJ8GWVJo2I3NyKclYF1GxgyYDEAnXHJrMpNAm/rFBSczPiYAlwXF8ZnmesvoOdyMbx7m4o0S5LWdn4bex2Z4xYmEzaEb5EUcnxbA+WWglqIn6aHPTInCgVbdlZyMqMrIQHMRSiaBBakS1903p04w434n0loBoQFOt1yu2YAnY68RXiNsqh2s2qqxuyKb7Imtmgcrqsp6h8D/fMSpapldx55nwayK/SfqCQd2hcFdAgDp5GMvqhvakF4mZuS710WGIYy30khekRkMu92GNu6bo7r/ttjqwLaua5+HOdrKq5Cl3dcwi+xKiLBwwwom4b0E6xvuYyqOa8IAEghwQAV45VvovpkxBl2mo0W7AKbCZXoAhgMmWnOkEqx2JX5nUufbgJHpXCfMOGu2QAd8eitpW1eaNrNeMGN27mNz0swziYnpSbXN19gYtstzfXrdYjNHtAIYGFVwwAEvR1dfxdjKxVzAP0twAAW/ir2w3nzTd3W4yQWO3t0DfleB4XYnEHCEhffdKgaA29p0eo4fHLng9qoG+OVyXz0gMeWGY7qq3xhiRIEAwayNxBawxy777LTXbjsVXRSh++689+7778AHL/zwxBdv/PEnhAAAIfkECQoAAAAsAAAAANwAEwAABf8gII5kaZ5oqq5s675wLM90bd94ru987//AoHBIBAgGhKRyyWw6n9CodEqtWq/YrHY6ELQEhYLD4BlwHGg0ubBpuzdm9Dk9eCTu+MTZkDb4PXYbeIIcHHxqf4F3gnqGY2kOdQmCjHCGfpCSjHhmh2N+knmEkJmKg3uHfgaaeY2qn6t2i4t7sKAPbwIJD2VhXisDCQZgDrKDBQ8aGgjKyhvDlJMJyAjV1gjCunkP1NfVwpRtk93e2ZVt5NfCk27jD97f0LPP7/Dr4pTp1veLgvrx7AL+Q/BM25uBegoYkDCABYFhEobhkUBRwoMGEDJqXPDgQMUEFC9c1LjxQUUJICX/iMRIEgIDkycrjmzJMSXFlDNJvkwJsmdOjQwKfDz5M+PLoSGLQqgZU6XSoB/voHxawGbFlS2XGktAwKEADB0xiEWAodqGBRPSqp1wx5qCamDRrp2Qoa3bagLkzrULF4GCvHPTglRAmKxZvWsHayBcliDitHUlvGWM97FgCdYWVw4c2e/kw4HZJlCwmDBhwHPrjraGYTHqtaoxVKggoesKAgd2SX5rbUMFCxOAC8cGDwHFwBYWJCgu4XfwtcqZV0grPHj0u2SnqwU+IXph3rK5b1fOu7Bx5+K7L6/2/Xhg8uyXnQ8dvfRiDe7TwyfNuzlybKYpgIFtKhAgwEKkKcOf/wChZbBBgMucRh1so5XH3wbI1WXafRJy9iCErmX4IWHNaIAhZ6uxBxeGHXQA24P3yYfBBhmgSBozESpwongWOBhggn/N1aKG8a1YY2oVAklgCgQUUwGJ8iXAgItrWUARbwpqIOWEal0ZoYJbzmWlZCWSlsAC6VkwZonNbMAAl5cpg+NiZwpnJ0Xylegmlc+tWY1mjnGnZnB4QukMA9UJRxGOf5r4ppqDjjmnfKilh2ejGiyJAgF1XNmYbC2GmhZ5AcJVgajcXecNqM9Rx8B6bingnlotviqdkB3YCg+rtOaapFsUhSrsq6axJ6sEwoZK7I/HWpCsr57FBxJ1w8LqV/81zbkoXK3LfVeNpic0KRQG4NHoIW/XEmZuaiN6tti62/moWbk18uhjqerWS6GFpe2YVotskVssWfBOAHACrZHoWcGQwQhlvmsdXBZ/F9YLMF2jzUuYBP4a7CLCnoEHrgkDSCDAARUILAGaVVqAwQHR8pZXomm9/ONhgjrbgc2lyYxmpIRK9uSNjrXs8gEbTrYyl2ryTJmsLCdKkWzFQl1lWlOXGmifal6p9VnbQfpyY2SZyXKVV7JmZkMrgIFSyrIeUJ2r7YKnXdivUg1kAgdQ8B7IzJjGsd9zKSdwyBL03WpwDGxwuOASEP5vriO2F3nLjQdIrpaRDxqcBdgIHGA74pKrZXiR2ZWuZt49m+o3pKMC3p4Av7SNxBa456777rz37jsVXRQh/PDEF2/88cgnr/zyzDfv/PMnhAAAIfkECQoAAAAsAAAAANwAEwAABf8gII5kaZ5oqq5s675wLM90bd94ru987//AoHBIBAgGhKRyyWw6n9CodEqtWq/YrHY6ELQEhYLDUPAMHGi0weEpbN7wI8cxTzsGj4R+n+DUxwaBeBt7hH1/gYIPhox+Y3Z3iwmGk36BkIN8egOIl3h8hBuOkAaZhQlna4BrpnyWa4mleZOFjrGKcXoFA2ReKwMJBgISDw6abwUPGggazc0bBqG0G8kI1tcIwZp51djW2nC03d7BjG8J49jl4cgP3t/RetLp1+vT6O7v5fKhAvnk0UKFogeP3zmCCIoZkDCABQFhChQYuKBHgkUJkxpA2MhxQYEDFhNcvPBAI8eNCx7/gMQYckPJkxsZPLhIM8FLmDJrYiRp8mTKkCwT8IQJwSPQkENhpgQpEunNkzlpWkwKdSbGihKocowqVSvKWQkIOBSgQOYFDBgQpI0oYMGEt3AzTLKm4BqGtnDjirxW95vbvG/nWlub8G9euRsiqqWLF/AEkRoiprX2wLDeDQgkW9PQGLDgyNc665WguK8C0XAnRY6oGPUEuRLsgk5g+a3cCxUqSBC7gsCBBXcVq6swwULx4hayvctGPK8FCwsSLE9A3Hje6NOrHzeOnW695sffRi/9HfDz7sIVSNB+XXrmugo0rHcM3X388o6jr44ceb51uNjF1xcC8zk3wXiS8aYC/wESaLABBs7ch0ECjr2WAGvLsLZBeHqVFl9kGxooV0T81TVhBo6NiOEyJ4p4IYnNRBQiYCN6x4wCG3ZAY2If8jXjYRcyk2FmG/5nXAY8wqhWAii+1YGOSGLoY4VRfqiAgikwmIeS1gjAgHkWYLQZf9m49V9gDWYWY5nmTYCRM2TS5pxxb8IZGV5nhplmhJyZadxzbrpnZ2d/6rnZgHIid5xIMDaDgJfbLdrgMkKW+Rygz1kEZz1mehabkBpgiQIByVikwGTqVfDkk2/Vxxqiqur4X3fksHccre8xlxerDLiHjQIVUAgXr77yFeyuOvYqXGbMrbrqBMqaFpFFzhL7qv9i1FX7ZLR0LUNdcc4e6Cus263KbV+inkAAHhJg0BeITR6WmHcaxhvXg/AJiKO9R77ILF1FwmVdAu6WBu+ZFua72mkZWMfqBElKu0G8rFZ5n4ATp5jkmvsOq+Nj7u63ZMMPv4bveyYy6fDH+C6brgnACHBABQUrkGirz2FwAHnM4Mmhzq9yijOrOi/MKabH6VwBiYwZdukEQAvILKTWXVq0ZvH5/CfUM7M29Zetthp1eht0eqkFYw8IKXKA6mzXfTeH7fZg9zW0AhgY0TwthUa6Ch9dBeIsbsFrYkRBfgTfiG0FhwMWnbsoq3cABUYOnu/ejU/A6uNeT8u4wMb1WnBCyJJTLjjnr8o3OeJrUcpc5oCiPqAEkz8tXuLkPeDL3Uhs4fvvwAcv/PDEU9FFEcgnr/zyzDfv/PPQRy/99NRXf0IIACH5BAkKAAAALAAAAADcABMAAAX/ICCOZGmeaKqubOu+cCzPdG3feK7vfO//wKBwSAQIBoSkcslsOp/QqHRKrVqv2Kx2OhC0BIWCw/AoDziOtCHt8BQ28PjmzK57Hom8fo42+P8DeAkbeYQcfX9+gYOFg4d1bIGEjQmPbICClI9/YwaLjHAJdJeKmZOViGtpn3qOqZineoeJgG8CeWUbBV4rAwkGAhIVGL97hGACGsrKCAgbBoTRhLvN1c3PepnU1s2/oZO6AtzdBoPf4eMI3tIJyOnF0YwFD+nY8e3z7+Xfefnj9uz8cVsXCh89axgk7BrAggAwBQsYIChwQILFixIeNIDAseOCBwcSXMy2sSPHjxJE/6a0eEGjSY4MQGK86PIlypUJEmYsaTKmyJ8JW/Ls6HMkzaEn8YwMWtPkx4pGd76E4DMPRqFTY860OGhogwYagBFoKEABA46DEGBAoEBB0AUT4sqdIFKBNbcC4M6dkEEk22oYFOTdG9fvWrtsBxM23MytYL17666t9phwXwlum2lIDHmuSA2IGyuOLOHv38qLMbdFjHruZbWgRXeOe1nC2BUEDiyAMMHZuwoTLAQX3nvDOAUW5Vogru434d4JnAsnPmFB9NBshQXfa9104+Rxl8e13rZxN+CEydtVsFkd+vDjE7C/q52wOvb4s7+faz025frbxefWbSoQIAEDEUCwgf9j7bUlwHN9ZVaegxDK1xYzFMJH24L5saXABhlYxiEzHoKoIV8LYqAMaw9aZqFmJUK4YHuNfRjiXhmk+NcyJgaIolvM8BhiBx3IleN8lH1IWAcRgkZgCgYiaBGJojGgHHFTgtagAFYSZhF7/qnTpY+faVlNAnqJN0EHWa6ozAZjBtgmmBokwMB01LW5jAZwbqfmlNips4B4eOqJgDJ2+imXRZpthuigeC6XZTWIxilXmRo8iYKBCwiWmWkJVEAkfB0w8KI1IvlIpKnOkVpqdB5+h96o8d3lFnijrgprjbfGRSt0lH0nAZG5vsprWxYRW6Suq4UWqrLEsspWg8Io6yv/q6EhK0Fw0GLbjKYn5CZYBYht1laPrnEY67kyrhYbuyceiR28Pso7bYwiXjihjWsWuWF5p/H765HmNoiur3RJsGKNG/jq748XMrwmjhwCfO6QD9v7LQsDxPTAMKsFpthyJCdkmgYiw0VdXF/Om9dyv7YMWGXTLYpZg5wNR11C78oW3p8HSGgul4qyrJppgllJHJZHn0Y0yUwDXCXUNquFZNLKyYXBAVZvxtAKYIQEsmPgDacr0tltO1y/DMwYpkgUpJfTasLGzd3cdCN3gN3UWRcY3epIEPevfq+3njBxq/kqBoGBduvea8f393zICS63ivRBTqgFpgaWZEIUULdcK+frIfAAL2AjscXqrLfu+uuwx05FF0XUbvvtuOeu++689+7778AHL/wJIQAAOwAAAAAAAAAAAA==");
| zzangtest123-google-drive-sdk-samples | ruby/public/ace/cockpit-uncompressed.js | JavaScript | asf20 | 113,605 |
<html>
<head>
<link rel="stylesheet" href="/bootstrap.min.css"></link>
<link rel="stylesheet" href="/dredit.css"></link>
<script src="https://www.google.com/jsapi" charset="utf-8"></script>
<script src="/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
<script src="/ace/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/ace/mode-html.js" type="text/javascript" charset="utf-8"></script>
<script src="/dredit.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="main">
<div id="nav-pane"></div>
<div id="action-pane">
<button type="submit" class="btn" id="create"><i
class="icon-file icon"></i> New</button>
<button type="submit" class="btn" id="open"><i
class="icon-download icon"></i> Open</button>
<button type="submit" class="btn" id="edit"><i
class="icon-edit icon"></i> Edit</button>
<button type="submit" class="btn" id="save"><i
class="icon-upload icon"></i> Save</button>
<div id="saving" class="pull-right alert">Talking to Drive</div>
</div>
<div id="editor-pane"></div>
</div>
</body>
<script>
var dredit = dredit || {};
dredit.STATE = <%= @state.to_json %>
dredit.FILE_IDS = <%= @file_ids.to_json %>;
dredit.APP_ID = '<%= @app_id %>';
google.load('picker', '1');
</script>
</html>
| zzangtest123-google-drive-sdk-samples | ruby/views/index.erb | HTML+ERB | asf20 | 1,521 |
source :gemcutter
gem 'sinatra', :require => 'sinatra/base'
gem 'thin', '~> 1.3'
gem 'pg'
gem 'data_mapper', '~> 1.2'
gem 'dm-postgres-adapter'
gem 'google-api-client', '>= 0.4.3'
group :development do
gem 'dm-sqlite-adapter', '~> 1.2'
gem 'do_sqlite3', '~> 0.10'
end
| zzangtest123-google-drive-sdk-samples | ruby/Gemfile | Ruby | asf20 | 282 |
<?php
/**
* Class for handling authentication of the user and authorization
* to access Google Drive.
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Load required libraries for working with REST API to create, read and update
* files on Google Drive. Also, load in the UserInfo service for retrieving
* Google user profile information and the DrEdit configuration.
*/
require_once 'libs/gd-v1-php/apiClient.php';
require_once 'libs/gd-v1-php/contrib/apiOauth2Service.php';
require_once 'oauth_credentials.php';
require_once 'config.php';
session_start();
/**
* Class for handling authentication of the user and authorization
* to access Google Drive.
*
* Example usage:
* $authHandler = new AuthHandler('webui');
* $authHandler->VerifyAuth();
*
* @author Ryan Boyd <rboyd@google.com>
*/
class AuthHandler {
/**
* Text to display in alert modal after authentication.
*/
private $alertModalText;
/**
* PDO database connection for storing refresh tokens.
*
* @var PDO
*/
private $dbConnection;
/**
* String representing the type of request - 'webui' or 'webapi'. Used to
* determine whether auth errors should result in a redirect to the OAuth
* provider or just a HTTP status code returned
*
* @var string
*/
private $requestType;
/**
* Constructor for AuthHandler.
*
* @param string $requestType request type used to set member variable
* @return AuthHandler constructed class
*/
function AuthHandler($requestType) {
$this->requestType = $requestType;
$this->alertModalText = '';
$this->dbConnection = $this->GetDbConnection();
return $this;
}
/**
* Get text to display in alert modal after authentication.
*
* @return string Alert modal text
*/
function GetAlertModalText() {
return $this->alertModalText;
}
/**
* Exchange an authorization code for OAuth 2.0 credentials.
*
* @param String $authorizationCode Authorization code to exchange for an
* access token and refresh token. The refresh token is only returned by
* Google on the very first exchange- when a user explicitly approves
* the authorization request.
* @return OauthCredentials OAuth 2.0 credentials object
*/
function GetOAuth2Credentials($authorizationCode) {
$client = new apiClient();
$client->setClientId(Config::CLIENT_ID);
$client->setClientSecret(Config::CLIENT_SECRET);
$client->setRedirectUri(Config::REDIRECT_URI);
/**
* Ordinarily we wouldn't set the $_GET variable. However, the API library's
* authenticate() function looks for authorization code in the query string,
* so we want to make sure it is set to the correct value passed into the
* function arguments.
*/
$_GET['code'] = $authorizationCode;
$jsonCredentials = json_decode($client->authenticate());
$oauthCredentials = new OauthCredentials(
$jsonCredentials->access_token,
isset($jsonCredentials->refresh_token)?($jsonCredentials->refresh_token):null,
$jsonCredentials->created,
$jsonCredentials->expires_in,
Config::CLIENT_ID,
Config::CLIENT_SECRET
);
return $oauthCredentials;
}
/**
* Retrieve user profile information from Google's UserInfo service.
*
* @param OauthCredentials $credentials Object representation of OAuth creds
* @return Userinfo User profile information
*/
function GetUserInfo($credentials) {
$client = new apiClient();
$client->setUseObjects(true);
/*
* Set clientId and clientSecret in case token is expired.
* and refresh is needed
*/
$client->setClientId($credentials->clientId);
$client->setClientSecret($credentials->clientSecret);
$client->setAccessToken($credentials->toJson());
$userInfoService = new apiOauth2Service($client);
$userInfo = $userInfoService->userinfo->get();
return $userInfo;
}
/**
* Create a PDO database connection.
*
* @return PDO created database connection object
*/
function GetDbConnection() {
$dbh = new PDO(Config::DB_PDO_CONNECT,
Config::DB_PDO_USER,
Config::DB_PDO_PASSWORD);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbConnection = $dbh;
return $dbConnection;
}
/**
* Get a user row from the database with the specified Google user ID.
*
* @param string $userId Google user ID from UserInfo service
* @return array Array of a database row, keyed on column. Returns null if
* no record is found
*/
function GetUserFromDb($userId) {
$selectStmt = $this->dbConnection->prepare(
'SELECT id, refresh_token FROM users WHERE id=:id');
$selectStmt->bindParam(':id', $userId);
if ($selectStmt->execute()) {
$row = $selectStmt->fetch();
if ($row) {
return $row;
}
}
return null;
}
/**
* Update the refresh token in the database for the supplied user ID.
*
* @param string $userId Google user ID from UserInfo service
* @param string $refreshToken Refresh token to set in DB
* @return bool true on success. PDO exceptions thrown otherwise.
*/
function UpdateRefreshTokenInDb($userId, $refreshToken) {
$updateStmt = $this->dbConnection->prepare(
'UPDATE users SET refresh_token=:refresh_token WHERE id=:id');
$updateStmt->bindParam(':id', $userInfo->id);
$updateStmt->bindParam(':refresh_token', $refreshToken);
$updateStmt->execute();
return true;
}
/**
* Create a user record in the database, with the specified UserInfo profile
* and refresh token.
*
* @param stdClass $userInfo stdClass returned by Google's UserInfo service
* @param string $refreshToken OAuth refresh token for user
* @return bool true on sucess. PDO exceptions thrown otherwise.
*/
function CreateUserInDb($userInfo, $refreshToken) {
$insertStmt = $this->dbConnection->prepare(
'INSERT INTO users(id,first_name,last_name,email,refresh_token) ' .
'VALUES(:id,:first_name,:last_name,:email,:refresh_token)');
$insertStmt->bindParam(':id', $userInfo->id);
$insertStmt->bindParam(':first_name', $userInfo->given_name);
$insertStmt->bindParam(':last_name', $userInfo->family_name);
$insertStmt->bindParam(':email', $userInfo->email);
$insertStmt->bindParam(':refresh_token', $refreshToken);
$insertStmt->execute();
return true;
}
/**
* Retrieve the user from the database.
* - If the user does not exist, create it
* - If the user does exist and there's a new refresh token, update it
* Save credentials in the session
*
* @param stdClass $userInfo stdClass returned by Google's UserInfo service
* @param string $refreshToken OAuth refresh token for user
* @return string User ID of the retrieved or created user
*/
function GetUser($userInfo, $refreshToken='') {
$userId = null;
$sessCredentials = $_SESSION['credentials'];
$userRow = $this->GetUserFromDb($userInfo->id);
if ($userRow) {
if ($refreshToken == '') {
$sessCredentials->refreshToken = $userRow['refresh_token'];
} else {
// we have a new refresh token, update it in the DB
$this->UpdateRefreshTokenInDb($userRow['id'], $refreshToken);
$sessCredentials->refreshToken = $refreshToken;
}
} else {
// create user
$this->CreateUserInDb($userInfo, $refreshToken);
$sessCredentials->refreshToken = $refreshToken;
}
/*
* Store updated credentials in the user's session, using refreshToken
* retrieved from database
*/
$_SESSION['credentials'] = $sessCredentials;
return $userInfo->id;
}
function VerifyAuth() {
$userInfo = null;
try {
/*
* If an authorization code is in the URL, process it
*/
if (isset($_GET['code'])) {
/**
* Redeemed authorization codes are stored in the session to prevent
* accidental multiple redemption of the same code causing an exception.
* ie, if a user refreshes their browser when a code is in the URL.
* We need to initialize the array of redeemed authorization codes.
*/
if (!isset($_SESSION['redeemed_codes'])) {
$_SESSION['redeemed_codes'] = array();
}
/*
* If code has not been used before, we could have a new
* user authenticating. Check if this is the case.
*/
if (array_search($_GET['code'], $_SESSION['redeemed_codes']) === false) {
$oldUserInfo = (isset($_SESSION['userInfo']))?($_SESSION['userInfo']):null;
$credentials = $this->GetOAuth2Credentials($_GET['code']);
$_SESSION['credentials'] = $credentials;
try {
$userInfo = $this->GetUserInfo($_SESSION['credentials']);
$_SESSION['userInfo'] = $userInfo;
} catch (apiException $e) {
error_log('Error retrieving user information from UserInfo svc: ' .
$e->getMessage(), 0);
throw $e;
}
try {
$refreshToken = $credentials->refreshToken;
$userId = $this->GetUser($userInfo, $refreshToken);
} catch (Exception $e) {
error_log('Error retrieving user from DB or updating refresh token: ' .
$e->getMessage(), 0);
throw $e;
}
$_SESSION['userId'] = $userId;
$_SESSION['redeemed_codes'][] = $_GET['code'];
/*
* If the user has changed during this session, set the alertModalText
* to display the change in the UI. This mitigates some types of
* session fixation attacks.
*/
if (isset($oldUserInfo->id) && isset($userInfo->id) &&
$oldUserInfo->id != $userInfo->id) {
$this->alertModalText =
sprintf('<p>Previously signed in as: %s <br />' .
'Now signing in as: %s</p>',
$oldUserInfo->email,
$userInfo->email);
}
}
}
} catch (apiException $e) {
error_log('Error when authenticating and authorizing user: ' .
$e->getMessage(), 0);
/*
* Remove all credentials from session, as user isn't properly
* authorized or there were issues retrieving the user's identity.
*/
unset($_SESSION['userId']);
unset($_SESSION['credentials']);
}
/*
* If we dont' have an authenticated user, or don't have OAuth credentials
* available for interaction with the Drive API, we need to redirect the
* user to OAuth (for web UI requests) or fail (for JS API request).
*/
if (!isset($_SESSION['userId']) || ! isset($_SESSION['credentials'])){
if ($this->requestType == 'webui') {
/*
* Request came direct to app's web UI. Redirect for OAuth
* authorization and stop processing the PHP code.
*/
header('Location: ' . Config::FULL_AUTH_URL);
exit;
} else {
/*
* Request came to JS API. JS needs to decide how to handle, so throw a 401
* and stop processing the PHP code.
*/
header("HTTP/1.1 401 Unauthorized");
exit;
}
}
return $userInfo;
}
}
| zzangtest123-google-drive-sdk-samples | php/auth_handler.php | PHP | asf20 | 11,930 |
<?php
/**
* Outputs DrEdit PHP user interface. Needs OAuth URLs and the values of
* query params in order to setup the UI. These are set as javascript
* vars based on PHP processing.
*
* @author Ryan Boyd <rboyd@google.com>
*
* If the user's picture is set, it is included in the interface to mitigate
* potential session fixation attacks.
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
?><html>
<head>
<title>DrEdit PHP</title>
<link rel="stylesheet" href="static/bootstrap.min.css"></link>
<link rel="stylesheet" href="static/dredit.css"></link>
<script src="https://www.google.com/jsapi" charset="utf-8"></script>
<script src="static/jquery.min.js"
type="text/javascript"
charset="utf-8"></script>
<script src="static/bootstrap.min.js"
type="text/javascript"
charset="utf-8"></script>
<script src="static/ace/ace.js"
type="text/javascript"
charset="utf-8"></script>
<script src="static/ace/mode-html.js"
type="text/javascript"
charset="utf-8"></script>
<script src="static/dredit.js"
type="text/javascript"
charset="utf-8"></script>
</head>
<body>
<div class="navbar navbar-fixed-top pull-right">
<ul class="nav pull-right">
<?php if (isset($userPicture)) { ?>
<li><img src="<?php echo $userPicture;?>" height="30" /></li>
<?php } ?>
</ul>
</div>
<div id="main">
<div id="nav-pane"></div>
<div id="action-pane">
<button type="submit" class="btn" id="create"><i
class="icon-file icon"></i> New</button>
<button type="submit" class="btn" id="open"><i
class="icon-download icon"></i> Open</button>
<button type="submit" class="btn" id="edit"><i
class="icon-edit icon"></i> Edit</button>
<button type="submit" class="btn" id="save"><i
class="icon-upload icon"></i> Save</button>
<div id="saving" class="pull-right alert">Talking to Drive</div>
<div id="saving-error" class="pull-right alert alert-error"
style="display: none;">Error Saving</div>
</div>
<div id="editor-pane"></div>
</div>
</body>
<script>
var alertModalText = <?php echo json_encode($alertModalText);?>;
var dredit = dredit || {};
dredit.FILE_IDS = <?php echo json_encode($_SESSION['fileIds']);?>;
dredit.PARENT_ID = <?php echo json_encode($_SESSION['parentId']);?>;
dredit.APP_ID = '<?php echo Config::APP_ID;?>';
dredit.OAUTH_AUTH_URL = '<?php echo Config::FULL_AUTH_URL;?>';
google.load('picker', '1');
</script>
</html>
| zzangtest123-google-drive-sdk-samples | php/output_editor.php | PHP | asf20 | 3,205 |
<?php
/**
* Class for accessing the Google Drive API, including retrieving,
* creating and updating files stored in Google Drive.
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once 'libs/gd-v1-php/apiClient.php';
require_once 'libs/gd-v1-php/contrib/apiDriveService.php';
/**
* Class for accessing the Google Drive API, including retrieving,
* creating and updating files stored in Google Drive.
*
* @author Ryan Boyd <rboyd@google.com>
*/
class DriveHandler {
/**
* Google API service class for interacting with Drive API
*
* @var apiDriveService
*/
private $service;
/**
* Construct a DriveHandler, building the service object from the passed
* OAuth credentials.
*
* @param OauthCredentials $credentials OAuth credentials
* @return DriveHandler the constructed object
*/
function DriveHandler($credentials) {
$this->service = $this->BuildService($credentials);
return $this;
}
/**
* Build a Drive service object for interacting with the Google Drive API.
*
* @return apiDriveService service object
*/
function BuildService($credentials) {
$client = new apiClient();
// return data from API calls as PHP objects instead of arrays
$client->setUseObjects(true);
$client->setAccessToken($credentials->toJson());
// set clientId and clientSecret in case token is expired
// and refresh is needed
$client->setClientId($credentials->clientId);
$client->setClientSecret($credentials->clientSecret);
return new apiDriveService($client);
}
/**
* Retrieve a file metadata and content from Drive.
*
* @param string $fileId ID for the file to retrieve from Drive
* @return string JSON string representation of file metadata and content
*/
function GetFile($fileId) {
$fileVars = null;
try {
/*
* Retrieve metadata for the file specified by $fileId.
*/
$file = $this->service->files->get($fileId);
$fileVars = get_object_vars($file);
/*
* Retrieve the file's content using download URL specified in metadata.
*/
$request = new apiHttpRequest($file->downloadUrl, 'GET', null, null);
$httpRequest = apiClient::$io->authenticatedRequest($request);
$content = $httpRequest->getResponseBody();
$fileVars['content'] = $content?($content):'';
} catch (apiServiceException $e) {
/*
* Log error and re-throw
*/
error_log('Error retrieving file from Drive: ' . $e->getMessage(), 0);
throw $e;
}
return json_encode($fileVars);
}
/**
* Save an updated file to drive, including metadata and content.
*
* @param string $fileId ID representing file to save to Drive
* @param DriveFile $inputFile File to be updated
* @return DriveFile File object representing new file
*/
function SaveUpdatedFile($fileId, $inputFile) {
try {
$file = $this->service->files->get($fileId);
$file->setTitle($inputFile->title);
$file->setDescription($inputFile->description);
$optParams = array('newRevision' => true);
$updatedFile = $this->service->files->update($fileId, $file,
array('data' => $inputFile->content, 'mimeType' => $file->mimeType));
return $updatedFile;
} catch (apiServiceException $e) {
/*
* Log error and re-throw
*/
error_log('Error saving updated file to Drive: ' . $e->getMessage(), 0);
throw $e;
}
}
/**
* Save a new file to drive, including metadata and content.
*
* @param DriveFile $inputFile File to be updated
* @return DriveFile File object representing new file
*/
function SaveNewFile($inputFile) {
try {
$mimeType = 'text/plain';
$file = new DriveFile();
$file->setTitle($inputFile->title);
$file->setDescription($inputFile->description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($inputFile->parentId != null) {
$parentsCollectionData = new DriveFileParentsCollection();
$parentsCollectionData->setId($inputFile->parentId);
$file->setParentsCollection(array($parentsCollectionData));
}
$createdFile = $this->service->files->insert($file, array(
'data' => $inputFile->content,
'mimeType' => $mimeType,
));
return $createdFile;
} catch (apiServiceException $e) {
/*
* Log error and re-throw
*/
error_log('Error saving new file to Drive: ' . $e->getMessage(), 0);
throw $e;
}
}
/**
* Save a file to drive, including metadata and content.
*
* @param string $fileId ID representing file to save to Drive
* @param DriveFile $inputFile File to be updated
* @return DriveFile File object representing saved content
*/
function SaveFile($fileId, $inputFile) {
if ($fileId != '') {
return $this->SaveUpdatedFile($fileId, $inputFile);
} else {
$createdFile = $this->SaveNewFile($inputFile);
$_SESSION['fileId'] = $createdFile->id;
return $createdFile;
}
}
}
?>
| zzangtest123-google-drive-sdk-samples | php/drive_handler.php | PHP | asf20 | 5,644 |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Namespace for DrEdit user interface.
* @type {object}
*/
var dredit = dredit || {};
dredit.main_view = null;
dredit.new_file_counter = 0;
/**
* User interface controller class.
* @constructor
*/
dredit.View = function(config) {
this.config = config || {};
this.current_page = null;
this.editor_id = 'editor';
this.pages = {};
};
/**
* Creates the user interface of the view.
*/
dredit.View.prototype.CreateUi = function() {
this.CreateNavs();
this.CreateEditor();
this.saver = new dredit.SaveNotification();
$('#edit').click($.proxy(this.Edit, this));
$('#save').click($.proxy(this.Save, this));
$('#create').click($.proxy(this.Create, this));
$('#open').click($.proxy(this.CreatePicker, this));
}
/**
* Creates the list that will hold the file navigation elements.
*/
dredit.View.prototype.CreateNavs = function() {
$('#nav-pane').append(
$('<ul></ul>')
.attr('id', 'editor-navs')
.attr('class', 'nav nav-pills'));
}
/**
* Creates the element that will hold the text editor.
*/
dredit.View.prototype.CreateEditor = function() {
$('#editor-pane').append(
$('<div></div>')
.attr('id', 'editor-holder')
.append(
$('<div></div>')
.attr('class', 'editor')
.attr('id', this.editor_id)));
this.editor = ace.edit(this.editor_id);
var mode = require('ace/mode/html').Mode;
this.editor.getSession().setMode(new mode());
}
/**
* Creates a page for a file ID.
* @param {string} File's ID or an empty string for a new file.
*/
dredit.View.prototype.CreatePage = function(file_id) {
var page = new dredit.Page(this);
page.Load(file_id);
this.pages[page.tab_id] = page;
}
dredit.View.prototype.PickerSelected = function(data) {
if (data.action == 'picked') {
for (i in data.docs) {
this.CreatePage(data.docs[i].id);
}
}
}
dredit.View.prototype.CreatePicker = function() {
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes('text/plain,text/html');
picker = new google.picker.PickerBuilder().
setAppId(dredit.APP_ID).
addView(view).
setCallback($.proxy(this.PickerSelected, this)).
enableFeature(google.picker.Feature.NAV_HIDDEN).
build();
picker.setVisible(true);
}
/**
* Sets a tab id as the active page.
* @param {string} tab_id Tab's ID.
*/
dredit.View.prototype.SetTab = function(tab_id) {
this.SetPage(this.pages[tab_id]);
}
/**
* Sets a page as the active page.
* @param {dredit.Page} page Page to activate.
*/
dredit.View.prototype.SetPage = function(page) {
this.current_page = page;
$('#editor-navs > li').removeClass('active');
page.label_holder.addClass('active');
this.editor.setSession(page.session);
}
/**
* Performs an appropriate XHR to save the current file.
*/
dredit.View.prototype.Save = function() {
if (!dredit.blocked) {
this.current_page.Save();
}
else {
// console.log('Blocked on another operation.');
}
};
dredit.View.prototype.Edit = function() {
this.current_page.title_changer.Pop();
};
dredit.View.prototype.Create = function() {
this.CreatePage();
};
/**
* Model for an individual file.
* @constructor
*/
dredit.Page = function(view) {
this.file_id = null;
this.title = null;
this.description = null;
this.content = null;
this.position = null;
this.view = view;
}
/**
* Create the navigation label for this page.
*/
dredit.Page.prototype.CreateLabel = function() {
this.label_holder = $('<li></li>');
var tab_id = this.tab_id;
var view = this.view;
var _OnFileClicked = function() {
view.SetTab(tab_id);
}
this.label_text = $('<a>Loading</a>')
.attr('href', '#' + this.tab_id)
.click(_OnFileClicked);
this.label_holder.append(this.label_text);
$('#editor-navs').append(this.label_holder);
}
/**
* Load a file from the server.
* @param {string} file ID to load or an empty string for a new file.
*/
dredit.Page.prototype.Load = function(file_id) {
this.title_changer = new dredit.TitleChanger(this);
if (!file_id) {
this.tab_id = dredit.new_file_counter++ + "";
this.title_changer.Pop();
this.CreateLabel();
this.Empty();
}
else {
this.file_id = file_id;
this.tab_id = file_id;
this.CreateLabel();
this.Get();
}
}
dredit.Page.prototype.Empty = function(file_id) {
this.GetSuccess({
'title': 'untitled.html',
'content': '',
'mimeType': 'text/html',
'description': '',
});
}
dredit.Page.prototype.GetSuccess = function(data, result, xhr) {
if (data.redirect) {
window.location.href = data.redirect;
}
else {
this.title = data['title'];
this.UpdateTitle(this.title);
this.content = data['content'];
this.mimetype = data['mimeType'];
this.description = data['description'];
var EditSession = require('ace/edit_session').EditSession;
this.session = new EditSession(this.content);
this.view.SetPage(this);
}
}
dredit.Page.prototype.SaveError = function(xhr, text_status, error) {
console.log(error);
$('#saving-error').show();
//window.location.href = dredit.OAUTH_AUTH_URL;
}
dredit.Page.prototype.OpenError = function(xhr, text_status, error) {
console.log(error);
window.location.href = dredit.OAUTH_AUTH_URL;
}
dredit.Page.prototype.Get = function() {
$.ajax({
url: 'svc.php?file_id=' + this.file_id,
success: this.GetSuccess,
error: this.OpenError,
context: this
});
}
dredit.Page.prototype.SaveSuccess = function(data, result, xhr) {
if (data.redirect) {
window.location.href = data.redirect;
}
else {
this.file_id = data;
}
}
dredit.Page.prototype.Save = function() {
this.content = this.session.getValue();
$.ajax({
url: 'svc.php',
type: 'PUT',
type: this.IsNew() ? 'POST' : 'PUT',
success: this.SaveSuccess,
error: this.SaveError,
data: JSON.stringify(this.Read()),
dataType: 'json',
contentType: 'application/json',
context: this
});
}
dredit.Page.prototype.Read = function() {
return {
'content': this.content,
'title': this.title,
'description': this.description,
'mimeType': this.mimetype,
'resource_id': this.file_id,
'parentId': dredit.PARENT_ID
};
}
dredit.Page.prototype.IsNew = function() {
return (this.file_id == null);
}
dredit.Page.prototype.UpdateTitle = function(title) {
this.title = title;
this.label_text.text(title);
}
dredit.Editor = function(editor_id) {
this.id = editor_id;
this.editor = ace.edit(this.id);
}
dredit.Editor.prototype.SetMode = function(filetype) {
var mode = require('ace/mode/' + filetype).Mode;
this.editor.getSession().setMode(new mode());
}
dredit.SaveNotification = function() {
$('#saving')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
//$('#save').hide();
dredit.blocked = true;
})
.ajaxStop(function() {
$(this).hide();
dredit.blocked = false;
});
$('#saving-error').hide();
}
dredit.TitleChanger = function(page) {
this.page = page;
this.title = null;
this.CreateUi(page.title);
}
dredit.TitleChanger.prototype.Pop = function() {
this.title.val(this.page.title || 'untitled.txt');
this.description.val(this.page.description);
this.modal.modal('show');
this.title.focus().select();
}
dredit.TitleChanger.prototype.Save = function() {
this.page.UpdateTitle(this.title.val());
this.page.description = this.description.val();
this.modal.modal('hide');
this.page.Save();
}
dredit.TitleChanger.prototype.CreateField = function(field, label) {
return $('<div class="control-group"></div>')
.append($('<label class="control-label"></label').text(label))
.append($('<div class="controls"></div>')
.append(field));
}
dredit.TitleChanger.prototype.CreateUi = function() {
this.title = $('<input type="text" placeholder="Enter filename" name="title">');
this.description = $('<textarea placeholder="Enter description"></textarea>');
this.saver = $('<a href="#" class="btn btn-primary">Done</a>');
this.modal = $('<div class="modal"></div>')
.append(
$('<div class="modal-header"></div>')
.append($('<a class="close" data-dismiss="modal">close</a>'))
.append($('<h3>Edit details</h3>')))
.append(
$('<div class="modal-body"></div>')
.append($('<form class="form-horizontal">')
.append(this.CreateField(this.title, 'Title'))
.append(this.CreateField(this.description, 'Description'))))
.append(
$('<div class="modal-footer"></div>')
.append(this.saver));
this.saver.click($.proxy(this.Save, this));
}
dredit.CreateAlertModal = function(alertText) {
this.closer = $('<a href="#" class="btn btn-primary">Close</a>');
this.alertModal = $('<div class="modal"></div>')
.append(
$('<div class="modal-header"></div>')
.append($('<h3>Alert</h3>')))
.append(
$('<div class="modal-body"></div>')
.append($(alertText)))
.append(
$('<div class="modal-footer"></div>')
.append(this.closer))
this.closer.click($.proxy(this.DismissAlert, this));
this.alertModal.modal('show');
}
dredit.DismissAlert = function() {
this.alertModal.modal('hide');
}
function DrEdit() {
this.view = new dredit.View();
this.view.CreateUi();
if (dredit.FILE_IDS.length > 0 ) {
for (i in dredit.FILE_IDS) {
this.view.CreatePage(dredit.FILE_IDS[i]);
}
} else {
this.view.CreatePage();
}
if (alertModalText != '') {
dredit.CreateAlertModal(alertModalText);
}
}
$(document).ready(function() {
dredit.main = new DrEdit();
});
| zzangtest123-google-drive-sdk-samples | php/static/dredit.js | JavaScript | asf20 | 10,297 |
/**
* CSS used for DrEdit
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
body {
margin: 10px;
}
div#main {
width: 720px;
margin: auto;
}
#title_changer {
display: none;
margin-top: -100px;
}
.editor {
position: relative;
width: 720px;
height: 480px;
}
#editor-pane {
margin-top: 10px;
}
| zzangtest123-google-drive-sdk-samples | php/static/dredit.css | CSS | asf20 | 859 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/**
* Define a module along with a payload
* @param module a name for the payload
* @param payload a function to call with (require, exports, module) params
*/
(function() {
var global = (function() {
return this;
})();
// if we find an existing require function use it.
if (global.require && global.define) {
require.packaged = true;
return;
}
var _define = function(module, deps, payload) {
if (typeof module !== 'string') {
if (_define.original)
_define.original.apply(window, arguments);
else {
console.error('dropping module because define wasn\'t a string.');
console.trace();
}
return;
}
if (arguments.length == 2)
payload = deps;
if (!define.modules)
define.modules = {};
define.modules[module] = payload;
};
if (global.define)
_define.original = global.define;
global.define = _define;
/**
* Get at functionality define()ed using the function above
*/
var _require = function(module, callback) {
if (Object.prototype.toString.call(module) === "[object Array]") {
var params = [];
for (var i = 0, l = module.length; i < l; ++i) {
var dep = lookup(module[i]);
if (!dep && _require.original)
return _require.original.apply(window, arguments);
params.push(dep);
}
if (callback) {
callback.apply(null, params);
}
}
else if (typeof module === 'string') {
var payload = lookup(module);
if (!payload && _require.original)
return _require.original.apply(window, arguments);
if (callback) {
callback();
}
return payload;
}
else {
if (_require.original)
return _require.original.apply(window, arguments);
}
};
if (global.require)
_require.original = global.require;
global.require = _require;
require.packaged = true;
/**
* Internal function to lookup moduleNames and resolve them by calling the
* definition function if needed.
*/
var lookup = function(moduleName) {
var module = define.modules[moduleName];
if (module == null) {
console.error('Missing module: ' + moduleName);
return null;
}
if (typeof module === 'function') {
var exports = {};
module(require, exports, { id: moduleName, uri: '' });
// cache the resulting module object for next time
define.modules[moduleName] = exports;
return exports;
}
return module;
};
})();// vim:set ts=4 sts=4 sw=4 st:
// -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project)
// -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified
// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
// -- Irakli Gozalishvili Copyright (C) 2010 MIT License
/*!
Copyright (c) 2009, 280 North Inc. http://280north.com/
MIT License. http://github.com/280north/narwhal/blob/master/README.md
*/
define('pilot/fixoldbrowsers', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* ES5 Draft
* http://www.ecma-international.org/publications/files/drafts/tc39-2009-050.pdf
*
* NOTE: this is a draft, and as such, the URL is subject to change. If the
* link is broken, check in the parent directory for the latest TC39 PDF.
* http://www.ecma-international.org/publications/files/drafts/
*
* Previous ES5 Draft
* http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf
* This is a broken link to the previous draft of ES5 on which most of the
* numbered specification references and quotes herein were taken. Updating
* these references and quotes to reflect the new document would be a welcome
* volunteer project.
*
* @module
*/
/*whatsupdoc*/
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf
if (!Function.prototype.bind) {
var slice = Array.prototype.slice;
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
// XXX this gets pretty close, for all intents and purposes, letting
// some duck-types slide
if (typeof target.apply !== "function" || typeof target.call !== "function")
return new TypeError();
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
var args = slice.call(arguments);
// 4. Let F be a new native ECMAScript object.
// 9. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 10. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 11. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 12. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
// 13. The [[Scope]] internal property of F is unused and need not
// exist.
var bound = function bound() {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
var self = Object.create(target.prototype);
target.apply(self, args.concat(slice.call(arguments)));
return self;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the list
// boundArgs in the same order followed by the same values as
// the list ExtraArgs in the same order. 5. Return the
// result of calling the [[Call]] internal method of target
// providing boundThis as the this value and providing args
// as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.call.apply(
target,
args.concat(slice.call(arguments))
);
}
};
bound.length = (
// 14. If the [[Class]] internal property of Target is "Function", then
typeof target === "function" ?
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is larger.
Math.max(target.length - args.length, 0) :
// 15. Else set the length own property of F to 0.
0
)
// 16. The length own property of F is given attributes as specified in
// 15.3.5.1.
// TODO
// 17. Set the [[Extensible]] internal property of F to true.
// TODO
// 18. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Value]]: null,
// [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]:
// false}, and false.
// TODO
// 19. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Value]]: null,
// [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]:
// false}, and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property.
// XXX can't delete it in pure-js.
return bound;
};
}
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var owns = call.bind(prototypeOfObject.hasOwnProperty);
var defineGetter, defineSetter, lookupGetter, lookupSetter, supportsAccessors;
// If JS engine supports accessors creating shortcuts.
if ((supportsAccessors = owns(prototypeOfObject, '__defineGetter__'))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.3.2
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
}
// ES5 15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(block, thisObject) {
var len = +this.length;
for (var i = 0; i < len; i++) {
if (i in this) {
block.call(thisObject, this[i], i, this);
}
}
};
}
// ES5 15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
// ES5 15.4.4.20
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(block /*, thisp */) {
var values = [];
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (block.call(thisp, this[i]))
values.push(this[i]);
return values;
};
}
// ES5 15.4.4.16
if (!Array.prototype.every) {
Array.prototype.every = function every(block /*, thisp */) {
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (!block.call(thisp, this[i]))
return false;
return true;
};
}
// ES5 15.4.4.17
if (!Array.prototype.some) {
Array.prototype.some = function some(block /*, thisp */) {
var thisp = arguments[1];
for (var i = 0; i < this.length; i++)
if (block.call(thisp, this[i]))
return true;
return false;
};
}
// ES5 15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len === 0 && arguments.length === 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
} while (true);
}
for (; i < len; i++) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
// ES5 15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
// no value to return if no initial value, empty array
if (len === 0 && arguments.length === 1)
throw new TypeError();
var i = len - 1;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0)
throw new TypeError();
} while (true);
}
for (; i >= 0; i--) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
// ES5 15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(value /*, fromIndex */ ) {
var length = this.length;
if (!length)
return -1;
var i = arguments[1] || 0;
if (i >= length)
return -1;
if (i < 0)
i += length;
for (; i < length; i++) {
if (!owns(this, i))
continue;
if (value === this[i])
return i;
}
return -1;
};
}
// ES5 15.4.4.15
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function lastIndexOf(value /*, fromIndex */) {
var length = this.length;
if (!length)
return -1;
var i = arguments[1] || length;
if (i < 0)
i += length;
i = Math.min(i, length - 1);
for (; i >= 0; i--) {
if (!owns(this, i))
continue;
if (value === this[i])
return i;
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.2
if (!Object.getPrototypeOf) {
// https://github.com/kriskowal/es5-shim/issues#issue/2
// http://ejohn.org/blog/objectgetprototypeof/
// recommended by fschaefer on github
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || object.constructor.prototype;
// or undefined if not available in this engine
};
}
// ES5 15.2.3.3
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
"non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object !== "object" && typeof object !== "function") || object === null)
throw new TypeError(ERR_NON_OBJECT + object);
// If object does not owns property return undefined immediately.
if (!owns(object, property))
return undefined;
var despriptor, getter, setter;
// If object has a property then it's for sure both `enumerable` and
// `configurable`.
despriptor = { enumerable: true, configurable: true };
// If JS engine supports accessor properties then property may be a
// getter or setter.
if (supportsAccessors) {
// Unfortunately `__lookupGetter__` will return a getter even
// if object has own non getter property along with a same named
// inherited getter. To avoid misbehavior we temporary remove
// `__proto__` so that `__lookupGetter__` will return getter only
// if it's owned by an object.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
// Once we have getter and setter we can put values back.
object.__proto__ = prototype;
if (getter || setter) {
if (getter) descriptor.get = getter;
if (setter) descriptor.set = setter;
// If it was accessor property we're done and return here
// in order to avoid adding `value` to the descriptor.
return descriptor;
}
}
// If we got this far we know that object has an own property that is
// not an accessor so we set it as a value and return descriptor.
descriptor.value = object[property];
return descriptor;
};
}
// ES5 15.2.3.4
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
// ES5 15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype !== "object")
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
var Type = function () {};
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (typeof properties !== "undefined")
Object.defineProperties(object, properties);
return object;
};
}
// ES5 15.2.3.6
if (!Object.defineProperty) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if (typeof object !== "object" && typeof object !== "function")
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
if (typeof object !== "object" || object === null)
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors)
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get"))
defineGetter(object, property, descriptor.get);
if (owns(descriptor, "set"))
defineSetter(object, property, descriptor.set);
}
return object;
};
}
// ES5 15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property))
Object.defineProperty(object, property, properties[property]);
}
return object;
};
}
// ES5 15.2.3.8
if (!Object.seal) {
Object.seal = function seal(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.9
if (!Object.freeze) {
Object.freeze = function freeze(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// detect a Rhino bug and patch it
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object === "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
// ES5 15.2.3.10
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.11
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
// ES5 15.2.3.12
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
// ES5 15.2.3.13
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
return true;
};
}
// ES5 15.2.3.14
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
if (!Object.keys) {
var hasDontEnumBug = true,
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null})
hasDontEnumBug = false;
Object.keys = function keys(object) {
if (
typeof object !== "object" && typeof object !== "function"
|| object === null
)
throw new TypeError("Object.keys called on a non-object");
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// Format a Date object as a string according to a subset of the ISO-8601 standard.
// Useful in Atom, among other things.
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function toISOString() {
return (
this.getUTCFullYear() + "-" +
(this.getUTCMonth() + 1) + "-" +
this.getUTCDate() + "T" +
this.getUTCHours() + ":" +
this.getUTCMinutes() + ":" +
this.getUTCSeconds() + "Z"
);
}
}
// ES5 15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
// ES5 15.9.5.44
if (!Date.prototype.toJSON) {
Date.prototype.toJSON = function toJSON(key) {
// This function provides a String representation of a Date object for
// use by JSON.stringify (15.12.3). When the toJSON method is called
// with argument key, the following steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be ToPrimitive(O, hint Number).
// 3. If tv is a Number and is not finite, return null.
// XXX
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (typeof this.toISOString !== "function")
throw new TypeError();
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return this.toISOString();
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// 15.9.4.2 Date.parse (string)
// 15.9.1.15 Date Time String Format
// Date.parse
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
if (isNaN(Date.parse("T00:00"))) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function(NativeDate) {
// Date.length === 7
var Date = function(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length === 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(Date.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = Date;
return date;
}
return NativeDate.apply(this, arguments);
};
// 15.9.1.15 Date Time String Format
var isoDateExpression = new RegExp("^" +
"(?:" + // optional year-month-day
"(" + // year capture
"(?:[+-]\\d\\d)?" + // 15.9.1.15.1 Extended years
"\\d\\d\\d\\d" + // four-digit year
")" +
"(?:-" + // optional month-day
"(\\d\\d)" + // month capture
"(?:-" + // optional day
"(\\d\\d)" + // day capture
")?" +
")?" +
")?" +
"(?:T" + // hour:minute:second.subsecond
"(\\d\\d)" + // hour capture
":(\\d\\d)" + // minute capture
"(?::" + // optional :second.subsecond
"(\\d\\d)" + // second capture
"(?:\\.(\\d\\d\\d))?" + // milisecond capture
")?" +
")?" +
"(?:" + // time zone
"Z|" + // UTC capture
"([+-])(\\d\\d):(\\d\\d)" + // timezone offset
// capture sign, hour, minute
")?" +
"$");
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate)
Date[key] = NativeDate[key];
// Copy "native" methods explicitly; they may be non-enumerable
Date.now = NativeDate.now;
Date.UTC = NativeDate.UTC;
Date.prototype = NativeDate.prototype;
Date.prototype.constructor = Date;
// Upgrade Date.parse to handle the ISO dates we use
// TODO review specification to ascertain whether it is
// necessary to implement partial ISO date strings.
Date.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
match.shift(); // kill match[0], the full match
// recognize times without dates before normalizing the
// numeric values, for later use
var timeOnly = match[0] === undefined;
// parse numerics
for (var i = 0; i < 10; i++) {
// skip + or - for the timezone offset
if (i === 7)
continue;
// Note: parseInt would read 0-prefix numbers as
// octal. Number constructor or unary + work better
// here:
match[i] = +(match[i] || (i < 3 ? 1 : 0));
// match[1] is the month. Months are 0-11 in JavaScript
// Date objects, but 1-12 in ISO notation, so we
// decrement.
if (i === 1)
match[i]--;
}
// if no year-month-date is provided, return a milisecond
// quantity instead of a UTC date number value.
if (timeOnly)
return ((match[3] * 60 + match[4]) * 60 + match[5]) * 1000 + match[6];
// account for an explicit time zone offset if provided
var offset = (match[8] * 60 + match[9]) * 60 * 1000;
if (match[6] === "-")
offset = -offset;
return NativeDate.UTC.apply(this, match.slice(0, 7)) + offset;
}
return NativeDate.parse.apply(this, arguments);
};
return Date;
})(Date);
}
//
// String
// ======
//
// ES5 15.5.4.20
if (!String.prototype.trim) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
String.prototype.trim = function trim() {
return String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
};
}
});/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/ace', ['require', 'exports', 'module' , 'pilot/index', 'pilot/fixoldbrowsers', 'pilot/plugin_manager', 'pilot/dom', 'pilot/event', 'ace/editor', 'ace/edit_session', 'ace/undomanager', 'ace/virtual_renderer', 'ace/theme/textmate', 'pilot/environment'], function(require, exports, module) {
require("pilot/index");
require("pilot/fixoldbrowsers");
var catalog = require("pilot/plugin_manager").catalog;
catalog.registerPlugins([ "pilot/index" ]);
var Dom = require("pilot/dom");
var Event = require("pilot/event");
var Editor = require("ace/editor").Editor;
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
var Renderer = require("ace/virtual_renderer").VirtualRenderer;
exports.edit = function(el) {
if (typeof(el) == "string") {
el = document.getElementById(el);
}
var doc = new EditSession(Dom.getInnerText(el));
doc.setUndoManager(new UndoManager());
el.innerHTML = '';
var editor = new Editor(new Renderer(el, require("ace/theme/textmate")));
editor.setSession(doc);
var env = require("pilot/environment").create();
catalog.startupPlugins({ env: env }).then(function() {
env.document = doc;
env.editor = editor;
editor.resize();
Event.addListener(window, "resize", function() {
editor.resize();
});
el.env = env;
});
// Store env on editor such that it can be accessed later on from
// the returned object.
editor.env = env;
return editor;
};
});/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/index', ['require', 'exports', 'module' , 'pilot/fixoldbrowsers', 'pilot/types/basic', 'pilot/types/command', 'pilot/types/settings', 'pilot/commands/settings', 'pilot/commands/basic', 'pilot/settings/canon', 'pilot/canon'], function(require, exports, module) {
exports.startup = function(data, reason) {
require('pilot/fixoldbrowsers');
require('pilot/types/basic').startup(data, reason);
require('pilot/types/command').startup(data, reason);
require('pilot/types/settings').startup(data, reason);
require('pilot/commands/settings').startup(data, reason);
require('pilot/commands/basic').startup(data, reason);
// require('pilot/commands/history').startup(data, reason);
require('pilot/settings/canon').startup(data, reason);
require('pilot/canon').startup(data, reason);
};
exports.shutdown = function(data, reason) {
require('pilot/types/basic').shutdown(data, reason);
require('pilot/types/command').shutdown(data, reason);
require('pilot/types/settings').shutdown(data, reason);
require('pilot/commands/settings').shutdown(data, reason);
require('pilot/commands/basic').shutdown(data, reason);
// require('pilot/commands/history').shutdown(data, reason);
require('pilot/settings/canon').shutdown(data, reason);
require('pilot/canon').shutdown(data, reason);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/types/basic', ['require', 'exports', 'module' , 'pilot/types'], function(require, exports, module) {
var types = require("pilot/types");
var Type = types.Type;
var Conversion = types.Conversion;
var Status = types.Status;
/**
* These are the basic types that we accept. They are vaguely based on the
* Jetpack settings system (https://wiki.mozilla.org/Labs/Jetpack/JEP/24)
* although clearly more restricted.
*
* <p>In addition to these types, Jetpack also accepts range, member, password
* that we are thinking of adding.
*
* <p>This module probably should not be accessed directly, but instead used
* through types.js
*/
/**
* 'text' is the default if no type is given.
*/
var text = new Type();
text.stringify = function(value) {
return value;
};
text.parse = function(value) {
if (typeof value != 'string') {
throw new Error('non-string passed to text.parse()');
}
return new Conversion(value);
};
text.name = 'text';
/**
* We don't currently plan to distinguish between integers and floats
*/
var number = new Type();
number.stringify = function(value) {
if (!value) {
return null;
}
return '' + value;
};
number.parse = function(value) {
if (typeof value != 'string') {
throw new Error('non-string passed to number.parse()');
}
if (value.replace(/\s/g, '').length === 0) {
return new Conversion(null, Status.INCOMPLETE, '');
}
var reply = new Conversion(parseInt(value, 10));
if (isNaN(reply.value)) {
reply.status = Status.INVALID;
reply.message = 'Can\'t convert "' + value + '" to a number.';
}
return reply;
};
number.decrement = function(value) {
return value - 1;
};
number.increment = function(value) {
return value + 1;
};
number.name = 'number';
/**
* One of a known set of options
*/
function SelectionType(typeSpec) {
if (!Array.isArray(typeSpec.data) && typeof typeSpec.data !== 'function') {
throw new Error('instances of SelectionType need typeSpec.data to be an array or function that returns an array:' + JSON.stringify(typeSpec));
}
Object.keys(typeSpec).forEach(function(key) {
this[key] = typeSpec[key];
}, this);
};
SelectionType.prototype = new Type();
SelectionType.prototype.stringify = function(value) {
return value;
};
SelectionType.prototype.parse = function(str) {
if (typeof str != 'string') {
throw new Error('non-string passed to parse()');
}
if (!this.data) {
throw new Error('Missing data on selection type extension.');
}
var data = (typeof(this.data) === 'function') ? this.data() : this.data;
// The matchedValue could be the boolean value false
var hasMatched = false;
var matchedValue;
var completions = [];
data.forEach(function(option) {
if (str == option) {
matchedValue = this.fromString(option);
hasMatched = true;
}
else if (option.indexOf(str) === 0) {
completions.push(this.fromString(option));
}
}, this);
if (hasMatched) {
return new Conversion(matchedValue);
}
else {
// This is something of a hack it basically allows us to tell the
// setting type to forget its last setting hack.
if (this.noMatch) {
this.noMatch();
}
if (completions.length > 0) {
var msg = 'Possibilities' +
(str.length === 0 ? '' : ' for \'' + str + '\'');
return new Conversion(null, Status.INCOMPLETE, msg, completions);
}
else {
var msg = 'Can\'t use \'' + str + '\'.';
return new Conversion(null, Status.INVALID, msg, completions);
}
}
};
SelectionType.prototype.fromString = function(str) {
return str;
};
SelectionType.prototype.decrement = function(value) {
var data = (typeof this.data === 'function') ? this.data() : this.data;
var index;
if (value == null) {
index = data.length - 1;
}
else {
var name = this.stringify(value);
var index = data.indexOf(name);
index = (index === 0 ? data.length - 1 : index - 1);
}
return this.fromString(data[index]);
};
SelectionType.prototype.increment = function(value) {
var data = (typeof this.data === 'function') ? this.data() : this.data;
var index;
if (value == null) {
index = 0;
}
else {
var name = this.stringify(value);
var index = data.indexOf(name);
index = (index === data.length - 1 ? 0 : index + 1);
}
return this.fromString(data[index]);
};
SelectionType.prototype.name = 'selection';
/**
* SelectionType is a base class for other types
*/
exports.SelectionType = SelectionType;
/**
* true/false values
*/
var bool = new SelectionType({
name: 'bool',
data: [ 'true', 'false' ],
stringify: function(value) {
return '' + value;
},
fromString: function(str) {
return str === 'true' ? true : false;
}
});
/**
* A we don't know right now, but hope to soon.
*/
function DeferredType(typeSpec) {
if (typeof typeSpec.defer !== 'function') {
throw new Error('Instances of DeferredType need typeSpec.defer to be a function that returns a type');
}
Object.keys(typeSpec).forEach(function(key) {
this[key] = typeSpec[key];
}, this);
};
DeferredType.prototype = new Type();
DeferredType.prototype.stringify = function(value) {
return this.defer().stringify(value);
};
DeferredType.prototype.parse = function(value) {
return this.defer().parse(value);
};
DeferredType.prototype.decrement = function(value) {
var deferred = this.defer();
return (deferred.decrement ? deferred.decrement(value) : undefined);
};
DeferredType.prototype.increment = function(value) {
var deferred = this.defer();
return (deferred.increment ? deferred.increment(value) : undefined);
};
DeferredType.prototype.name = 'deferred';
/**
* DeferredType is a base class for other types
*/
exports.DeferredType = DeferredType;
/**
* A set of objects of the same type
*/
function ArrayType(typeSpec) {
if (typeSpec instanceof Type) {
this.subtype = typeSpec;
}
else if (typeof typeSpec === 'string') {
this.subtype = types.getType(typeSpec);
if (this.subtype == null) {
throw new Error('Unknown array subtype: ' + typeSpec);
}
}
else {
throw new Error('Can\' handle array subtype');
}
};
ArrayType.prototype = new Type();
ArrayType.prototype.stringify = function(values) {
// TODO: Check for strings with spaces and add quotes
return values.join(' ');
};
ArrayType.prototype.parse = function(value) {
return this.defer().parse(value);
};
ArrayType.prototype.name = 'array';
/**
* Registration and de-registration.
*/
var isStarted = false;
exports.startup = function() {
if (isStarted) {
return;
}
isStarted = true;
types.registerType(text);
types.registerType(number);
types.registerType(bool);
types.registerType(SelectionType);
types.registerType(DeferredType);
types.registerType(ArrayType);
};
exports.shutdown = function() {
isStarted = false;
types.unregisterType(text);
types.unregisterType(number);
types.unregisterType(bool);
types.unregisterType(SelectionType);
types.unregisterType(DeferredType);
types.unregisterType(ArrayType);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/types', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* Some types can detect validity, that is to say they can distinguish between
* valid and invalid values.
* TODO: Change these constants to be numbers for more performance?
*/
var Status = {
/**
* The conversion process worked without any problem, and the value is
* valid. There are a number of failure states, so the best way to check
* for failure is (x !== Status.VALID)
*/
VALID: {
toString: function() { return 'VALID'; },
valueOf: function() { return 0; }
},
/**
* A conversion process failed, however it was noted that the string
* provided to 'parse()' could be VALID by the addition of more characters,
* so the typing may not be actually incorrect yet, just unfinished.
* @see Status.INVALID
*/
INCOMPLETE: {
toString: function() { return 'INCOMPLETE'; },
valueOf: function() { return 1; }
},
/**
* The conversion process did not work, the value should be null and a
* reason for failure should have been provided. In addition some completion
* values may be available.
* @see Status.INCOMPLETE
*/
INVALID: {
toString: function() { return 'INVALID'; },
valueOf: function() { return 2; }
},
/**
* A combined status is the worser of the provided statuses
*/
combine: function(statuses) {
var combined = Status.VALID;
for (var i = 0; i < statuses.length; i++) {
if (statuses[i].valueOf() > combined.valueOf()) {
combined = statuses[i];
}
}
return combined;
}
};
exports.Status = Status;
/**
* The type.parse() method returns a Conversion to inform the user about not
* only the result of a Conversion but also about what went wrong.
* We could use an exception, and throw if the conversion failed, but that
* seems to violate the idea that exceptions should be exceptional. Typos are
* not. Also in order to store both a status and a message we'd still need
* some sort of exception type...
*/
function Conversion(value, status, message, predictions) {
/**
* The result of the conversion process. Will be null if status != VALID
*/
this.value = value;
/**
* The status of the conversion.
* @see Status
*/
this.status = status || Status.VALID;
/**
* A message to go with the conversion. This could be present for any status
* including VALID in the case where we want to note a warning for example.
* I18N: On the one hand this nasty and un-internationalized, however with
* a command line it is hard to know where to start.
*/
this.message = message;
/**
* A array of strings which are the systems best guess at better inputs than
* the one presented.
* We generally expect there to be about 7 predictions (to match human list
* comprehension ability) however it is valid to provide up to about 20,
* or less. It is the job of the predictor to decide a smart cut-off.
* For example if there are 4 very good matches and 4 very poor ones,
* probably only the 4 very good matches should be presented.
*/
this.predictions = predictions || [];
}
exports.Conversion = Conversion;
/**
* Most of our types are 'static' e.g. there is only one type of 'text', however
* some types like 'selection' and 'deferred' are customizable. The basic
* Type type isn't useful, but does provide documentation about what types do.
*/
function Type() {
};
Type.prototype = {
/**
* Convert the given <tt>value</tt> to a string representation.
* Where possible, there should be round-tripping between values and their
* string representations.
*/
stringify: function(value) { throw new Error("not implemented"); },
/**
* Convert the given <tt>str</tt> to an instance of this type.
* Where possible, there should be round-tripping between values and their
* string representations.
* @return Conversion
*/
parse: function(str) { throw new Error("not implemented"); },
/**
* The plug-in system, and other things need to know what this type is
* called. The name alone is not enough to fully specify a type. Types like
* 'selection' and 'deferred' need extra data, however this function returns
* only the name, not the extra data.
* <p>In old bespin, equality was based on the name. This may turn out to be
* important in Ace too.
*/
name: undefined,
/**
* If there is some concept of a higher value, return it,
* otherwise return undefined.
*/
increment: function(value) {
return undefined;
},
/**
* If there is some concept of a lower value, return it,
* otherwise return undefined.
*/
decrement: function(value) {
return undefined;
},
/**
* There is interesting information (like predictions) in a conversion of
* nothing, the output of this can sometimes be customized.
* @return Conversion
*/
getDefault: function() {
return this.parse('');
}
};
exports.Type = Type;
/**
* Private registry of types
* Invariant: types[name] = type.name
*/
var types = {};
/**
* Add a new type to the list available to the system.
* You can pass 2 things to this function - either an instance of Type, in
* which case we return this instance when #getType() is called with a 'name'
* that matches type.name.
* Also you can pass in a constructor (i.e. function) in which case when
* #getType() is called with a 'name' that matches Type.prototype.name we will
* pass the typeSpec into this constructor. See #reconstituteType().
*/
exports.registerType = function(type) {
if (typeof type === 'object') {
if (type instanceof Type) {
if (!type.name) {
throw new Error('All registered types must have a name');
}
types[type.name] = type;
}
else {
throw new Error('Can\'t registerType using: ' + type);
}
}
else if (typeof type === 'function') {
if (!type.prototype.name) {
throw new Error('All registered types must have a name');
}
types[type.prototype.name] = type;
}
else {
throw new Error('Unknown type: ' + type);
}
};
exports.registerTypes = function registerTypes(types) {
Object.keys(types).forEach(function (name) {
var type = types[name];
type.name = name;
exports.registerType(type);
});
};
/**
* Remove a type from the list available to the system
*/
exports.deregisterType = function(type) {
delete types[type.name];
};
/**
* See description of #exports.registerType()
*/
function reconstituteType(name, typeSpec) {
if (name.substr(-2) === '[]') { // i.e. endsWith('[]')
var subtypeName = name.slice(0, -2);
return new types['array'](subtypeName);
}
var type = types[name];
if (typeof type === 'function') {
type = new type(typeSpec);
}
return type;
}
/**
* Find a type, previously registered using #registerType()
*/
exports.getType = function(typeSpec) {
if (typeof typeSpec === 'string') {
return reconstituteType(typeSpec);
}
if (typeof typeSpec === 'object') {
if (!typeSpec.name) {
throw new Error('Missing \'name\' member to typeSpec');
}
return reconstituteType(typeSpec.name, typeSpec);
}
throw new Error('Can\'t extract type from ' + typeSpec);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/types/command', ['require', 'exports', 'module' , 'pilot/canon', 'pilot/types/basic', 'pilot/types'], function(require, exports, module) {
var canon = require("pilot/canon");
var SelectionType = require("pilot/types/basic").SelectionType;
var types = require("pilot/types");
/**
* Select from the available commands
*/
var command = new SelectionType({
name: 'command',
data: function() {
return canon.getCommandNames();
},
stringify: function(command) {
return command.name;
},
fromString: function(str) {
return canon.getCommand(str);
}
});
/**
* Registration and de-registration.
*/
exports.startup = function() {
types.registerType(command);
};
exports.shutdown = function() {
types.unregisterType(command);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/canon', ['require', 'exports', 'module' , 'pilot/console', 'pilot/stacktrace', 'pilot/oop', 'pilot/useragent', 'pilot/keys', 'pilot/event_emitter', 'pilot/typecheck', 'pilot/catalog', 'pilot/types', 'pilot/lang'], function(require, exports, module) {
var console = require('pilot/console');
var Trace = require('pilot/stacktrace').Trace;
var oop = require('pilot/oop');
var useragent = require('pilot/useragent');
var keyUtil = require('pilot/keys');
var EventEmitter = require('pilot/event_emitter').EventEmitter;
var typecheck = require('pilot/typecheck');
var catalog = require('pilot/catalog');
var Status = require('pilot/types').Status;
var types = require('pilot/types');
var lang = require('pilot/lang');
/*
// TODO: this doesn't belong here - or maybe anywhere?
var dimensionsChangedExtensionSpec = {
name: 'dimensionsChanged',
description: 'A dimensionsChanged is a way to be notified of ' +
'changes to the dimension of Skywriter'
};
exports.startup = function(data, reason) {
catalog.addExtensionSpec(commandExtensionSpec);
};
exports.shutdown = function(data, reason) {
catalog.removeExtensionSpec(commandExtensionSpec);
};
*/
var commandExtensionSpec = {
name: 'command',
description: 'A command is a bit of functionality with optional ' +
'typed arguments which can do something small like moving ' +
'the cursor around the screen, or large like cloning a ' +
'project from VCS.',
indexOn: 'name'
};
exports.startup = function(data, reason) {
// TODO: this is probably all kinds of evil, but we need something working
catalog.addExtensionSpec(commandExtensionSpec);
};
exports.shutdown = function(data, reason) {
catalog.removeExtensionSpec(commandExtensionSpec);
};
/**
* Manage a list of commands in the current canon
*/
/**
* A Command is a discrete action optionally with a set of ways to customize
* how it happens. This is here for documentation purposes.
* TODO: Document better
*/
var thingCommand = {
name: 'thing',
description: 'thing is an example command',
params: [{
name: 'param1',
description: 'an example parameter',
type: 'text',
defaultValue: null
}],
exec: function(env, args, request) {
thing();
}
};
/**
* A lookup hash of our registered commands
*/
var commands = {};
/**
* A lookup has for command key bindings that use a string as sender.
*/
var commmandKeyBinding = {};
/**
* Array with command key bindings that use a function to determ the sender.
*/
var commandKeyBindingFunc = { };
function splitSafe(s, separator, limit, bLowerCase) {
return (bLowerCase && s.toLowerCase() || s)
.replace(/(?:^\s+|\n|\s+$)/g, "")
.split(new RegExp("[\\s ]*" + separator + "[\\s ]*", "g"), limit || 999);
}
function parseKeys(keys, val, ret) {
var key,
hashId = 0,
parts = splitSafe(keys, "\\-", null, true),
i = 0,
l = parts.length;
for (; i < l; ++i) {
if (keyUtil.KEY_MODS[parts[i]])
hashId = hashId | keyUtil.KEY_MODS[parts[i]];
else
key = parts[i] || "-"; //when empty, the splitSafe removed a '-'
}
if (ret == null) {
return {
key: key,
hashId: hashId
}
} else {
(ret[hashId] || (ret[hashId] = {}))[key] = val;
}
}
var platform = useragent.isMac ? "mac" : "win";
function buildKeyHash(command) {
var binding = command.bindKey,
key = binding[platform],
ckb = commmandKeyBinding,
ckbf = commandKeyBindingFunc
if (!binding.sender) {
throw new Error('All key bindings must have a sender');
}
if (!binding.mac && binding.mac !== null) {
throw new Error('All key bindings must have a mac key binding');
}
if (!binding.win && binding.win !== null) {
throw new Error('All key bindings must have a windows key binding');
}
if(!binding[platform]) {
// No keymapping for this platform.
return;
}
if (typeof binding.sender == 'string') {
var targets = splitSafe(binding.sender, "\\|", null, true);
targets.forEach(function(target) {
if (!ckb[target]) {
ckb[target] = { };
}
key.split("|").forEach(function(keyPart) {
parseKeys(keyPart, command, ckb[target]);
});
});
} else if (typecheck.isFunction(binding.sender)) {
var val = {
command: command,
sender: binding.sender
};
keyData = parseKeys(key);
if (!ckbf[keyData.hashId]) {
ckbf[keyData.hashId] = { };
}
if (!ckbf[keyData.hashId][keyData.key]) {
ckbf[keyData.hashId][keyData.key] = [ val ];
} else {
ckbf[keyData.hashId][keyData.key].push(val);
}
} else {
throw new Error('Key binding must have a sender that is a string or function');
}
}
function findKeyCommand(env, sender, hashId, textOrKey) {
// Convert keyCode to the string representation.
if (typecheck.isNumber(textOrKey)) {
textOrKey = keyUtil.keyCodeToString(textOrKey);
}
// Check bindings with functions as sender first.
var bindFuncs = (commandKeyBindingFunc[hashId] || {})[textOrKey] || [];
for (var i = 0; i < bindFuncs.length; i++) {
if (bindFuncs[i].sender(env, sender, hashId, textOrKey)) {
return bindFuncs[i].command;
}
}
var ckbr = commmandKeyBinding[sender];
return ckbr && ckbr[hashId] && ckbr[hashId][textOrKey];
}
function execKeyCommand(env, sender, hashId, textOrKey) {
var command = findKeyCommand(env, sender, hashId, textOrKey);
if (command) {
return exec(command, env, sender, { });
} else {
return false;
}
}
/**
* A sorted list of command names, we regularly want them in order, so pre-sort
*/
var commandNames = [];
/**
* This registration method isn't like other Ace registration methods because
* it doesn't return a decorated command because there is no functional
* decoration to be done.
* TODO: Are we sure that in the future there will be no such decoration?
*/
function addCommand(command) {
if (!command.name) {
throw new Error('All registered commands must have a name');
}
if (command.params == null) {
command.params = [];
}
if (!Array.isArray(command.params)) {
throw new Error('command.params must be an array in ' + command.name);
}
// Replace the type
command.params.forEach(function(param) {
if (!param.name) {
throw new Error('In ' + command.name + ': all params must have a name');
}
upgradeType(command.name, param);
}, this);
commands[command.name] = command;
if (command.bindKey) {
buildKeyHash(command);
}
commandNames.push(command.name);
commandNames.sort();
};
function upgradeType(name, param) {
var lookup = param.type;
param.type = types.getType(lookup);
if (param.type == null) {
throw new Error('In ' + name + '/' + param.name +
': can\'t find type for: ' + JSON.stringify(lookup));
}
}
function removeCommand(command) {
var name = (typeof command === 'string' ? command : command.name);
command = commands[name];
delete commands[name];
lang.arrayRemove(commandNames, name);
// exaustive search is a little bit brute force but since removeCommand is
// not a performance critical operation this should be OK
var ckb = commmandKeyBinding;
for (var k1 in ckb) {
for (var k2 in ckb[k1]) {
for (var k3 in ckb[k1][k2]) {
if (ckb[k1][k2][k3] == command)
delete ckb[k1][k2][k3];
}
}
}
var ckbf = commandKeyBindingFunc;
for (var k1 in ckbf) {
for (var k2 in ckbf[k1]) {
ckbf[k1][k2].forEach(function(cmd, i) {
if (cmd.command == command) {
ckbf[k1][k2].splice(i, 1);
}
})
}
}
};
function getCommand(name) {
return commands[name];
};
function getCommandNames() {
return commandNames;
};
/**
* Default ArgumentProvider that is used if no ArgumentProvider is provided
* by the command's sender.
*/
function defaultArgsProvider(request, callback) {
var args = request.args,
params = request.command.params;
for (var i = 0; i < params.length; i++) {
var param = params[i];
// If the parameter is already valid, then don't ask for it anymore.
if (request.getParamStatus(param) != Status.VALID ||
// Ask for optional parameters as well.
param.defaultValue === null)
{
var paramPrompt = param.description;
if (param.defaultValue === null) {
paramPrompt += " (optional)";
}
var value = prompt(paramPrompt, param.defaultValue || "");
// No value but required -> nope.
if (!value) {
callback();
return;
} else {
args[param.name] = value;
}
}
}
callback();
}
/**
* Entry point for keyboard accelerators or anything else that wants to execute
* a command. A new request object is created and a check performed, if the
* passed in arguments are VALID/INVALID or INCOMPLETE. If they are INCOMPLETE
* the ArgumentProvider on the sender is called or otherwise the default
* ArgumentProvider to get the still required arguments.
* If they are valid (or valid after the ArgumentProvider is done), the command
* is executed.
*
* @param command Either a command, or the name of one
* @param env Current environment to execute the command in
* @param sender String that should be the same as the senderObject stored on
* the environment in env[sender]
* @param args Arguments for the command
* @param typed (Optional)
*/
function exec(command, env, sender, args, typed) {
if (typeof command === 'string') {
command = commands[command];
}
if (!command) {
// TODO: Should we complain more than returning false?
return false;
}
var request = new Request({
sender: sender,
command: command,
args: args || {},
typed: typed
});
/**
* Executes the command and ensures request.done is called on the request in
* case it's not marked to be done already or async.
*/
function execute() {
command.exec(env, request.args, request);
// If the request isn't asnync and isn't done, then make it done.
if (!request.isAsync && !request.isDone) {
request.done();
}
}
if (request.getStatus() == Status.INVALID) {
console.error("Canon.exec: Invalid parameter(s) passed to " +
command.name);
return false;
}
// If the request isn't complete yet, try to complete it.
else if (request.getStatus() == Status.INCOMPLETE) {
// Check if the sender has a ArgsProvider, otherwise use the default
// build in one.
var argsProvider;
var senderObj = env[sender];
if (!senderObj || !senderObj.getArgsProvider ||
!(argsProvider = senderObj.getArgsProvider()))
{
argsProvider = defaultArgsProvider;
}
// Ask the paramProvider to complete the request.
argsProvider(request, function() {
if (request.getStatus() == Status.VALID) {
execute();
}
});
return true;
} else {
execute();
return true;
}
};
exports.removeCommand = removeCommand;
exports.addCommand = addCommand;
exports.getCommand = getCommand;
exports.getCommandNames = getCommandNames;
exports.findKeyCommand = findKeyCommand;
exports.exec = exec;
exports.execKeyCommand = execKeyCommand;
exports.upgradeType = upgradeType;
/**
* We publish a 'output' event whenever new command begins output
* TODO: make this more obvious
*/
oop.implement(exports, EventEmitter);
/**
* Current requirements are around displaying the command line, and provision
* of a 'history' command and cursor up|down navigation of history.
* <p>Future requirements could include:
* <ul>
* <li>Multiple command lines
* <li>The ability to recall key presses (i.e. requests with no output) which
* will likely be needed for macro recording or similar
* <li>The ability to store the command history either on the server or in the
* browser local storage.
* </ul>
* <p>The execute() command doesn't really live here, except as part of that
* last future requirement, and because it doesn't really have anywhere else to
* live.
*/
/**
* The array of requests that wish to announce their presence
*/
var requests = [];
/**
* How many requests do we store?
*/
var maxRequestLength = 100;
/**
* To create an invocation, you need to do something like this (all the ctor
* args are optional):
* <pre>
* var request = new Request({
* command: command,
* args: args,
* typed: typed
* });
* </pre>
* @constructor
*/
function Request(options) {
options = options || {};
// Will be used in the keyboard case and the cli case
this.command = options.command;
// Will be used only in the cli case
this.args = options.args;
this.typed = options.typed;
// Have we been initialized?
this._begunOutput = false;
this.start = new Date();
this.end = null;
this.completed = false;
this.error = false;
};
oop.implement(Request.prototype, EventEmitter);
/**
* Return the status of a parameter on the request object.
*/
Request.prototype.getParamStatus = function(param) {
var args = this.args || {};
// Check if there is already a value for this parameter.
if (param.name in args) {
// If there is no value set and then the value is VALID if it's not
// required or INCOMPLETE if not set yet.
if (args[param.name] == null) {
if (param.defaultValue === null) {
return Status.VALID;
} else {
return Status.INCOMPLETE;
}
}
// Check if the parameter value is valid.
var reply,
// The passed in value when parsing a type is a string.
argsValue = args[param.name].toString();
// Type.parse can throw errors.
try {
reply = param.type.parse(argsValue);
} catch (e) {
return Status.INVALID;
}
if (reply.status != Status.VALID) {
return reply.status;
}
}
// Check if the param is marked as required.
else if (param.defaultValue === undefined) {
// The parameter is not set on the args object but it's required,
// which means, things are invalid.
return Status.INCOMPLETE;
}
return Status.VALID;
}
/**
* Return the status of a parameter name on the request object.
*/
Request.prototype.getParamNameStatus = function(paramName) {
var params = this.command.params || [];
for (var i = 0; i < params.length; i++) {
if (params[i].name == paramName) {
return this.getParamStatus(params[i]);
}
}
throw "Parameter '" + paramName +
"' not defined on command '" + this.command.name + "'";
}
/**
* Checks if all required arguments are set on the request such that it can
* get executed.
*/
Request.prototype.getStatus = function() {
var args = this.args || {},
params = this.command.params;
// If there are not parameters, then it's valid.
if (!params || params.length == 0) {
return Status.VALID;
}
var status = [];
for (var i = 0; i < params.length; i++) {
status.push(this.getParamStatus(params[i]));
}
return Status.combine(status);
}
/**
* Lazy init to register with the history should only be done on output.
* init() is expensive, and won't be used in the majority of cases
*/
Request.prototype._beginOutput = function() {
this._begunOutput = true;
this.outputs = [];
requests.push(this);
// This could probably be optimized with some maths, but 99.99% of the
// time we will only be off by one, and I'm feeling lazy.
while (requests.length > maxRequestLength) {
requests.shiftObject();
}
exports._dispatchEvent('output', { requests: requests, request: this });
};
/**
* Sugar for:
* <pre>request.error = true; request.done(output);</pre>
*/
Request.prototype.doneWithError = function(content) {
this.error = true;
this.done(content);
};
/**
* Declares that this function will not be automatically done when
* the command exits
*/
Request.prototype.async = function() {
this.isAsync = true;
if (!this._begunOutput) {
this._beginOutput();
}
};
/**
* Complete the currently executing command with successful output.
* @param output Either DOM node, an SproutCore element or something that
* can be used in the content of a DIV to create a DOM node.
*/
Request.prototype.output = function(content) {
if (!this._begunOutput) {
this._beginOutput();
}
if (typeof content !== 'string' && !(content instanceof Node)) {
content = content.toString();
}
this.outputs.push(content);
this.isDone = true;
this._dispatchEvent('output', {});
return this;
};
/**
* All commands that do output must call this to indicate that the command
* has finished execution.
*/
Request.prototype.done = function(content) {
this.completed = true;
this.end = new Date();
this.duration = this.end.getTime() - this.start.getTime();
if (content) {
this.output(content);
}
// Ensure to finish the request only once.
if (!this.isDone) {
this.isDone = true;
this._dispatchEvent('output', {});
}
};
exports.Request = Request;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Patrick Walton (pwalton@mozilla.com)
* Julian Viereck (jviereck@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/console', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* This object represents a "safe console" object that forwards debugging
* messages appropriately without creating a dependency on Firebug in Firefox.
*/
var noop = function() {};
// These are the functions that are available in Chrome 4/5, Safari 4
// and Firefox 3.6. Don't add to this list without checking browser support
var NAMES = [
"assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd",
"info", "log", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"
];
if (typeof(window) === 'undefined') {
// We're in a web worker. Forward to the main thread so the messages
// will show up.
NAMES.forEach(function(name) {
exports[name] = function() {
var args = Array.prototype.slice.call(arguments);
var msg = { op: 'log', method: name, args: args };
postMessage(JSON.stringify(msg));
};
});
} else {
// For each of the console functions, copy them if they exist, stub if not
NAMES.forEach(function(name) {
if (window.console && window.console[name]) {
exports[name] = Function.prototype.bind.call(window.console[name], window.console);
} else {
exports[name] = noop;
}
});
}
});
define('pilot/stacktrace', ['require', 'exports', 'module' , 'pilot/useragent', 'pilot/console'], function(require, exports, module) {
var ua = require("pilot/useragent");
var console = require('pilot/console');
// Changed to suit the specific needs of running within Skywriter
// Domain Public by Eric Wendelin http://eriwen.com/ (2008)
// Luke Smith http://lucassmith.name/ (2008)
// Loic Dachary <loic@dachary.org> (2008)
// Johan Euphrosine <proppy@aminche.com> (2008)
// Øyvind Sean Kinsey http://kinsey.no/blog
//
// Information and discussions
// http://jspoker.pokersource.info/skin/test-printstacktrace.html
// http://eriwen.com/javascript/js-stack-trace/
// http://eriwen.com/javascript/stacktrace-update/
// http://pastie.org/253058
// http://browsershots.org/http://jspoker.pokersource.info/skin/test-printstacktrace.html
//
//
// guessFunctionNameFromLines comes from firebug
//
// Software License Agreement (BSD License)
//
// Copyright (c) 2007, Parakey Inc.
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the
// following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// * Neither the name of Parakey Inc. nor the names of its
// contributors may be used to endorse or promote products
// derived from this software without specific prior
// written permission of Parakey Inc.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Different browsers create stack traces in different ways.
* <strike>Feature</strike> Browser detection baby ;).
*/
var mode = (function() {
// We use SC's browser detection here to avoid the "break on error"
// functionality provided by Firebug. Firebug tries to do the right
// thing here and break, but it happens every time you load the page.
// bug 554105
if (ua.isGecko) {
return 'firefox';
} else if (ua.isOpera) {
return 'opera';
} else {
return 'other';
}
// SC doesn't do any detection of Chrome at this time.
// this is the original feature detection code that is used as a
// fallback.
try {
(0)();
} catch (e) {
if (e.arguments) {
return 'chrome';
}
if (e.stack) {
return 'firefox';
}
if (window.opera && !('stacktrace' in e)) { //Opera 9-
return 'opera';
}
}
return 'other';
})();
/**
*
*/
function stringifyArguments(args) {
for (var i = 0; i < args.length; ++i) {
var argument = args[i];
if (typeof argument == 'object') {
args[i] = '#object';
} else if (typeof argument == 'function') {
args[i] = '#function';
} else if (typeof argument == 'string') {
args[i] = '"' + argument + '"';
}
}
return args.join(',');
}
/**
* Extract a stack trace from the format emitted by each browser.
*/
var decoders = {
chrome: function(e) {
var stack = e.stack;
if (!stack) {
console.log(e);
return [];
}
return stack.replace(/^.*?\n/, '').
replace(/^.*?\n/, '').
replace(/^.*?\n/, '').
replace(/^[^\(]+?[\n$]/gm, '').
replace(/^\s+at\s+/gm, '').
replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@').
split('\n');
},
firefox: function(e) {
var stack = e.stack;
if (!stack) {
console.log(e);
return [];
}
// stack = stack.replace(/^.*?\n/, '');
stack = stack.replace(/(?:\n@:0)?\s+$/m, '');
stack = stack.replace(/^\(/gm, '{anonymous}(');
return stack.split('\n');
},
// Opera 7.x and 8.x only!
opera: function(e) {
var lines = e.message.split('\n'), ANON = '{anonymous}',
lineRE = /Line\s+(\d+).*?script\s+(http\S+)(?:.*?in\s+function\s+(\S+))?/i, i, j, len;
for (i = 4, j = 0, len = lines.length; i < len; i += 2) {
if (lineRE.test(lines[i])) {
lines[j++] = (RegExp.$3 ? RegExp.$3 + '()@' + RegExp.$2 + RegExp.$1 : ANON + '()@' + RegExp.$2 + ':' + RegExp.$1) +
' -- ' +
lines[i + 1].replace(/^\s+/, '');
}
}
lines.splice(j, lines.length - j);
return lines;
},
// Safari, Opera 9+, IE, and others
other: function(curr) {
var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], j = 0, fn, args;
var maxStackSize = 10;
while (curr && stack.length < maxStackSize) {
fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;
args = Array.prototype.slice.call(curr['arguments']);
stack[j++] = fn + '(' + stringifyArguments(args) + ')';
//Opera bug: if curr.caller does not exist, Opera returns curr (WTF)
if (curr === curr.caller && window.opera) {
//TODO: check for same arguments if possible
break;
}
curr = curr.caller;
}
return stack;
}
};
/**
*
*/
function NameGuesser() {
}
NameGuesser.prototype = {
sourceCache: {},
ajax: function(url) {
var req = this.createXMLHTTPObject();
if (!req) {
return;
}
req.open('GET', url, false);
req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
req.send('');
return req.responseText;
},
createXMLHTTPObject: function() {
// Try XHR methods in order and store XHR factory
var xmlhttp, XMLHttpFactories = [
function() {
return new XMLHttpRequest();
}, function() {
return new ActiveXObject('Msxml2.XMLHTTP');
}, function() {
return new ActiveXObject('Msxml3.XMLHTTP');
}, function() {
return new ActiveXObject('Microsoft.XMLHTTP');
}
];
for (var i = 0; i < XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
// Use memoization to cache the factory
this.createXMLHTTPObject = XMLHttpFactories[i];
return xmlhttp;
} catch (e) {}
}
},
getSource: function(url) {
if (!(url in this.sourceCache)) {
this.sourceCache[url] = this.ajax(url).split('\n');
}
return this.sourceCache[url];
},
guessFunctions: function(stack) {
for (var i = 0; i < stack.length; ++i) {
var reStack = /{anonymous}\(.*\)@(\w+:\/\/([-\w\.]+)+(:\d+)?[^:]+):(\d+):?(\d+)?/;
var frame = stack[i], m = reStack.exec(frame);
if (m) {
var file = m[1], lineno = m[4]; //m[7] is character position in Chrome
if (file && lineno) {
var functionName = this.guessFunctionName(file, lineno);
stack[i] = frame.replace('{anonymous}', functionName);
}
}
}
return stack;
},
guessFunctionName: function(url, lineNo) {
try {
return this.guessFunctionNameFromLines(lineNo, this.getSource(url));
} catch (e) {
return 'getSource failed with url: ' + url + ', exception: ' + e.toString();
}
},
guessFunctionNameFromLines: function(lineNo, source) {
var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/;
var reGuessFunction = /['"]?([0-9A-Za-z_]+)['"]?\s*[:=]\s*(function|eval|new Function)/;
// Walk backwards from the first line in the function until we find the line which
// matches the pattern above, which is the function definition
var line = '', maxLines = 10;
for (var i = 0; i < maxLines; ++i) {
line = source[lineNo - i] + line;
if (line !== undefined) {
var m = reGuessFunction.exec(line);
if (m) {
return m[1];
}
else {
m = reFunctionArgNames.exec(line);
}
if (m && m[1]) {
return m[1];
}
}
}
return '(?)';
}
};
var guesser = new NameGuesser();
var frameIgnorePatterns = [
/http:\/\/localhost:4020\/sproutcore.js:/
];
exports.ignoreFramesMatching = function(regex) {
frameIgnorePatterns.push(regex);
};
/**
* Create a stack trace from an exception
* @param ex {Error} The error to create a stacktrace from (optional)
* @param guess {Boolean} If we should try to resolve the names of anonymous functions
*/
exports.Trace = function Trace(ex, guess) {
this._ex = ex;
this._stack = decoders[mode](ex);
if (guess) {
this._stack = guesser.guessFunctions(this._stack);
}
};
/**
* Log to the console a number of lines (default all of them)
* @param lines {number} Maximum number of lines to wrote to console
*/
exports.Trace.prototype.log = function(lines) {
if (lines <= 0) {
// You aren't going to have more lines in your stack trace than this
// and it still fits in a 32bit integer
lines = 999999999;
}
var printed = 0;
for (var i = 0; i < this._stack.length && printed < lines; i++) {
var frame = this._stack[i];
var display = true;
frameIgnorePatterns.forEach(function(regex) {
if (regex.test(frame)) {
display = false;
}
});
if (display) {
console.debug(frame);
printed++;
}
}
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/useragent', ['require', 'exports', 'module' ], function(require, exports, module) {
var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase();
var ua = navigator.userAgent;
var av = navigator.appVersion;
/** Is the user using a browser that identifies itself as Windows */
exports.isWin = (os == "win");
/** Is the user using a browser that identifies itself as Mac OS */
exports.isMac = (os == "mac");
/** Is the user using a browser that identifies itself as Linux */
exports.isLinux = (os == "linux");
exports.isIE = ! + "\v1";
/** Is this Firefox or related? */
exports.isGecko = exports.isMozilla = window.controllers && window.navigator.product === "Gecko";
/** oldGecko == rev < 2.0 **/
exports.isOldGecko = exports.isGecko && /rv\:1/.test(navigator.userAgent);
/** Is this Opera */
exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]";
/** Is the user using a browser that identifies itself as WebKit */
exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined;
exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined;
exports.isAIR = ua.indexOf("AdobeAIR") >= 0;
exports.isIPad = ua.indexOf("iPad") >= 0;
/**
* I hate doing this, but we need some way to determine if the user is on a Mac
* The reason is that users have different expectations of their key combinations.
*
* Take copy as an example, Mac people expect to use CMD or APPLE + C
* Windows folks expect to use CTRL + C
*/
exports.OS = {
LINUX: 'LINUX',
MAC: 'MAC',
WINDOWS: 'WINDOWS'
};
/**
* Return an exports.OS constant
*/
exports.getOS = function() {
if (exports.isMac) {
return exports.OS['MAC'];
} else if (exports.isLinux) {
return exports.OS['LINUX'];
} else {
return exports.OS['WINDOWS'];
}
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/oop', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.inherits = (function() {
var tempCtor = function() {};
return function(ctor, superCtor) {
tempCtor.prototype = superCtor.prototype;
ctor.super_ = superCtor.prototype;
ctor.prototype = new tempCtor();
ctor.prototype.constructor = ctor;
}
}());
exports.mixin = function(obj, mixin) {
for (var key in mixin) {
obj[key] = mixin[key];
}
};
exports.implement = function(proto, mixin) {
exports.mixin(proto, mixin);
};
});
/*! @license
==========================================================================
SproutCore -- JavaScript Application Framework
copyright 2006-2009, Sprout Systems Inc., Apple Inc. and contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
SproutCore and the SproutCore logo are trademarks of Sprout Systems, Inc.
For more information about SproutCore, visit http://www.sproutcore.com
==========================================================================
@license */
// Most of the following code is taken from SproutCore with a few changes.
define('pilot/keys', ['require', 'exports', 'module' , 'pilot/oop'], function(require, exports, module) {
var oop = require("pilot/oop");
/**
* Helper functions and hashes for key handling.
*/
var Keys = (function() {
var ret = {
MODIFIER_KEYS: {
16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta'
},
KEY_MODS: {
"ctrl": 1, "alt": 2, "option" : 2,
"shift": 4, "meta": 8, "command": 8
},
FUNCTION_KEYS : {
8 : "Backspace",
9 : "Tab",
13 : "Return",
19 : "Pause",
27 : "Esc",
32 : "Space",
33 : "PageUp",
34 : "PageDown",
35 : "End",
36 : "Home",
37 : "Left",
38 : "Up",
39 : "Right",
40 : "Down",
44 : "Print",
45 : "Insert",
46 : "Delete",
112: "F1",
113: "F2",
114: "F3",
115: "F4",
116: "F5",
117: "F6",
118: "F7",
119: "F8",
120: "F9",
121: "F10",
122: "F11",
123: "F12",
144: "Numlock",
145: "Scrolllock"
},
PRINTABLE_KEYS: {
32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5',
54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a',
66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h',
73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o',
80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v',
87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.',
188: ',', 190: '.', 191: '/', 192: '`', 219: '[', 220: '\\',
221: ']', 222: '\"'
}
};
// A reverse map of FUNCTION_KEYS
for (i in ret.FUNCTION_KEYS) {
var name = ret.FUNCTION_KEYS[i].toUpperCase();
ret[name] = parseInt(i, 10);
}
// Add the MODIFIER_KEYS, FUNCTION_KEYS and PRINTABLE_KEYS to the KEY
// variables as well.
oop.mixin(ret, ret.MODIFIER_KEYS);
oop.mixin(ret, ret.PRINTABLE_KEYS);
oop.mixin(ret, ret.FUNCTION_KEYS);
return ret;
})();
oop.mixin(exports, Keys);
exports.keyCodeToString = function(keyCode) {
return (Keys[keyCode] || String.fromCharCode(keyCode)).toLowerCase();
}
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) {
var EventEmitter = {};
EventEmitter._emit =
EventEmitter._dispatchEvent = function(eventName, e) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners || !listeners.length) return;
var e = e || {};
e.type = eventName;
for (var i=0; i<listeners.length; i++) {
listeners[i](e);
}
};
EventEmitter.on =
EventEmitter.addEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners) {
var listeners = this._eventRegistry[eventName] = [];
}
if (listeners.indexOf(callback) == -1) {
listeners.push(callback);
}
};
EventEmitter.removeListener =
EventEmitter.removeEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners) {
return;
}
var index = listeners.indexOf(callback);
if (index !== -1) {
listeners.splice(index, 1);
}
};
EventEmitter.removeAllListeners = function(eventName) {
if (this._eventRegistry) this._eventRegistry[eventName] = [];
}
exports.EventEmitter = EventEmitter;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/typecheck', ['require', 'exports', 'module' ], function(require, exports, module) {
var objectToString = Object.prototype.toString;
/**
* Return true if it is a String
*/
exports.isString = function(it) {
return it && objectToString.call(it) === "[object String]";
};
/**
* Returns true if it is a Boolean.
*/
exports.isBoolean = function(it) {
return it && objectToString.call(it) === "[object Boolean]";
};
/**
* Returns true if it is a Number.
*/
exports.isNumber = function(it) {
return it && objectToString.call(it) === "[object Number]" && isFinite(it);
};
/**
* Hack copied from dojo.
*/
exports.isObject = function(it) {
return it !== undefined &&
(it === null || typeof it == "object" ||
Array.isArray(it) || exports.isFunction(it));
};
/**
* Is the passed object a function?
* From dojo.isFunction()
*/
exports.isFunction = function(it) {
return it && objectToString.call(it) === "[object Function]";
};
});/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Julian Viereck (jviereck@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/catalog', ['require', 'exports', 'module' ], function(require, exports, module) {
var extensionSpecs = {};
exports.addExtensionSpec = function(extensionSpec) {
extensionSpecs[extensionSpec.name] = extensionSpec;
};
exports.removeExtensionSpec = function(extensionSpec) {
if (typeof extensionSpec === "string") {
delete extensionSpecs[extensionSpec];
}
else {
delete extensionSpecs[extensionSpec.name];
}
};
exports.getExtensionSpec = function(name) {
return extensionSpecs[name];
};
exports.getExtensionSpecs = function() {
return Object.keys(extensionSpecs);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/lang', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.stringReverse = function(string) {
return string.split("").reverse().join("");
};
exports.stringRepeat = function (string, count) {
return new Array(count + 1).join(string);
};
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
exports.stringTrimLeft = function (string) {
return string.replace(trimBeginRegexp, '')
};
exports.stringTrimRight = function (string) {
return string.replace(trimEndRegexp, '');
};
exports.copyObject = function(obj) {
var copy = {};
for (var key in obj) {
copy[key] = obj[key];
}
return copy;
};
exports.copyArray = function(array){
var copy = [];
for (i=0, l=array.length; i<l; i++) {
if (array[i] && typeof array[i] == "object")
copy[i] = this.copyObject( array[i] );
else
copy[i] = array[i]
}
return copy;
};
exports.deepCopy = function (obj) {
if (typeof obj != "object") {
return obj;
}
var copy = obj.constructor();
for (var key in obj) {
if (typeof obj[key] == "object") {
copy[key] = this.deepCopy(obj[key]);
} else {
copy[key] = obj[key];
}
}
return copy;
}
exports.arrayToMap = function(arr) {
var map = {};
for (var i=0; i<arr.length; i++) {
map[arr[i]] = 1;
}
return map;
};
/**
* splice out of 'array' anything that === 'value'
*/
exports.arrayRemove = function(array, value) {
for (var i = 0; i <= array.length; i++) {
if (value === array[i]) {
array.splice(i, 1);
}
}
};
exports.escapeRegExp = function(str) {
return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
};
exports.deferredCall = function(fcn) {
var timer = null;
var callback = function() {
timer = null;
fcn();
};
var deferred = function(timeout) {
if (!timer) {
timer = setTimeout(callback, timeout || 0);
}
return deferred;
}
deferred.schedule = deferred;
deferred.call = function() {
this.cancel();
fcn();
return deferred;
};
deferred.cancel = function() {
clearTimeout(timer);
timer = null;
return deferred;
};
return deferred;
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/types/settings', ['require', 'exports', 'module' , 'pilot/types/basic', 'pilot/types', 'pilot/settings'], function(require, exports, module) {
var SelectionType = require('pilot/types/basic').SelectionType;
var DeferredType = require('pilot/types/basic').DeferredType;
var types = require('pilot/types');
var settings = require('pilot/settings').settings;
/**
* EVIL: This relies on us using settingValue in the same event as setting
* The alternative is to have some central place where we store the current
* command line, but this might be a lesser evil for now.
*/
var lastSetting;
/**
* Select from the available settings
*/
var setting = new SelectionType({
name: 'setting',
data: function() {
return env.settings.getSettingNames();
},
stringify: function(setting) {
lastSetting = setting;
return setting.name;
},
fromString: function(str) {
lastSetting = settings.getSetting(str);
return lastSetting;
},
noMatch: function() {
lastSetting = null;
}
});
/**
* Something of a hack to allow the set command to give a clearer definition
* of the type to the command line.
*/
var settingValue = new DeferredType({
name: 'settingValue',
defer: function() {
if (lastSetting) {
return lastSetting.type;
}
else {
return types.getType('text');
}
},
/**
* Promote the current value in any list of predictions, and add it if
* there are none.
*/
getDefault: function() {
var conversion = this.parse('');
if (lastSetting) {
var current = lastSetting.get();
if (conversion.predictions.length === 0) {
conversion.predictions.push(current);
}
else {
// Remove current from predictions
var removed = false;
while (true) {
var index = conversion.predictions.indexOf(current);
if (index === -1) {
break;
}
conversion.predictions.splice(index, 1);
removed = true;
}
// If the current value wasn't something we would predict, leave it
if (removed) {
conversion.predictions.push(current);
}
}
}
return conversion;
}
});
var env;
/**
* Registration and de-registration.
*/
exports.startup = function(data, reason) {
// TODO: this is probably all kinds of evil, but we need something working
env = data.env;
types.registerType(setting);
types.registerType(settingValue);
};
exports.shutdown = function(data, reason) {
types.unregisterType(setting);
types.unregisterType(settingValue);
};
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
* Julian Viereck (jviereck@mozilla.com)
* Kevin Dangoor (kdangoor@mozilla.com)
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/settings', ['require', 'exports', 'module' , 'pilot/console', 'pilot/oop', 'pilot/types', 'pilot/event_emitter', 'pilot/catalog'], function(require, exports, module) {
/**
* This plug-in manages settings.
*/
var console = require('pilot/console');
var oop = require('pilot/oop');
var types = require('pilot/types');
var EventEmitter = require('pilot/event_emitter').EventEmitter;
var catalog = require('pilot/catalog');
var settingExtensionSpec = {
name: 'setting',
description: 'A setting is something that the application offers as a ' +
'way to customize how it works',
register: 'env.settings.addSetting',
indexOn: 'name'
};
exports.startup = function(data, reason) {
catalog.addExtensionSpec(settingExtensionSpec);
};
exports.shutdown = function(data, reason) {
catalog.removeExtensionSpec(settingExtensionSpec);
};
/**
* Create a new setting.
* @param settingSpec An object literal that looks like this:
* {
* name: 'thing',
* description: 'Thing is an example setting',
* type: 'string',
* defaultValue: 'something'
* }
*/
function Setting(settingSpec, settings) {
this._settings = settings;
Object.keys(settingSpec).forEach(function(key) {
this[key] = settingSpec[key];
}, this);
this.type = types.getType(this.type);
if (this.type == null) {
throw new Error('In ' + this.name +
': can\'t find type for: ' + JSON.stringify(settingSpec.type));
}
if (!this.name) {
throw new Error('Setting.name == undefined. Ignoring.', this);
}
if (!this.defaultValue === undefined) {
throw new Error('Setting.defaultValue == undefined', this);
}
if (this.onChange) {
this.on('change', this.onChange.bind(this))
}
this.set(this.defaultValue);
}
Setting.prototype = {
get: function() {
return this.value;
},
set: function(value) {
if (this.value === value) {
return;
}
this.value = value;
if (this._settings.persister) {
this._settings.persister.persistValue(this._settings, this.name, value);
}
this._dispatchEvent('change', { setting: this, value: value });
},
/**
* Reset the value of the <code>key</code> setting to it's default
*/
resetValue: function() {
this.set(this.defaultValue);
},
toString: function () {
return this.name;
}
};
oop.implement(Setting.prototype, EventEmitter);
/**
* A base class for all the various methods of storing settings.
* <p>Usage:
* <pre>
* // Create manually, or require 'settings' from the container.
* // This is the manual version:
* var settings = plugins.catalog.getObject('settings');
* // Add a new setting
* settings.addSetting({ name:'foo', ... });
* // Display the default value
* alert(settings.get('foo'));
* // Alter the value, which also publishes the change etc.
* settings.set('foo', 'bar');
* // Reset the value to the default
* settings.resetValue('foo');
* </pre>
* @constructor
*/
function Settings(persister) {
// Storage for deactivated values
this._deactivated = {};
// Storage for the active settings
this._settings = {};
// We often want sorted setting names. Cache
this._settingNames = [];
if (persister) {
this.setPersister(persister);
}
};
Settings.prototype = {
/**
* Function to add to the list of available settings.
* <p>Example usage:
* <pre>
* var settings = plugins.catalog.getObject('settings');
* settings.addSetting({
* name: 'tabsize', // For use in settings.get('X')
* type: 'number', // To allow value checking.
* defaultValue: 4 // Default value for use when none is directly set
* });
* </pre>
* @param {object} settingSpec Object containing name/type/defaultValue members.
*/
addSetting: function(settingSpec) {
var setting = new Setting(settingSpec, this);
this._settings[setting.name] = setting;
this._settingNames.push(setting.name);
this._settingNames.sort();
},
addSettings: function addSettings(settings) {
Object.keys(settings).forEach(function (name) {
var setting = settings[name];
if (!('name' in setting)) setting.name = name;
this.addSetting(setting);
}, this);
},
removeSetting: function(setting) {
var name = (typeof setting === 'string' ? setting : setting.name);
setting = this._settings[name];
delete this._settings[name];
util.arrayRemove(this._settingNames, name);
settings.removeAllListeners('change');
},
removeSettings: function removeSettings(settings) {
Object.keys(settings).forEach(function(name) {
var setting = settings[name];
if (!('name' in setting)) setting.name = name;
this.removeSettings(setting);
}, this);
},
getSettingNames: function() {
return this._settingNames;
},
getSetting: function(name) {
return this._settings[name];
},
/**
* A Persister is able to store settings. It is an object that defines
* two functions:
* loadInitialValues(settings) and persistValue(settings, key, value).
*/
setPersister: function(persister) {
this._persister = persister;
if (persister) {
persister.loadInitialValues(this);
}
},
resetAll: function() {
this.getSettingNames().forEach(function(key) {
this.resetValue(key);
}, this);
},
/**
* Retrieve a list of the known settings and their values
*/
_list: function() {
var reply = [];
this.getSettingNames().forEach(function(setting) {
reply.push({
'key': setting,
'value': this.getSetting(setting).get()
});
}, this);
return reply;
},
/**
* Prime the local cache with the defaults.
*/
_loadDefaultValues: function() {
this._loadFromObject(this._getDefaultValues());
},
/**
* Utility to load settings from an object
*/
_loadFromObject: function(data) {
// We iterate over data rather than keys so we don't forget values
// which don't have a setting yet.
for (var key in data) {
if (data.hasOwnProperty(key)) {
var setting = this._settings[key];
if (setting) {
var value = setting.type.parse(data[key]);
this.set(key, value);
} else {
this.set(key, data[key]);
}
}
}
},
/**
* Utility to grab all the settings and export them into an object
*/
_saveToObject: function() {
return this.getSettingNames().map(function(key) {
return this._settings[key].type.stringify(this.get(key));
}.bind(this));
},
/**
* The default initial settings
*/
_getDefaultValues: function() {
return this.getSettingNames().map(function(key) {
return this._settings[key].spec.defaultValue;
}.bind(this));
}
};
exports.settings = new Settings();
/**
* Save the settings in a cookie
* This code has not been tested since reboot
* @constructor
*/
function CookiePersister() {
};
CookiePersister.prototype = {
loadInitialValues: function(settings) {
settings._loadDefaultValues();
var data = cookie.get('settings');
settings._loadFromObject(JSON.parse(data));
},
persistValue: function(settings, key, value) {
try {
var stringData = JSON.stringify(settings._saveToObject());
cookie.set('settings', stringData);
} catch (ex) {
console.error('Unable to JSONify the settings! ' + ex);
return;
}
}
};
exports.CookiePersister = CookiePersister;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Skywriter Team (skywriter@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/commands/settings', ['require', 'exports', 'module' , 'pilot/canon'], function(require, exports, module) {
var setCommandSpec = {
name: 'set',
params: [
{
name: 'setting',
type: 'setting',
description: 'The name of the setting to display or alter',
defaultValue: null
},
{
name: 'value',
type: 'settingValue',
description: 'The new value for the chosen setting',
defaultValue: null
}
],
description: 'define and show settings',
exec: function(env, args, request) {
var html;
if (!args.setting) {
// 'set' by itself lists all the settings
var names = env.settings.getSettingNames();
html = '';
// first sort the settingsList based on the name
names.sort(function(name1, name2) {
return name1.localeCompare(name2);
});
names.forEach(function(name) {
var setting = env.settings.getSetting(name);
var url = 'https://wiki.mozilla.org/Labs/Skywriter/Settings#' +
setting.name;
html += '<a class="setting" href="' + url +
'" title="View external documentation on setting: ' +
setting.name +
'" target="_blank">' +
setting.name +
'</a> = ' +
setting.value +
'<br/>';
});
} else {
// set with only a setting, shows the value for that setting
if (args.value === undefined) {
html = '<strong>' + setting.name + '</strong> = ' +
setting.get();
} else {
// Actually change the setting
args.setting.set(args.value);
html = 'Setting: <strong>' + args.setting.name + '</strong> = ' +
args.setting.get();
}
}
request.done(html);
}
};
var unsetCommandSpec = {
name: 'unset',
params: [
{
name: 'setting',
type: 'setting',
description: 'The name of the setting to return to defaults'
}
],
description: 'unset a setting entirely',
exec: function(env, args, request) {
var setting = env.settings.get(args.setting);
if (!setting) {
request.doneWithError('No setting with the name <strong>' +
args.setting + '</strong>.');
return;
}
setting.reset();
request.done('Reset ' + setting.name + ' to default: ' +
env.settings.get(args.setting));
}
};
var canon = require('pilot/canon');
exports.startup = function(data, reason) {
canon.addCommand(setCommandSpec);
canon.addCommand(unsetCommandSpec);
};
exports.shutdown = function(data, reason) {
canon.removeCommand(setCommandSpec);
canon.removeCommand(unsetCommandSpec);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Skywriter Team (skywriter@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/commands/basic', ['require', 'exports', 'module' , 'pilot/typecheck', 'pilot/canon'], function(require, exports, module) {
var checks = require("pilot/typecheck");
var canon = require('pilot/canon');
/**
* 'help' command
*/
var helpCommandSpec = {
name: 'help',
params: [
{
name: 'search',
type: 'text',
description: 'Search string to narrow the output.',
defaultValue: null
}
],
description: 'Get help on the available commands.',
exec: function(env, args, request) {
var output = [];
var command = canon.getCommand(args.search);
if (command && command.exec) {
// caught a real command
output.push(command.description ?
command.description :
'No description for ' + args.search);
} else {
var showHidden = false;
if (command) {
// We must be looking at sub-commands
output.push('<h2>Sub-Commands of ' + command.name + '</h2>');
output.push('<p>' + command.description + '</p>');
}
else if (args.search) {
if (args.search == 'hidden') { // sneaky, sneaky.
args.search = '';
showHidden = true;
}
output.push('<h2>Commands starting with \'' + args.search + '\':</h2>');
}
else {
output.push('<h2>Available Commands:</h2>');
}
var commandNames = canon.getCommandNames();
commandNames.sort();
output.push('<table>');
for (var i = 0; i < commandNames.length; i++) {
command = canon.getCommand(commandNames[i]);
if (!showHidden && command.hidden) {
continue;
}
if (command.description === undefined) {
// Ignore editor actions
continue;
}
if (args.search && command.name.indexOf(args.search) !== 0) {
// Filtered out by the user
continue;
}
if (!args.search && command.name.indexOf(' ') != -1) {
// sub command
continue;
}
if (command && command.name == args.search) {
// sub command, and we've already given that help
continue;
}
// todo add back a column with parameter information, perhaps?
output.push('<tr>');
output.push('<th class="right">' + command.name + '</th>');
output.push('<td>' + command.description + '</td>');
output.push('</tr>');
}
output.push('</table>');
}
request.done(output.join(''));
}
};
/**
* 'eval' command
*/
var evalCommandSpec = {
name: 'eval',
params: [
{
name: 'javascript',
type: 'text',
description: 'The JavaScript to evaluate'
}
],
description: 'evals given js code and show the result',
hidden: true,
exec: function(env, args, request) {
var result;
var javascript = args.javascript;
try {
result = eval(javascript);
} catch (e) {
result = '<b>Error: ' + e.message + '</b>';
}
var msg = '';
var type = '';
var x;
if (checks.isFunction(result)) {
// converts the function to a well formated string
msg = (result + '').replace(/\n/g, '<br>').replace(/ /g, ' ');
type = 'function';
} else if (checks.isObject(result)) {
if (Array.isArray(result)) {
type = 'array';
} else {
type = 'object';
}
var items = [];
var value;
for (x in result) {
if (result.hasOwnProperty(x)) {
if (checks.isFunction(result[x])) {
value = '[function]';
} else if (checks.isObject(result[x])) {
value = '[object]';
} else {
value = result[x];
}
items.push({name: x, value: value});
}
}
items.sort(function(a,b) {
return (a.name.toLowerCase() < b.name.toLowerCase()) ? -1 : 1;
});
for (x = 0; x < items.length; x++) {
msg += '<b>' + items[x].name + '</b>: ' + items[x].value + '<br>';
}
} else {
msg = result;
type = typeof result;
}
request.done('Result for eval <b>\'' + javascript + '\'</b>' +
' (type: '+ type+'): <br><br>'+ msg);
}
};
var canon = require('pilot/canon');
exports.startup = function(data, reason) {
canon.addCommand(helpCommandSpec);
canon.addCommand(evalCommandSpec);
};
exports.shutdown = function(data, reason) {
canon.removeCommand(helpCommandSpec);
canon.removeCommand(evalCommandSpec);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/settings/canon', ['require', 'exports', 'module' ], function(require, exports, module) {
var historyLengthSetting = {
name: "historyLength",
description: "How many typed commands do we recall for reference?",
type: "number",
defaultValue: 50
};
exports.startup = function(data, reason) {
data.env.settings.addSetting(historyLengthSetting);
};
exports.shutdown = function(data, reason) {
data.env.settings.removeSetting(historyLengthSetting);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/plugin_manager', ['require', 'exports', 'module' , 'pilot/promise'], function(require, exports, module) {
var Promise = require("pilot/promise").Promise;
exports.REASONS = {
APP_STARTUP: 1,
APP_SHUTDOWN: 2,
PLUGIN_ENABLE: 3,
PLUGIN_DISABLE: 4,
PLUGIN_INSTALL: 5,
PLUGIN_UNINSTALL: 6,
PLUGIN_UPGRADE: 7,
PLUGIN_DOWNGRADE: 8
};
exports.Plugin = function(name) {
this.name = name;
this.status = this.INSTALLED;
};
exports.Plugin.prototype = {
/**
* constants for the state
*/
NEW: 0,
INSTALLED: 1,
REGISTERED: 2,
STARTED: 3,
UNREGISTERED: 4,
SHUTDOWN: 5,
install: function(data, reason) {
var pr = new Promise();
if (this.status > this.NEW) {
pr.resolve(this);
return pr;
}
require([this.name], function(pluginModule) {
if (pluginModule.install) {
pluginModule.install(data, reason);
}
this.status = this.INSTALLED;
pr.resolve(this);
}.bind(this));
return pr;
},
register: function(data, reason) {
var pr = new Promise();
if (this.status != this.INSTALLED) {
pr.resolve(this);
return pr;
}
require([this.name], function(pluginModule) {
if (pluginModule.register) {
pluginModule.register(data, reason);
}
this.status = this.REGISTERED;
pr.resolve(this);
}.bind(this));
return pr;
},
startup: function(data, reason) {
reason = reason || exports.REASONS.APP_STARTUP;
var pr = new Promise();
if (this.status != this.REGISTERED) {
pr.resolve(this);
return pr;
}
require([this.name], function(pluginModule) {
if (pluginModule.startup) {
pluginModule.startup(data, reason);
}
this.status = this.STARTED;
pr.resolve(this);
}.bind(this));
return pr;
},
shutdown: function(data, reason) {
if (this.status != this.STARTED) {
return;
}
pluginModule = require(this.name);
if (pluginModule.shutdown) {
pluginModule.shutdown(data, reason);
}
}
};
exports.PluginCatalog = function() {
this.plugins = {};
};
exports.PluginCatalog.prototype = {
registerPlugins: function(pluginList, data, reason) {
var registrationPromises = [];
pluginList.forEach(function(pluginName) {
var plugin = this.plugins[pluginName];
if (plugin === undefined) {
plugin = new exports.Plugin(pluginName);
this.plugins[pluginName] = plugin;
registrationPromises.push(plugin.register(data, reason));
}
}.bind(this));
return Promise.group(registrationPromises);
},
startupPlugins: function(data, reason) {
var startupPromises = [];
for (var pluginName in this.plugins) {
var plugin = this.plugins[pluginName];
startupPromises.push(plugin.startup(data, reason));
}
return Promise.group(startupPromises);
}
};
exports.catalog = new exports.PluginCatalog();
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/promise', ['require', 'exports', 'module' , 'pilot/console', 'pilot/stacktrace'], function(require, exports, module) {
var console = require("pilot/console");
var Trace = require('pilot/stacktrace').Trace;
/**
* A promise can be in one of 2 states.
* The ERROR and SUCCESS states are terminal, the PENDING state is the only
* start state.
*/
var ERROR = -1;
var PENDING = 0;
var SUCCESS = 1;
/**
* We give promises and ID so we can track which are outstanding
*/
var _nextId = 0;
/**
* Debugging help if 2 things try to complete the same promise.
* This can be slow (especially on chrome due to the stack trace unwinding) so
* we should leave this turned off in normal use.
*/
var _traceCompletion = false;
/**
* Outstanding promises. Handy list for debugging only.
*/
var _outstanding = [];
/**
* Recently resolved promises. Also for debugging only.
*/
var _recent = [];
/**
* Create an unfulfilled promise
*/
Promise = function () {
this._status = PENDING;
this._value = undefined;
this._onSuccessHandlers = [];
this._onErrorHandlers = [];
// Debugging help
this._id = _nextId++;
//this._createTrace = new Trace(new Error());
_outstanding[this._id] = this;
};
/**
* Yeay for RTTI.
*/
Promise.prototype.isPromise = true;
/**
* Have we either been resolve()ed or reject()ed?
*/
Promise.prototype.isComplete = function() {
return this._status != PENDING;
};
/**
* Have we resolve()ed?
*/
Promise.prototype.isResolved = function() {
return this._status == SUCCESS;
};
/**
* Have we reject()ed?
*/
Promise.prototype.isRejected = function() {
return this._status == ERROR;
};
/**
* Take the specified action of fulfillment of a promise, and (optionally)
* a different action on promise rejection.
*/
Promise.prototype.then = function(onSuccess, onError) {
if (typeof onSuccess === 'function') {
if (this._status === SUCCESS) {
onSuccess.call(null, this._value);
} else if (this._status === PENDING) {
this._onSuccessHandlers.push(onSuccess);
}
}
if (typeof onError === 'function') {
if (this._status === ERROR) {
onError.call(null, this._value);
} else if (this._status === PENDING) {
this._onErrorHandlers.push(onError);
}
}
return this;
};
/**
* Like then() except that rather than returning <tt>this</tt> we return
* a promise which
*/
Promise.prototype.chainPromise = function(onSuccess) {
var chain = new Promise();
chain._chainedFrom = this;
this.then(function(data) {
try {
chain.resolve(onSuccess(data));
} catch (ex) {
chain.reject(ex);
}
}, function(ex) {
chain.reject(ex);
});
return chain;
};
/**
* Supply the fulfillment of a promise
*/
Promise.prototype.resolve = function(data) {
return this._complete(this._onSuccessHandlers, SUCCESS, data, 'resolve');
};
/**
* Renege on a promise
*/
Promise.prototype.reject = function(data) {
return this._complete(this._onErrorHandlers, ERROR, data, 'reject');
};
/**
* Internal method to be called on resolve() or reject().
* @private
*/
Promise.prototype._complete = function(list, status, data, name) {
// Complain if we've already been completed
if (this._status != PENDING) {
console.group('Promise already closed');
console.error('Attempted ' + name + '() with ', data);
console.error('Previous status = ', this._status,
', previous value = ', this._value);
console.trace();
if (this._completeTrace) {
console.error('Trace of previous completion:');
this._completeTrace.log(5);
}
console.groupEnd();
return this;
}
if (_traceCompletion) {
this._completeTrace = new Trace(new Error());
}
this._status = status;
this._value = data;
// Call all the handlers, and then delete them
list.forEach(function(handler) {
handler.call(null, this._value);
}, this);
this._onSuccessHandlers.length = 0;
this._onErrorHandlers.length = 0;
// Remove the given {promise} from the _outstanding list, and add it to the
// _recent list, pruning more than 20 recent promises from that list.
delete _outstanding[this._id];
_recent.push(this);
while (_recent.length > 20) {
_recent.shift();
}
return this;
};
/**
* Takes an array of promises and returns a promise that that is fulfilled once
* all the promises in the array are fulfilled
* @param group The array of promises
* @return the promise that is fulfilled when all the array is fulfilled
*/
Promise.group = function(promiseList) {
if (!(promiseList instanceof Array)) {
promiseList = Array.prototype.slice.call(arguments);
}
// If the original array has nothing in it, return now to avoid waiting
if (promiseList.length === 0) {
return new Promise().resolve([]);
}
var groupPromise = new Promise();
var results = [];
var fulfilled = 0;
var onSuccessFactory = function(index) {
return function(data) {
results[index] = data;
fulfilled++;
// If the group has already failed, silently drop extra results
if (groupPromise._status !== ERROR) {
if (fulfilled === promiseList.length) {
groupPromise.resolve(results);
}
}
};
};
promiseList.forEach(function(promise, index) {
var onSuccess = onSuccessFactory(index);
var onError = groupPromise.reject.bind(groupPromise);
promise.then(onSuccess, onError);
});
return groupPromise;
};
exports.Promise = Promise;
exports._outstanding = _outstanding;
exports._recent = _recent;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai AT sucan AT gmail ODT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/dom', ['require', 'exports', 'module' ], function(require, exports, module) {
var XHTML_NS = "http://www.w3.org/1999/xhtml";
exports.createElement = function(tag, ns) {
return document.createElementNS ?
document.createElementNS(ns || XHTML_NS, tag) :
document.createElement(tag);
};
exports.setText = function(elem, text) {
if (elem.innerText !== undefined) {
elem.innerText = text;
}
if (elem.textContent !== undefined) {
elem.textContent = text;
}
};
if (!document.documentElement.classList) {
exports.hasCssClass = function(el, name) {
var classes = el.className.split(/\s+/g);
return classes.indexOf(name) !== -1;
};
/**
* Add a CSS class to the list of classes on the given node
*/
exports.addCssClass = function(el, name) {
if (!exports.hasCssClass(el, name)) {
el.className += " " + name;
}
};
/**
* Remove a CSS class from the list of classes on the given node
*/
exports.removeCssClass = function(el, name) {
var classes = el.className.split(/\s+/g);
while (true) {
var index = classes.indexOf(name);
if (index == -1) {
break;
}
classes.splice(index, 1);
}
el.className = classes.join(" ");
};
exports.toggleCssClass = function(el, name) {
var classes = el.className.split(/\s+/g), add = true;
while (true) {
var index = classes.indexOf(name);
if (index == -1) {
break;
}
add = false;
classes.splice(index, 1);
}
if(add)
classes.push(name);
el.className = classes.join(" ");
return add;
};
} else {
exports.hasCssClass = function(el, name) {
return el.classList.contains(name);
};
exports.addCssClass = function(el, name) {
el.classList.add(name);
};
exports.removeCssClass = function(el, name) {
el.classList.remove(name);
};
exports.toggleCssClass = function(el, name) {
return el.classList.toggle(name);
};
}
/**
* Add or remove a CSS class from the list of classes on the given node
* depending on the value of <tt>include</tt>
*/
exports.setCssClass = function(node, className, include) {
if (include) {
exports.addCssClass(node, className);
} else {
exports.removeCssClass(node, className);
}
};
exports.importCssString = function(cssText, doc){
doc = doc || document;
if (doc.createStyleSheet) {
var sheet = doc.createStyleSheet();
sheet.cssText = cssText;
}
else {
var style = doc.createElementNS ?
doc.createElementNS(XHTML_NS, "style") :
doc.createElement("style");
style.appendChild(doc.createTextNode(cssText));
var head = doc.getElementsByTagName("head")[0] || doc.documentElement;
head.appendChild(style);
}
};
exports.getInnerWidth = function(element) {
return (parseInt(exports.computedStyle(element, "paddingLeft"))
+ parseInt(exports.computedStyle(element, "paddingRight")) + element.clientWidth);
};
exports.getInnerHeight = function(element) {
return (parseInt(exports.computedStyle(element, "paddingTop"))
+ parseInt(exports.computedStyle(element, "paddingBottom")) + element.clientHeight);
};
if (window.pageYOffset !== undefined) {
exports.getPageScrollTop = function() {
return window.pageYOffset;
};
exports.getPageScrollLeft = function() {
return window.pageXOffset;
};
}
else {
exports.getPageScrollTop = function() {
return document.body.scrollTop;
};
exports.getPageScrollLeft = function() {
return document.body.scrollLeft;
};
}
if (window.getComputedStyle)
exports.computedStyle = function(element, style) {
if (style)
return (window.getComputedStyle(element, "") || {})[style] || "";
return window.getComputedStyle(element, "") || {}
};
else
exports.computedStyle = function(element, style) {
if (style)
return element.currentStyle[style];
return element.currentStyle
};
exports.scrollbarWidth = function() {
var inner = exports.createElement("p");
inner.style.width = "100%";
inner.style.minWidth = "0px";
inner.style.height = "200px";
var outer = exports.createElement("div");
var style = outer.style;
style.position = "absolute";
style.left = "-10000px";
style.overflow = "hidden";
style.width = "200px";
style.minWidth = "0px";
style.height = "150px";
outer.appendChild(inner);
var body = document.body || document.documentElement;
body.appendChild(outer);
var noScrollbar = inner.offsetWidth;
style.overflow = "scroll";
var withScrollbar = inner.offsetWidth;
if (noScrollbar == withScrollbar) {
withScrollbar = outer.clientWidth;
}
body.removeChild(outer);
return noScrollbar-withScrollbar;
};
/**
* Optimized set innerHTML. This is faster than plain innerHTML if the element
* already contains a lot of child elements.
*
* See http://blog.stevenlevithan.com/archives/faster-than-innerhtml for details
*/
exports.setInnerHtml = function(el, innerHtml) {
var element = el.cloneNode(false);//document.createElement("div");
element.innerHTML = innerHtml;
el.parentNode.replaceChild(element, el);
return element;
};
exports.setInnerText = function(el, innerText) {
if (document.body && "textContent" in document.body)
el.textContent = innerText;
else
el.innerText = innerText;
};
exports.getInnerText = function(el) {
if (document.body && "textContent" in document.body)
return el.textContent;
else
return el.innerText || el.textContent || "";
};
exports.getParentWindow = function(document) {
return document.defaultView || document.parentWindow;
};
exports.getSelectionStart = function(textarea) {
// TODO IE
var start;
try {
start = textarea.selectionStart || 0;
} catch (e) {
start = 0;
}
return start;
};
exports.setSelectionStart = function(textarea, start) {
// TODO IE
return textarea.selectionStart = start;
};
exports.getSelectionEnd = function(textarea) {
// TODO IE
var end;
try {
end = textarea.selectionEnd || 0;
} catch (e) {
end = 0;
}
return end;
};
exports.setSelectionEnd = function(textarea, end) {
// TODO IE
return textarea.selectionEnd = end;
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/event', ['require', 'exports', 'module' , 'pilot/keys', 'pilot/useragent', 'pilot/dom'], function(require, exports, module) {
var keys = require("pilot/keys");
var useragent = require("pilot/useragent");
var dom = require("pilot/dom");
exports.addListener = function(elem, type, callback) {
if (elem.addEventListener) {
return elem.addEventListener(type, callback, false);
}
if (elem.attachEvent) {
var wrapper = function() {
callback(window.event);
};
callback._wrapper = wrapper;
elem.attachEvent("on" + type, wrapper);
}
};
exports.removeListener = function(elem, type, callback) {
if (elem.removeEventListener) {
return elem.removeEventListener(type, callback, false);
}
if (elem.detachEvent) {
elem.detachEvent("on" + type, callback._wrapper || callback);
}
};
/**
* Prevents propagation and clobbers the default action of the passed event
*/
exports.stopEvent = function(e) {
exports.stopPropagation(e);
exports.preventDefault(e);
return false;
};
exports.stopPropagation = function(e) {
if (e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
};
exports.preventDefault = function(e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
};
exports.getDocumentX = function(e) {
if (e.clientX) {
return e.clientX + dom.getPageScrollLeft();
} else {
return e.pageX;
}
};
exports.getDocumentY = function(e) {
if (e.clientY) {
return e.clientY + dom.getPageScrollTop();
} else {
return e.pageY;
}
};
/**
* @return {Number} 0 for left button, 1 for middle button, 2 for right button
*/
exports.getButton = function(e) {
if (e.type == "dblclick")
return 0;
else if (e.type == "contextmenu")
return 2;
// DOM Event
if (e.preventDefault) {
return e.button;
}
// old IE
else {
return {1:0, 2:2, 4:1}[e.button];
}
};
if (document.documentElement.setCapture) {
exports.capture = function(el, eventHandler, releaseCaptureHandler) {
function onMouseMove(e) {
eventHandler(e);
return exports.stopPropagation(e);
}
function onReleaseCapture(e) {
eventHandler && eventHandler(e);
releaseCaptureHandler && releaseCaptureHandler();
exports.removeListener(el, "mousemove", eventHandler);
exports.removeListener(el, "mouseup", onReleaseCapture);
exports.removeListener(el, "losecapture", onReleaseCapture);
el.releaseCapture();
}
exports.addListener(el, "mousemove", eventHandler);
exports.addListener(el, "mouseup", onReleaseCapture);
exports.addListener(el, "losecapture", onReleaseCapture);
el.setCapture();
};
}
else {
exports.capture = function(el, eventHandler, releaseCaptureHandler) {
function onMouseMove(e) {
eventHandler(e);
e.stopPropagation();
}
function onMouseUp(e) {
eventHandler && eventHandler(e);
releaseCaptureHandler && releaseCaptureHandler();
document.removeEventListener("mousemove", onMouseMove, true);
document.removeEventListener("mouseup", onMouseUp, true);
e.stopPropagation();
}
document.addEventListener("mousemove", onMouseMove, true);
document.addEventListener("mouseup", onMouseUp, true);
};
}
exports.addMouseWheelListener = function(el, callback) {
var listener = function(e) {
if (e.wheelDelta !== undefined) {
if (e.wheelDeltaX !== undefined) {
e.wheelX = -e.wheelDeltaX / 8;
e.wheelY = -e.wheelDeltaY / 8;
} else {
e.wheelX = 0;
e.wheelY = -e.wheelDelta / 8;
}
}
else {
if (e.axis && e.axis == e.HORIZONTAL_AXIS) {
e.wheelX = (e.detail || 0) * 5;
e.wheelY = 0;
} else {
e.wheelX = 0;
e.wheelY = (e.detail || 0) * 5;
}
}
callback(e);
};
exports.addListener(el, "DOMMouseScroll", listener);
exports.addListener(el, "mousewheel", listener);
};
exports.addMultiMouseDownListener = function(el, button, count, timeout, callback) {
var clicks = 0;
var startX, startY;
var listener = function(e) {
clicks += 1;
if (clicks == 1) {
startX = e.clientX;
startY = e.clientY;
setTimeout(function() {
clicks = 0;
}, timeout || 600);
}
var isButton = exports.getButton(e) == button;
if (!isButton || Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5)
clicks = 0;
if (clicks == count) {
clicks = 0;
callback(e);
}
if (isButton)
return exports.preventDefault(e);
};
exports.addListener(el, "mousedown", listener);
useragent.isIE && exports.addListener(el, "dblclick", listener);
};
function normalizeCommandKeys(callback, e, keyCode) {
var hashId = 0;
if (useragent.isOpera && useragent.isMac) {
hashId = 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0)
| (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0);
} else {
hashId = 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0)
| (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0);
}
if (keyCode in keys.MODIFIER_KEYS) {
switch (keys.MODIFIER_KEYS[keyCode]) {
case "Alt":
hashId = 2;
break;
case "Shift":
hashId = 4;
break
case "Ctrl":
hashId = 1;
break;
default:
hashId = 8;
break;
}
keyCode = 0;
}
if (hashId & 8 && (keyCode == 91 || keyCode == 93)) {
keyCode = 0;
}
// If there is no hashID and the keyCode is not a function key, then
// we don't call the callback as we don't handle a command key here
// (it's a normal key/character input).
if (hashId == 0 && !(keyCode in keys.FUNCTION_KEYS)) {
return false;
}
return callback(e, hashId, keyCode);
}
exports.addCommandKeyListener = function(el, callback) {
var addListener = exports.addListener;
if (useragent.isOldGecko) {
// Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown
// event if the user pressed the key for a longer time. Instead, the
// keydown event was fired once and later on only the keypress event.
// To emulate the 'right' keydown behavior, the keyCode of the initial
// keyDown event is stored and in the following keypress events the
// stores keyCode is used to emulate a keyDown event.
var lastKeyDownKeyCode = null;
addListener(el, "keydown", function(e) {
lastKeyDownKeyCode = e.keyCode;
});
addListener(el, "keypress", function(e) {
return normalizeCommandKeys(callback, e, lastKeyDownKeyCode);
});
} else {
var lastDown = null;
addListener(el, "keydown", function(e) {
lastDown = e.keyIdentifier || e.keyCode;
return normalizeCommandKeys(callback, e, e.keyCode);
});
// repeated keys are fired as keypress and not keydown events
if (useragent.isMac && useragent.isOpera) {
addListener(el, "keypress", function(e) {
var keyId = e.keyIdentifier || e.keyCode;
if (lastDown !== keyId) {
return normalizeCommandKeys(callback, e, e.keyCode);
} else {
lastDown = null;
}
});
}
}
};
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/editor', ['require', 'exports', 'module' , 'pilot/fixoldbrowsers', 'pilot/oop', 'pilot/event', 'pilot/lang', 'pilot/useragent', 'ace/keyboard/textinput', 'ace/mouse_handler', 'ace/keyboard/keybinding', 'ace/edit_session', 'ace/search', 'ace/range', 'pilot/event_emitter'], function(require, exports, module) {
require("pilot/fixoldbrowsers");
var oop = require("pilot/oop");
var event = require("pilot/event");
var lang = require("pilot/lang");
var useragent = require("pilot/useragent");
var TextInput = require("ace/keyboard/textinput").TextInput;
var MouseHandler = require("ace/mouse_handler").MouseHandler;
//var TouchHandler = require("ace/touch_handler").TouchHandler;
var KeyBinding = require("ace/keyboard/keybinding").KeyBinding;
var EditSession = require("ace/edit_session").EditSession;
var Search = require("ace/search").Search;
var Range = require("ace/range").Range;
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Editor =function(renderer, session) {
var container = renderer.getContainerElement();
this.container = container;
this.renderer = renderer;
this.textInput = new TextInput(renderer.getTextAreaContainer(), this);
this.keyBinding = new KeyBinding(this);
// TODO detect touch event support
if (useragent.isIPad) {
//this.$mouseHandler = new TouchHandler(this);
} else {
this.$mouseHandler = new MouseHandler(this);
}
this.$blockScrolling = 0;
this.$search = new Search().set({
wrap: true
});
this.setSession(session || new EditSession(""));
};
(function(){
oop.implement(this, EventEmitter);
this.$forwardEvents = {
gutterclick: 1,
gutterdblclick: 1
};
this.$originalAddEventListener = this.addEventListener;
this.$originalRemoveEventListener = this.removeEventListener;
this.addEventListener = function(eventName, callback) {
if (this.$forwardEvents[eventName]) {
return this.renderer.addEventListener(eventName, callback);
} else {
return this.$originalAddEventListener(eventName, callback);
}
};
this.removeEventListener = function(eventName, callback) {
if (this.$forwardEvents[eventName]) {
return this.renderer.removeEventListener(eventName, callback);
} else {
return this.$originalRemoveEventListener(eventName, callback);
}
};
this.setKeyboardHandler = function(keyboardHandler) {
this.keyBinding.setKeyboardHandler(keyboardHandler);
};
this.getKeyboardHandler = function() {
return this.keyBinding.getKeyboardHandler();
};
this.setSession = function(session) {
if (this.session == session)
return;
if (this.session) {
var oldSession = this.session;
this.session.removeEventListener("change", this.$onDocumentChange);
this.session.removeEventListener("changeMode", this.$onChangeMode);
this.session.removeEventListener("tokenizerUpdate", this.$onTokenizerUpdate);
this.session.removeEventListener("changeTabSize", this.$onChangeTabSize);
this.session.removeEventListener("changeWrapLimit", this.$onChangeWrapLimit);
this.session.removeEventListener("changeWrapMode", this.$onChangeWrapMode);
this.session.removeEventListener("onChangeFold", this.$onChangeFold);
this.session.removeEventListener("changeFrontMarker", this.$onChangeFrontMarker);
this.session.removeEventListener("changeBackMarker", this.$onChangeBackMarker);
this.session.removeEventListener("changeBreakpoint", this.$onChangeBreakpoint);
this.session.removeEventListener("changeAnnotation", this.$onChangeAnnotation);
this.session.removeEventListener("changeOverwrite", this.$onCursorChange);
var selection = this.session.getSelection();
selection.removeEventListener("changeCursor", this.$onCursorChange);
selection.removeEventListener("changeSelection", this.$onSelectionChange);
this.session.setScrollTopRow(this.renderer.getScrollTopRow());
}
this.session = session;
this.$onDocumentChange = this.onDocumentChange.bind(this);
session.addEventListener("change", this.$onDocumentChange);
this.renderer.setSession(session);
this.$onChangeMode = this.onChangeMode.bind(this);
session.addEventListener("changeMode", this.$onChangeMode);
this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
session.addEventListener("tokenizerUpdate", this.$onTokenizerUpdate);
this.$onChangeTabSize = this.renderer.updateText.bind(this.renderer);
session.addEventListener("changeTabSize", this.$onChangeTabSize);
this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
session.addEventListener("changeWrapLimit", this.$onChangeWrapLimit);
this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
session.addEventListener("changeWrapMode", this.$onChangeWrapMode);
this.$onChangeFold = this.onChangeFold.bind(this);
session.addEventListener("changeFold", this.$onChangeFold);
this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
this.session.addEventListener("changeFrontMarker", this.$onChangeFrontMarker);
this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
this.session.addEventListener("changeBackMarker", this.$onChangeBackMarker);
this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
this.session.addEventListener("changeBreakpoint", this.$onChangeBreakpoint);
this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
this.session.addEventListener("changeAnnotation", this.$onChangeAnnotation);
this.$onCursorChange = this.onCursorChange.bind(this);
this.session.addEventListener("changeOverwrite", this.$onCursorChange);
this.selection = session.getSelection();
this.selection.addEventListener("changeCursor", this.$onCursorChange);
this.$onSelectionChange = this.onSelectionChange.bind(this);
this.selection.addEventListener("changeSelection", this.$onSelectionChange);
this.onChangeMode();
this.onCursorChange();
this.onSelectionChange();
this.onChangeFrontMarker();
this.onChangeBackMarker();
this.onChangeBreakpoint();
this.onChangeAnnotation();
this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
this.renderer.scrollToRow(session.getScrollTopRow());
this.renderer.updateFull();
this._dispatchEvent("changeSession", {
session: session,
oldSession: oldSession
});
};
this.getSession = function() {
return this.session;
};
this.getSelection = function() {
return this.selection;
};
this.resize = function() {
this.renderer.onResize();
};
this.setTheme = function(theme) {
this.renderer.setTheme(theme);
};
this.getTheme = function() {
return this.renderer.getTheme();
};
this.setStyle = function(style) {
this.renderer.setStyle(style);
};
this.unsetStyle = function(style) {
this.renderer.unsetStyle(style);
};
this.setFontSize = function(size) {
this.container.style.fontSize = size;
};
this.$highlightBrackets = function() {
if (this.session.$bracketHighlight) {
this.session.removeMarker(this.session.$bracketHighlight);
this.session.$bracketHighlight = null;
}
if (this.$highlightPending) {
return;
}
// perform highlight async to not block the browser during navigation
var self = this;
this.$highlightPending = true;
setTimeout(function() {
self.$highlightPending = false;
var pos = self.session.findMatchingBracket(self.getCursorPosition());
if (pos) {
var range = new Range(pos.row, pos.column, pos.row, pos.column+1);
self.session.$bracketHighlight = self.session.addMarker(range, "ace_bracket", "text");
}
}, 10);
};
this.focus = function() {
// Safari needs the timeout
// iOS and Firefox need it called immediately
// to be on the save side we do both
// except for IE
var _self = this;
if (!useragent.isIE) {
setTimeout(function() {
_self.textInput.focus();
});
}
this.textInput.focus();
};
this.isFocused = function() {
return this.textInput.isFocused();
};
this.blur = function() {
this.textInput.blur();
};
this.onFocus = function() {
this.renderer.showCursor();
this.renderer.visualizeFocus();
this._dispatchEvent("focus");
};
this.onBlur = function() {
this.renderer.hideCursor();
this.renderer.visualizeBlur();
this._dispatchEvent("blur");
};
this.onDocumentChange = function(e) {
var delta = e.data;
var range = delta.range;
if (range.start.row == range.end.row && delta.action != "insertLines" && delta.action != "removeLines")
var lastRow = range.end.row;
else
lastRow = Infinity;
this.renderer.updateLines(range.start.row, lastRow);
// update cursor because tab characters can influence the cursor position
this.renderer.updateCursor();
};
this.onTokenizerUpdate = function(e) {
var rows = e.data;
this.renderer.updateLines(rows.first, rows.last);
};
this.onCursorChange = function(e) {
this.renderer.updateCursor();
if (!this.$blockScrolling) {
this.renderer.scrollCursorIntoView();
}
// move text input over the cursor
// this is required for iOS and IME
this.renderer.moveTextAreaToCursor(this.textInput.getElement());
this.$highlightBrackets();
this.$updateHighlightActiveLine();
};
this.$updateHighlightActiveLine = function() {
var session = this.getSession();
if (session.$highlightLineMarker) {
session.removeMarker(session.$highlightLineMarker);
}
session.$highlightLineMarker = null;
if (this.getHighlightActiveLine() && (this.getSelectionStyle() != "line" || !this.selection.isMultiLine())) {
var cursor = this.getCursorPosition(),
foldLine = this.session.getFoldLine(cursor.row);
var range;
if (foldLine) {
range = new Range(foldLine.start.row, 0, foldLine.end.row + 1, 0);
} else {
range = new Range(cursor.row, 0, cursor.row+1, 0);
}
session.$highlightLineMarker = session.addMarker(range, "ace_active_line", "background");
}
};
this.onSelectionChange = function(e) {
var session = this.getSession();
if (session.$selectionMarker) {
session.removeMarker(session.$selectionMarker);
}
session.$selectionMarker = null;
if (!this.selection.isEmpty()) {
var range = this.selection.getRange();
var style = this.getSelectionStyle();
session.$selectionMarker = session.addMarker(range, "ace_selection", style);
} else {
this.$updateHighlightActiveLine();
}
if (this.$highlightSelectedWord)
this.session.getMode().highlightSelection(this);
};
this.onChangeFrontMarker = function() {
this.renderer.updateFrontMarkers();
};
this.onChangeBackMarker = function() {
this.renderer.updateBackMarkers();
};
this.onChangeBreakpoint = function() {
this.renderer.setBreakpoints(this.session.getBreakpoints());
};
this.onChangeAnnotation = function() {
this.renderer.setAnnotations(this.session.getAnnotations());
};
this.onChangeMode = function() {
this.renderer.updateText()
};
this.onChangeWrapLimit = function() {
this.renderer.updateFull();
};
this.onChangeWrapMode = function() {
this.renderer.onResize(true);
};
this.onChangeFold = function() {
// Update the active line marker as due to folding changes the current
// line range on the screen might have changed.
this.$updateHighlightActiveLine();
// TODO: This might be too much updating. Okay for now.
this.renderer.updateFull();
};
this.getCopyText = function() {
if (!this.selection.isEmpty()) {
return this.session.getTextRange(this.getSelectionRange());
}
else {
return "";
}
};
this.onCut = function() {
if (this.$readOnly)
return;
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange())
this.clearSelection();
}
};
this.insert = function(text) {
if (this.$readOnly)
return;
var session = this.session;
var mode = session.getMode();
var cursor = this.getCursorPosition();
if (this.getBehavioursEnabled()) {
// Get a transform if the current mode wants one.
var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
if (transform)
text = transform.text;
}
text = text.replace("\t", this.session.getTabString());
// remove selected text
if (!this.selection.isEmpty()) {
var cursor = this.session.remove(this.getSelectionRange());
this.clearSelection();
}
else if (this.session.getOverwrite()) {
var range = new Range.fromPoints(cursor, cursor);
range.end.column += text.length;
this.session.remove(range);
}
this.clearSelection();
var start = cursor.column;
var lineState = session.getState(cursor.row);
var shouldOutdent = mode.checkOutdent(lineState, session.getLine(cursor.row), text);
var line = session.getLine(cursor.row);
var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
var end = session.insert(cursor, text);
if (transform && transform.selection) {
if (transform.selection.length == 2) { // Transform relative to the current column
this.selection.setSelectionRange(
new Range(cursor.row, start + transform.selection[0],
cursor.row, start + transform.selection[1]));
} else { // Transform relative to the current row.
this.selection.setSelectionRange(
new Range(cursor.row + transform.selection[0],
transform.selection[1],
cursor.row + transform.selection[2],
transform.selection[3]));
}
}
var lineState = session.getState(cursor.row);
// TODO disabled multiline auto indent
// possibly doing the indent before inserting the text
// if (cursor.row !== end.row) {
if (session.getDocument().isNewLine(text)) {
this.moveCursorTo(cursor.row+1, 0);
var size = session.getTabSize();
var minIndent = Number.MAX_VALUE;
for (var row = cursor.row + 1; row <= end.row; ++row) {
var indent = 0;
line = session.getLine(row);
for (var i = 0; i < line.length; ++i)
if (line.charAt(i) == '\t')
indent += size;
else if (line.charAt(i) == ' ')
indent += 1;
else
break;
if (/[^\s]/.test(line))
minIndent = Math.min(indent, minIndent);
}
for (var row = cursor.row + 1; row <= end.row; ++row) {
var outdent = minIndent;
line = session.getLine(row);
for (var i = 0; i < line.length && outdent > 0; ++i)
if (line.charAt(i) == '\t')
outdent -= size;
else if (line.charAt(i) == ' ')
outdent -= 1;
session.remove(new Range(row, 0, row, i));
}
session.indentRows(cursor.row + 1, end.row, lineIndent);
} else {
if (shouldOutdent) {
mode.autoOutdent(lineState, session, cursor.row);
}
}
};
this.onTextInput = function(text, notPasted) {
// In case the text was not pasted and we got only one character, then
// handel it as a command key stroke.
if (notPasted && text.length == 1) {
// Note: The `null` as `keyCode` is important here, as there are
// some checks in the code for `keyCode == 0` meaning the text comes
// from the keyBinding.onTextInput code path.
var handled = this.keyBinding.onCommandKey({}, 0, null, text);
// Check if the text was handled. If not, then handled it as "normal"
// text and insert it to the editor directly. This shouldn't be done
// using the this.keyBinding.onTextInput(text) function, as it would
// make the `text` get sent to the keyboardHandler twice, which might
// turn out to be a bad thing in case there is a custome keyboard
// handler like the StateHandler.
if (!handled) {
this.insert(text);
}
} else {
this.keyBinding.onTextInput(text);
}
};
this.onCommandKey = function(e, hashId, keyCode) {
this.keyBinding.onCommandKey(e, hashId, keyCode);
};
this.setOverwrite = function(overwrite) {
this.session.setOverwrite(overwrite);
};
this.getOverwrite = function() {
return this.session.getOverwrite();
};
this.toggleOverwrite = function() {
this.session.toggleOverwrite();
};
this.setScrollSpeed = function(speed) {
this.$mouseHandler.setScrollSpeed(speed);
};
this.getScrollSpeed = function() {
return this.$mouseHandler.getScrollSpeed()
};
this.$selectionStyle = "line";
this.setSelectionStyle = function(style) {
if (this.$selectionStyle == style) return;
this.$selectionStyle = style;
this.onSelectionChange();
this._dispatchEvent("changeSelectionStyle", {data: style});
};
this.getSelectionStyle = function() {
return this.$selectionStyle;
};
this.$highlightActiveLine = true;
this.setHighlightActiveLine = function(shouldHighlight) {
if (this.$highlightActiveLine == shouldHighlight) return;
this.$highlightActiveLine = shouldHighlight;
this.$updateHighlightActiveLine();
};
this.getHighlightActiveLine = function() {
return this.$highlightActiveLine;
};
this.$highlightSelectedWord = true;
this.setHighlightSelectedWord = function(shouldHighlight) {
if (this.$highlightSelectedWord == shouldHighlight)
return;
this.$highlightSelectedWord = shouldHighlight;
if (shouldHighlight)
this.session.getMode().highlightSelection(this);
else
this.session.getMode().clearSelectionHighlight(this);
};
this.getHighlightSelectedWord = function() {
return this.$highlightSelectedWord;
};
this.setShowInvisibles = function(showInvisibles) {
if (this.getShowInvisibles() == showInvisibles)
return;
this.renderer.setShowInvisibles(showInvisibles);
};
this.getShowInvisibles = function() {
return this.renderer.getShowInvisibles();
};
this.setShowPrintMargin = function(showPrintMargin) {
this.renderer.setShowPrintMargin(showPrintMargin);
};
this.getShowPrintMargin = function() {
return this.renderer.getShowPrintMargin();
};
this.setPrintMarginColumn = function(showPrintMargin) {
this.renderer.setPrintMarginColumn(showPrintMargin);
};
this.getPrintMarginColumn = function() {
return this.renderer.getPrintMarginColumn();
};
this.$readOnly = false;
this.setReadOnly = function(readOnly) {
this.$readOnly = readOnly;
};
this.getReadOnly = function() {
return this.$readOnly;
};
this.$modeBehaviours = true;
this.setBehavioursEnabled = function (enabled) {
this.$modeBehaviours = enabled;
}
this.getBehavioursEnabled = function () {
return this.$modeBehaviours;
}
this.removeRight = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty()) {
this.selection.selectRight();
}
this.session.remove(this.getSelectionRange())
this.clearSelection();
};
this.removeLeft = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectLeft();
var range = this.getSelectionRange();
if (this.getBehavioursEnabled()) {
var session = this.session;
var state = session.getState(range.start.row);
var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
if (new_range !== false) {
range = new_range;
}
}
this.session.remove(range);
this.clearSelection();
};
this.removeWordRight = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectWordRight();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeWordLeft = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectWordLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeToLineStart = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectLineStart();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeToLineEnd = function() {
if (this.$readOnly)
return;
if (this.selection.isEmpty())
this.selection.selectLineEnd();
var range = this.getSelectionRange();
if (range.start.column == range.end.column && range.start.row == range.end.row) {
range.end.column = 0;
range.end.row++;
}
this.session.remove(range);
this.clearSelection();
};
this.splitLine = function() {
if (this.$readOnly)
return;
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
var cursor = this.getCursorPosition();
this.insert("\n");
this.moveCursorToPosition(cursor);
};
this.transposeLetters = function() {
if (this.$readOnly)
return;
if (!this.selection.isEmpty()) {
return;
}
var cursor = this.getCursorPosition();
var column = cursor.column;
if (column == 0)
return;
var line = this.session.getLine(cursor.row);
if (column < line.length) {
var swap = line.charAt(column) + line.charAt(column-1);
var range = new Range(cursor.row, column-1, cursor.row, column+1)
}
else {
var swap = line.charAt(column-1) + line.charAt(column-2);
var range = new Range(cursor.row, column-2, cursor.row, column)
}
this.session.replace(range, swap);
};
this.indent = function() {
if (this.$readOnly)
return;
var session = this.session;
var range = this.getSelectionRange();
if (range.start.row < range.end.row || range.start.column < range.end.column) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
} else {
var indentString;
if (this.session.getUseSoftTabs()) {
var size = session.getTabSize(),
position = this.getCursorPosition(),
column = session.documentToScreenColumn(position.row, position.column),
count = (size - column % size);
indentString = lang.stringRepeat(" ", count);
} else
indentString = "\t";
return this.onTextInput(indentString);
}
};
this.blockOutdent = function() {
if (this.$readOnly)
return;
var selection = this.session.getSelection();
this.session.outdentRows(selection.getRange());
};
this.toggleCommentLines = function() {
if (this.$readOnly)
return;
var state = this.session.getState(this.getCursorPosition().row);
var rows = this.$getSelectedRows()
this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
};
this.removeLines = function() {
if (this.$readOnly)
return;
var rows = this.$getSelectedRows();
if (rows.last == 0 || rows.last+1 < this.session.getLength())
var range = new Range(rows.first, 0, rows.last+1, 0)
else
var range = new Range(
rows.first-1, this.session.getLine(rows.first).length,
rows.last, this.session.getLine(rows.last).length
);
this.session.remove(range);
this.clearSelection();
};
this.moveLinesDown = function() {
if (this.$readOnly)
return;
this.$moveLines(function(firstRow, lastRow) {
return this.session.moveLinesDown(firstRow, lastRow);
});
};
this.moveLinesUp = function() {
if (this.$readOnly)
return;
this.$moveLines(function(firstRow, lastRow) {
return this.session.moveLinesUp(firstRow, lastRow);
});
};
this.moveText = function(range, toPosition) {
if (this.$readOnly)
return null;
return this.session.moveText(range, toPosition);
};
this.copyLinesUp = function() {
if (this.$readOnly)
return;
this.$moveLines(function(firstRow, lastRow) {
this.session.duplicateLines(firstRow, lastRow);
return 0;
});
};
this.copyLinesDown = function() {
if (this.$readOnly)
return;
this.$moveLines(function(firstRow, lastRow) {
return this.session.duplicateLines(firstRow, lastRow);
});
};
this.$moveLines = function(mover) {
var rows = this.$getSelectedRows();
var linesMoved = mover.call(this, rows.first, rows.last);
var selection = this.selection;
selection.setSelectionAnchor(rows.last+linesMoved+1, 0);
selection.$moveSelection(function() {
selection.moveCursorTo(rows.first+linesMoved, 0);
});
};
this.$getSelectedRows = function() {
var range = this.getSelectionRange().collapseRows();
return {
first: range.start.row,
last: range.end.row
};
};
this.onCompositionStart = function(text) {
this.renderer.showComposition(this.getCursorPosition());
};
this.onCompositionUpdate = function(text) {
this.renderer.setCompositionText(text);
};
this.onCompositionEnd = function() {
this.renderer.hideComposition();
};
this.getFirstVisibleRow = function() {
return this.renderer.getFirstVisibleRow();
};
this.getLastVisibleRow = function() {
return this.renderer.getLastVisibleRow();
};
this.isRowVisible = function(row) {
return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow());
};
this.$getVisibleRowCount = function() {
return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1;
};
this.$getPageDownRow = function() {
return this.renderer.getScrollBottomRow();
};
this.$getPageUpRow = function() {
var firstRow = this.renderer.getScrollTopRow();
var lastRow = this.renderer.getScrollBottomRow();
return firstRow - (lastRow - firstRow);
};
this.selectPageDown = function() {
var row = this.$getPageDownRow() + Math.floor(this.$getVisibleRowCount() / 2);
this.scrollPageDown();
var selection = this.getSelection();
var leadScreenPos = this.session.documentToScreenPosition(selection.getSelectionLead());
var dest = this.session.screenToDocumentPosition(row, leadScreenPos.column);
selection.selectTo(dest.row, dest.column);
};
this.selectPageUp = function() {
var visibleRows = this.renderer.getScrollTopRow() - this.renderer.getScrollBottomRow();
var row = this.$getPageUpRow() + Math.round(visibleRows / 2);
this.scrollPageUp();
var selection = this.getSelection();
var leadScreenPos = this.session.documentToScreenPosition(selection.getSelectionLead());
var dest = this.session.screenToDocumentPosition(row, leadScreenPos.column);
selection.selectTo(dest.row, dest.column);
};
this.gotoPageDown = function() {
var row = this.$getPageDownRow();
var column = this.getCursorPositionScreen().column;
this.scrollToRow(row);
this.getSelection().moveCursorToScreen(row, column);
};
this.gotoPageUp = function() {
var row = this.$getPageUpRow();
var column = this.getCursorPositionScreen().column;
this.scrollToRow(row);
this.getSelection().moveCursorToScreen(row, column);
};
this.scrollPageDown = function() {
this.scrollToRow(this.$getPageDownRow());
};
this.scrollPageUp = function() {
this.renderer.scrollToRow(this.$getPageUpRow());
};
this.scrollToRow = function(row) {
this.renderer.scrollToRow(row);
};
this.scrollToLine = function(line, center) {
this.renderer.scrollToLine(line, center);
};
this.centerSelection = function() {
var range = this.getSelectionRange();
var line = Math.floor(range.start.row + (range.end.row - range.start.row) / 2);
this.renderer.scrollToLine(line, true);
};
this.getCursorPosition = function() {
return this.selection.getCursor();
};
this.getCursorPositionScreen = function() {
return this.session.documentToScreenPosition(this.getCursorPosition());
};
this.getSelectionRange = function() {
return this.selection.getRange();
};
this.selectAll = function() {
this.$blockScrolling += 1;
this.selection.selectAll();
this.$blockScrolling -= 1;
};
this.clearSelection = function() {
this.selection.clearSelection();
};
this.moveCursorTo = function(row, column) {
this.selection.moveCursorTo(row, column);
};
this.moveCursorToPosition = function(pos) {
this.selection.moveCursorToPosition(pos);
};
this.gotoLine = function(lineNumber, column) {
this.selection.clearSelection();
this.$blockScrolling += 1;
this.moveCursorTo(lineNumber-1, column || 0);
this.$blockScrolling -= 1;
if (!this.isRowVisible(this.getCursorPosition().row)) {
this.scrollToLine(lineNumber, true);
}
},
this.navigateTo = function(row, column) {
this.clearSelection();
this.moveCursorTo(row, column);
};
this.navigateUp = function(times) {
this.selection.clearSelection();
times = times || 1;
this.selection.moveCursorBy(-times, 0);
};
this.navigateDown = function(times) {
this.selection.clearSelection();
times = times || 1;
this.selection.moveCursorBy(times, 0);
};
this.navigateLeft = function(times) {
if (!this.selection.isEmpty()) {
var selectionStart = this.getSelectionRange().start;
this.moveCursorToPosition(selectionStart);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorLeft();
}
}
this.clearSelection();
};
this.navigateRight = function(times) {
if (!this.selection.isEmpty()) {
var selectionEnd = this.getSelectionRange().end;
this.moveCursorToPosition(selectionEnd);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorRight();
}
}
this.clearSelection();
};
this.navigateLineStart = function() {
this.selection.moveCursorLineStart();
this.clearSelection();
};
this.navigateLineEnd = function() {
this.selection.moveCursorLineEnd();
this.clearSelection();
};
this.navigateFileEnd = function() {
this.selection.moveCursorFileEnd();
this.clearSelection();
};
this.navigateFileStart = function() {
this.selection.moveCursorFileStart();
this.clearSelection();
};
this.navigateWordRight = function() {
this.selection.moveCursorWordRight();
this.clearSelection();
};
this.navigateWordLeft = function() {
this.selection.moveCursorWordLeft();
this.clearSelection();
};
this.replace = function(replacement, options) {
if (options)
this.$search.set(options);
var range = this.$search.find(this.session);
if (!range)
return;
this.$tryReplace(range, replacement);
if (range !== null)
this.selection.setSelectionRange(range);
},
this.replaceAll = function(replacement, options) {
if (options) {
this.$search.set(options);
}
var ranges = this.$search.findAll(this.session);
if (!ranges.length)
return;
var selection = this.getSelectionRange();
this.clearSelection();
this.selection.moveCursorTo(0, 0);
this.$blockScrolling += 1;
for (var i = ranges.length - 1; i >= 0; --i)
this.$tryReplace(ranges[i], replacement);
this.selection.setSelectionRange(selection);
this.$blockScrolling -= 1;
},
this.$tryReplace = function(range, replacement) {
var input = this.session.getTextRange(range);
var replacement = this.$search.replace(input, replacement);
if (replacement !== null) {
range.end = this.session.replace(range, replacement);
return range;
} else {
return null;
}
};
this.getLastSearchOptions = function() {
return this.$search.getOptions();
};
this.find = function(needle, options) {
this.clearSelection();
options = options || {};
options.needle = needle;
this.$search.set(options);
this.$find();
},
this.findNext = function(options) {
options = options || {};
if (typeof options.backwards == "undefined")
options.backwards = false;
this.$search.set(options);
this.$find();
};
this.findPrevious = function(options) {
options = options || {};
if (typeof options.backwards == "undefined")
options.backwards = true;
this.$search.set(options);
this.$find();
};
this.$find = function(backwards) {
if (!this.selection.isEmpty()) {
this.$search.set({needle: this.session.getTextRange(this.getSelectionRange())});
}
if (typeof backwards != "undefined")
this.$search.set({backwards: backwards});
var range = this.$search.find(this.session);
if (range) {
this.gotoLine(range.end.row+1, range.end.column);
this.selection.setSelectionRange(range);
}
};
this.undo = function() {
this.session.getUndoManager().undo();
};
this.redo = function() {
this.session.getUndoManager().redo();
};
this.destroy = function() {
this.renderer.destroy();
}
}).call(Editor.prototype);
exports.Editor = Editor;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/keyboard/textinput', ['require', 'exports', 'module' , 'pilot/event', 'pilot/useragent', 'pilot/dom'], function(require, exports, module) {
var event = require("pilot/event");
var useragent = require("pilot/useragent");
var dom = require("pilot/dom");
var TextInput = function(parentNode, host) {
var text = dom.createElement("textarea");
text.style.left = "-10000px";
parentNode.appendChild(text);
var PLACEHOLDER = String.fromCharCode(0);
sendText();
var inCompostion = false;
var copied = false;
var pasted = false;
var tempStyle = '';
function sendText(valueToSend) {
if (!copied) {
var value = valueToSend || text.value;
if (value) {
if (value.charCodeAt(value.length-1) == PLACEHOLDER.charCodeAt(0)) {
value = value.slice(0, -1);
if (value)
host.onTextInput(value, !pasted);
}
else {
host.onTextInput(value, !pasted);
}
// If editor is no longer focused we quit immediately, since
// it means that something else is in charge now.
if (!isFocused())
return false;
}
}
copied = false;
pasted = false;
// Safari doesn't fire copy events if no text is selected
text.value = PLACEHOLDER;
text.select();
}
var onTextInput = function(e) {
setTimeout(function () {
if (!inCompostion)
sendText(e.data);
}, 0);
};
var onKeyPress = function(e) {
if (useragent.isIE && text.value.charCodeAt(0) > 128) return;
setTimeout(function() {
if (!inCompostion)
sendText();
}, 0);
};
var onCompositionStart = function(e) {
inCompostion = true;
host.onCompositionStart();
if (!useragent.isGecko) setTimeout(onCompositionUpdate, 0);
};
var onCompositionUpdate = function() {
if (!inCompostion) return;
host.onCompositionUpdate(text.value);
};
var onCompositionEnd = function(e) {
inCompostion = false;
host.onCompositionEnd();
};
var onCopy = function(e) {
copied = true;
var copyText = host.getCopyText();
if(copyText)
text.value = copyText;
else
e.preventDefault();
text.select();
setTimeout(function () {
sendText();
}, 0);
};
var onCut = function(e) {
copied = true;
var copyText = host.getCopyText();
if(copyText) {
text.value = copyText;
host.onCut();
} else
e.preventDefault();
text.select();
setTimeout(function () {
sendText();
}, 0);
};
event.addCommandKeyListener(text, host.onCommandKey.bind(host));
if (useragent.isIE) {
var keytable = { 13:1, 27:1 };
event.addListener(text, "keyup", function (e) {
if (inCompostion && (!text.value || keytable[e.keyCode]))
setTimeout(onCompositionEnd, 0);
if ((text.value.charCodeAt(0)|0) < 129) {
return;
};
inCompostion ? onCompositionUpdate() : onCompositionStart();
});
};
if (text.attachEvent) {
// Old IE + Opera
event.addListener(text, "propertychange", onKeyPress);
}
else {
if (useragent.isChrome || useragent.isSafari)
event.addListener(text, "textInput", onTextInput);
else if (useragent.isIE)
// IE9
event.addListener(text, "textinput", onTextInput);
else
// All browsers except old IE
event.addListener(text, "input", onTextInput);
}
event.addListener(text, "paste", function(e) {
// Mark that the next input text comes from past.
pasted = true;
// Some browsers support the event.clipboardData API. Use this to get
// the pasted content which increases speed if pasting a lot of lines.
if (e.clipboardData && e.clipboardData.getData) {
sendText(e.clipboardData.getData("text/plain"));
e.preventDefault();
}
else {
// If a browser doesn't support any of the things above, use the regular
// method to detect the pasted input.
onKeyPress();
}
});
if (useragent.isIE) {
event.addListener(text, "beforecopy", function(e) {
var copyText = host.getCopyText();
if(copyText)
clipboardData.setData("Text", copyText);
else
e.preventDefault();
});
event.addListener(parentNode, "keydown", function(e) {
if (e.ctrlKey && e.keyCode == 88) {
var copyText = host.getCopyText();
if (copyText) {
clipboardData.setData("Text", copyText);
host.onCut();
}
event.preventDefault(e)
}
});
}
else {
event.addListener(text, "copy", onCopy);
event.addListener(text, "cut", onCut);
}
event.addListener(text, "compositionstart", onCompositionStart);
if (useragent.isGecko) {
event.addListener(text, "text", onCompositionUpdate);
};
if (useragent.isWebKit) {
event.addListener(text, "keyup", onCompositionUpdate);
};
event.addListener(text, "compositionend", onCompositionEnd);
event.addListener(text, "blur", function() {
host.onBlur();
});
event.addListener(text, "focus", function() {
host.onFocus();
text.select();
});
this.focus = function() {
host.onFocus();
text.select();
text.focus();
};
this.blur = function() {
text.blur();
};
function isFocused() {
return document.activeElement === text;
};
this.isFocused = isFocused;
this.getElement = function() {
return text;
};
this.onContextMenu = function(mousePos, isEmpty){
if (mousePos) {
if(!tempStyle)
tempStyle = text.style.cssText;
text.style.cssText = 'position:fixed; z-index:1000;' +
'left:' + (mousePos.x - 2) + 'px; top:' + (mousePos.y - 2) + 'px;'
}
if (isEmpty)
text.value='';
}
this.onContextMenuClose = function(){
setTimeout(function () {
if (tempStyle) {
text.style.cssText = tempStyle;
tempStyle = '';
}
sendText();
}, 0);
}
};
exports.TextInput = TextInput;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mouse_handler', ['require', 'exports', 'module' , 'pilot/event', 'pilot/dom', 'pilot/browser_focus'], function(require, exports, module) {
var event = require("pilot/event");
var dom = require("pilot/dom");
var BrowserFocus = require("pilot/browser_focus").BrowserFocus;
var STATE_UNKNOWN = 0;
var STATE_SELECT = 1;
var STATE_DRAG = 2;
var DRAG_TIMER = 250; // milliseconds
var DRAG_OFFSET = 5; // pixels
var MouseHandler = function(editor) {
this.editor = editor;
this.browserFocus = new BrowserFocus();
event.addListener(editor.container, "mousedown", function(e) {
editor.focus();
return event.preventDefault(e);
});
event.addListener(editor.container, "selectstart", function(e) {
return event.preventDefault(e);
});
var mouseTarget = editor.renderer.getMouseEventTarget();
event.addListener(mouseTarget, "mousedown", this.onMouseDown.bind(this));
event.addMultiMouseDownListener(mouseTarget, 0, 2, 500, this.onMouseDoubleClick.bind(this));
event.addMultiMouseDownListener(mouseTarget, 0, 3, 600, this.onMouseTripleClick.bind(this));
event.addMultiMouseDownListener(mouseTarget, 0, 4, 600, this.onMouseQuadClick.bind(this));
event.addMouseWheelListener(mouseTarget, this.onMouseWheel.bind(this));
};
(function() {
this.$scrollSpeed = 1;
this.setScrollSpeed = function(speed) {
this.$scrollSpeed = speed;
};
this.getScrollSpeed = function() {
return this.$scrollSpeed;
};
this.$getEventPosition = function(e) {
var pageX = event.getDocumentX(e);
var pageY = event.getDocumentY(e);
var pos = this.editor.renderer.screenToTextCoordinates(pageX, pageY);
pos.row = Math.max(0, Math.min(pos.row, this.editor.session.getLength()-1));
return pos;
};
this.$distance = function(ax, ay, bx, by) {
return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
};
this.onMouseDown = function(e) {
// if this click caused the editor to be focused ignore the click
// for selection and cursor placement
if (
!this.browserFocus.isFocused()
|| new Date().getTime() - this.browserFocus.lastFocus < 20
|| !this.editor.isFocused()
)
return;
var pageX = event.getDocumentX(e);
var pageY = event.getDocumentY(e);
var pos = this.$getEventPosition(e);
var editor = this.editor;
var self = this;
var selectionRange = editor.getSelectionRange();
var selectionEmpty = selectionRange.isEmpty();
var state = STATE_UNKNOWN;
var inSelection = false;
var button = event.getButton(e);
if (button !== 0) {
if (selectionEmpty) {
editor.moveCursorToPosition(pos);
}
if(button == 2) {
editor.textInput.onContextMenu({x: pageX, y: pageY}, selectionEmpty);
event.capture(editor.container, function(){}, editor.textInput.onContextMenuClose);
}
return;
} else {
// Select the fold as the user clicks it.
var fold = editor.session.getFoldAt(pos.row, pos.column, 1);
if (fold) {
editor.selection.setSelectionRange(fold.range);
return;
}
inSelection = !editor.getReadOnly()
&& !selectionEmpty
&& selectionRange.contains(pos.row, pos.column);
}
if (!inSelection) {
// Directly pick STATE_SELECT, since the user is not clicking inside
// a selection.
onStartSelect(pos);
}
var mousePageX, mousePageY;
var overwrite = editor.getOverwrite();
var mousedownTime = (new Date()).getTime();
var dragCursor, dragRange;
var onMouseSelection = function(e) {
mousePageX = event.getDocumentX(e);
mousePageY = event.getDocumentY(e);
};
var onMouseSelectionEnd = function() {
clearInterval(timerId);
if (state == STATE_UNKNOWN)
onStartSelect(pos);
else if (state == STATE_DRAG)
onMouseDragSelectionEnd();
self.$clickSelection = null;
state = STATE_UNKNOWN;
};
var onMouseDragSelectionEnd = function() {
dom.removeCssClass(editor.container, "ace_dragging");
editor.session.removeMarker(dragSelectionMarker);
if (!self.$clickSelection) {
if (!dragCursor) {
editor.moveCursorToPosition(pos);
editor.selection.clearSelection(pos.row, pos.column);
}
}
if (!dragCursor)
return;
if (dragRange.contains(dragCursor.row, dragCursor.column)) {
dragCursor = null;
return;
}
editor.clearSelection();
var newRange = editor.moveText(dragRange, dragCursor);
if (!newRange) {
dragCursor = null;
return;
}
editor.selection.setSelectionRange(newRange);
};
var onSelectionInterval = function() {
if (mousePageX === undefined || mousePageY === undefined)
return;
if (state == STATE_UNKNOWN) {
var distance = self.$distance(pageX, pageY, mousePageX, mousePageY);
var time = (new Date()).getTime();
if (distance > DRAG_OFFSET) {
state = STATE_SELECT;
var cursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY);
cursor.row = Math.max(0, Math.min(cursor.row, editor.session.getLength()-1));
onStartSelect(cursor);
} else if ((time - mousedownTime) > DRAG_TIMER) {
state = STATE_DRAG;
dragRange = editor.getSelectionRange();
var style = editor.getSelectionStyle();
dragSelectionMarker = editor.session.addMarker(dragRange, "ace_selection", style);
editor.clearSelection();
dom.addCssClass(editor.container, "ace_dragging");
}
}
if (state == STATE_DRAG)
onDragSelectionInterval();
else if (state == STATE_SELECT)
onUpdateSelectionInterval();
};
function onStartSelect(pos) {
if (e.shiftKey)
editor.selection.selectToPosition(pos)
else {
if (!self.$clickSelection) {
editor.moveCursorToPosition(pos);
editor.selection.clearSelection(pos.row, pos.column);
}
}
state = STATE_SELECT;
}
var onUpdateSelectionInterval = function() {
var cursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY);
cursor.row = Math.max(0, Math.min(cursor.row, editor.session.getLength()-1));
if (self.$clickSelection) {
if (self.$clickSelection.contains(cursor.row, cursor.column)) {
editor.selection.setSelectionRange(self.$clickSelection);
} else {
if (self.$clickSelection.compare(cursor.row, cursor.column) == -1) {
var anchor = self.$clickSelection.end;
} else {
var anchor = self.$clickSelection.start;
}
editor.selection.setSelectionAnchor(anchor.row, anchor.column);
editor.selection.selectToPosition(cursor);
}
}
else {
editor.selection.selectToPosition(cursor);
}
editor.renderer.scrollCursorIntoView();
};
var onDragSelectionInterval = function() {
dragCursor = editor.renderer.screenToTextCoordinates(mousePageX, mousePageY);
dragCursor.row = Math.max(0, Math.min(dragCursor.row,
editor.session.getLength() - 1));
editor.moveCursorToPosition(dragCursor);
};
event.capture(editor.container, onMouseSelection, onMouseSelectionEnd);
var timerId = setInterval(onSelectionInterval, 20);
return event.preventDefault(e);
};
this.onMouseDoubleClick = function(e) {
var editor = this.editor;
var pos = this.$getEventPosition(e);
// If the user dclicked on a fold, then expand it.
var fold = editor.session.getFoldAt(pos.row, pos.column, 1);
if (fold) {
editor.session.expandFold(fold);
} else {
editor.moveCursorToPosition(pos);
editor.selection.selectWord();
this.$clickSelection = editor.getSelectionRange();
}
};
this.onMouseTripleClick = function(e) {
var pos = this.$getEventPosition(e);
this.editor.moveCursorToPosition(pos);
this.editor.selection.selectLine();
this.$clickSelection = this.editor.getSelectionRange();
};
this.onMouseQuadClick = function(e) {
this.editor.selectAll();
this.$clickSelection = this.editor.getSelectionRange();
};
this.onMouseWheel = function(e) {
var speed = this.$scrollSpeed * 2;
this.editor.renderer.scrollBy(e.wheelX * speed, e.wheelY * speed);
return event.preventDefault(e);
};
}).call(MouseHandler.prototype);
exports.MouseHandler = MouseHandler;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/browser_focus', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/event', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var event = require("pilot/event");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
/**
* This class keeps track of the focus state of the given window.
* Focus changes for example when the user switches a browser tab,
* goes to the location bar or switches to another application.
*/
var BrowserFocus = function(win) {
win = win || window;
this.lastFocus = new Date().getTime();
this._isFocused = true;
var _self = this;
event.addListener(win, "blur", function(e) {
_self._setFocused(false);
});
event.addListener(win, "focus", function(e) {
_self._setFocused(true);
});
};
(function(){
oop.implement(this, EventEmitter);
this.isFocused = function() {
return this._isFocused;
};
this._setFocused = function(isFocused) {
if (this._isFocused == isFocused)
return;
if (isFocused)
this.lastFocus = new Date().getTime();
this._isFocused = isFocused;
this._emit("changeFocus");
};
}).call(BrowserFocus.prototype);
exports.BrowserFocus = BrowserFocus;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/keyboard/keybinding', ['require', 'exports', 'module' , 'pilot/useragent', 'pilot/keys', 'pilot/event', 'pilot/settings', 'pilot/canon', 'ace/commands/default_commands'], function(require, exports, module) {
var useragent = require("pilot/useragent");
var keyUtil = require("pilot/keys");
var event = require("pilot/event");
var settings = require("pilot/settings").settings;
var canon = require("pilot/canon");
require("ace/commands/default_commands");
var KeyBinding = function(editor) {
this.$editor = editor;
this.$data = { };
this.$keyboardHandler = null;
};
(function() {
this.setKeyboardHandler = function(keyboardHandler) {
if (this.$keyboardHandler != keyboardHandler) {
this.$data = { };
this.$keyboardHandler = keyboardHandler;
}
};
this.getKeyboardHandler = function() {
return this.$keyboardHandler;
};
this.$callKeyboardHandler = function (e, hashId, keyOrText, keyCode) {
var env = {editor: this.$editor},
toExecute;
if (this.$keyboardHandler) {
toExecute =
this.$keyboardHandler.handleKeyboard(this.$data, hashId, keyOrText, keyCode, e);
}
// If there is nothing to execute yet, then use the default keymapping.
if (!toExecute || !toExecute.command) {
if (hashId != 0 || keyCode != 0) {
toExecute = {
command: canon.findKeyCommand(env, "editor", hashId, keyOrText)
}
} else {
toExecute = {
command: "inserttext",
args: {
text: keyOrText
}
}
}
}
var success = false;
if (toExecute) {
success = canon.exec(toExecute.command,
env, "editor", toExecute.args);
if (success) {
event.stopEvent(e);
}
}
return success;
};
this.onCommandKey = function(e, hashId, keyCode, keyString) {
// In case there is no keyString, try to interprete the keyCode.
if (!keyString) {
keyString = keyUtil.keyCodeToString(keyCode);
}
return this.$callKeyboardHandler(e, hashId, keyString, keyCode);
};
this.onTextInput = function(text) {
return this.$callKeyboardHandler({}, 0, text, 0);
}
}).call(KeyBinding.prototype);
exports.KeyBinding = KeyBinding;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
* Mihai Sucan <mihai.sucan@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/commands/default_commands', ['require', 'exports', 'module' , 'pilot/lang', 'pilot/canon'], function(require, exports, module) {
var lang = require("pilot/lang");
var canon = require("pilot/canon");
function bindKey(win, mac) {
return {
win: win,
mac: mac,
sender: "editor"
};
}
canon.addCommand({
name: "null",
exec: function(env, args, request) { }
});
canon.addCommand({
name: "selectall",
bindKey: bindKey("Ctrl-A", "Command-A"),
exec: function(env, args, request) { env.editor.selectAll(); }
});
canon.addCommand({
name: "removeline",
bindKey: bindKey("Ctrl-D", "Command-D"),
exec: function(env, args, request) { env.editor.removeLines(); }
});
canon.addCommand({
name: "gotoline",
bindKey: bindKey("Ctrl-L", "Command-L"),
exec: function(env, args, request) {
var line = parseInt(prompt("Enter line number:"));
if (!isNaN(line)) {
env.editor.gotoLine(line);
}
}
});
canon.addCommand({
name: "togglecomment",
bindKey: bindKey("Ctrl-7", "Command-7"),
exec: function(env, args, request) { env.editor.toggleCommentLines(); }
});
canon.addCommand({
name: "findnext",
bindKey: bindKey("Ctrl-K", "Command-G"),
exec: function(env, args, request) { env.editor.findNext(); }
});
canon.addCommand({
name: "findprevious",
bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"),
exec: function(env, args, request) { env.editor.findPrevious(); }
});
canon.addCommand({
name: "find",
bindKey: bindKey("Ctrl-F", "Command-F"),
exec: function(env, args, request) {
var needle = prompt("Find:");
env.editor.find(needle);
}
});
canon.addCommand({
name: "replace",
bindKey: bindKey("Ctrl-R", "Command-Option-F"),
exec: function(env, args, request) {
var needle = prompt("Find:");
if (!needle)
return;
var replacement = prompt("Replacement:");
if (!replacement)
return;
env.editor.replace(replacement, {needle: needle});
}
});
canon.addCommand({
name: "replaceall",
bindKey: bindKey("Ctrl-Shift-R", "Command-Shift-Option-F"),
exec: function(env, args, request) {
var needle = prompt("Find:");
if (!needle)
return;
var replacement = prompt("Replacement:");
if (!replacement)
return;
env.editor.replaceAll(replacement, {needle: needle});
}
});
canon.addCommand({
name: "undo",
bindKey: bindKey("Ctrl-Z", "Command-Z"),
exec: function(env, args, request) { env.editor.undo(); }
});
canon.addCommand({
name: "redo",
bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"),
exec: function(env, args, request) { env.editor.redo(); }
});
canon.addCommand({
name: "overwrite",
bindKey: bindKey("Insert", "Insert"),
exec: function(env, args, request) { env.editor.toggleOverwrite(); }
});
canon.addCommand({
name: "copylinesup",
bindKey: bindKey("Ctrl-Alt-Up", "Command-Option-Up"),
exec: function(env, args, request) { env.editor.copyLinesUp(); }
});
canon.addCommand({
name: "movelinesup",
bindKey: bindKey("Alt-Up", "Option-Up"),
exec: function(env, args, request) { env.editor.moveLinesUp(); }
});
canon.addCommand({
name: "selecttostart",
bindKey: bindKey("Ctrl-Shift-Home|Alt-Shift-Up", "Command-Shift-Up"),
exec: function(env, args, request) { env.editor.getSelection().selectFileStart(); }
});
canon.addCommand({
name: "gotostart",
bindKey: bindKey("Ctrl-Home|Ctrl-Up", "Command-Home|Command-Up"),
exec: function(env, args, request) { env.editor.navigateFileStart(); }
});
canon.addCommand({
name: "selectup",
bindKey: bindKey("Shift-Up", "Shift-Up"),
exec: function(env, args, request) { env.editor.getSelection().selectUp(); }
});
canon.addCommand({
name: "golineup",
bindKey: bindKey("Up", "Up|Ctrl-P"),
exec: function(env, args, request) { env.editor.navigateUp(args.times); }
});
canon.addCommand({
name: "copylinesdown",
bindKey: bindKey("Ctrl-Alt-Down", "Command-Option-Down"),
exec: function(env, args, request) { env.editor.copyLinesDown(); }
});
canon.addCommand({
name: "movelinesdown",
bindKey: bindKey("Alt-Down", "Option-Down"),
exec: function(env, args, request) { env.editor.moveLinesDown(); }
});
canon.addCommand({
name: "selecttoend",
bindKey: bindKey("Ctrl-Shift-End|Alt-Shift-Down", "Command-Shift-Down"),
exec: function(env, args, request) { env.editor.getSelection().selectFileEnd(); }
});
canon.addCommand({
name: "gotoend",
bindKey: bindKey("Ctrl-End|Ctrl-Down", "Command-End|Command-Down"),
exec: function(env, args, request) { env.editor.navigateFileEnd(); }
});
canon.addCommand({
name: "selectdown",
bindKey: bindKey("Shift-Down", "Shift-Down"),
exec: function(env, args, request) { env.editor.getSelection().selectDown(); }
});
canon.addCommand({
name: "golinedown",
bindKey: bindKey("Down", "Down|Ctrl-N"),
exec: function(env, args, request) { env.editor.navigateDown(args.times); }
});
canon.addCommand({
name: "selectwordleft",
bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"),
exec: function(env, args, request) { env.editor.getSelection().selectWordLeft(); }
});
canon.addCommand({
name: "gotowordleft",
bindKey: bindKey("Ctrl-Left", "Option-Left"),
exec: function(env, args, request) { env.editor.navigateWordLeft(); }
});
canon.addCommand({
name: "selecttolinestart",
bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left"),
exec: function(env, args, request) { env.editor.getSelection().selectLineStart(); }
});
canon.addCommand({
name: "gotolinestart",
bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"),
exec: function(env, args, request) { env.editor.navigateLineStart(); }
});
canon.addCommand({
name: "selectleft",
bindKey: bindKey("Shift-Left", "Shift-Left"),
exec: function(env, args, request) { env.editor.getSelection().selectLeft(); }
});
canon.addCommand({
name: "gotoleft",
bindKey: bindKey("Left", "Left|Ctrl-B"),
exec: function(env, args, request) { env.editor.navigateLeft(args.times); }
});
canon.addCommand({
name: "selectwordright",
bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"),
exec: function(env, args, request) { env.editor.getSelection().selectWordRight(); }
});
canon.addCommand({
name: "gotowordright",
bindKey: bindKey("Ctrl-Right", "Option-Right"),
exec: function(env, args, request) { env.editor.navigateWordRight(); }
});
canon.addCommand({
name: "selecttolineend",
bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right"),
exec: function(env, args, request) { env.editor.getSelection().selectLineEnd(); }
});
canon.addCommand({
name: "gotolineend",
bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"),
exec: function(env, args, request) { env.editor.navigateLineEnd(); }
});
canon.addCommand({
name: "selectright",
bindKey: bindKey("Shift-Right", "Shift-Right"),
exec: function(env, args, request) { env.editor.getSelection().selectRight(); }
});
canon.addCommand({
name: "gotoright",
bindKey: bindKey("Right", "Right|Ctrl-F"),
exec: function(env, args, request) { env.editor.navigateRight(args.times); }
});
canon.addCommand({
name: "selectpagedown",
bindKey: bindKey("Shift-PageDown", "Shift-PageDown"),
exec: function(env, args, request) { env.editor.selectPageDown(); }
});
canon.addCommand({
name: "pagedown",
bindKey: bindKey(null, "PageDown"),
exec: function(env, args, request) { env.editor.scrollPageDown(); }
});
canon.addCommand({
name: "gotopagedown",
bindKey: bindKey("PageDown", "Option-PageDown|Ctrl-V"),
exec: function(env, args, request) { env.editor.gotoPageDown(); }
});
canon.addCommand({
name: "selectpageup",
bindKey: bindKey("Shift-PageUp", "Shift-PageUp"),
exec: function(env, args, request) { env.editor.selectPageUp(); }
});
canon.addCommand({
name: "pageup",
bindKey: bindKey(null, "PageUp"),
exec: function(env, args, request) { env.editor.scrollPageUp(); }
});
canon.addCommand({
name: "gotopageup",
bindKey: bindKey("PageUp", "Option-PageUp"),
exec: function(env, args, request) { env.editor.gotoPageUp(); }
});
canon.addCommand({
name: "selectlinestart",
bindKey: bindKey("Shift-Home", "Shift-Home"),
exec: function(env, args, request) { env.editor.getSelection().selectLineStart(); }
});
canon.addCommand({
name: "selectlineend",
bindKey: bindKey("Shift-End", "Shift-End"),
exec: function(env, args, request) { env.editor.getSelection().selectLineEnd(); }
});
canon.addCommand({
name: "del",
bindKey: bindKey("Delete", "Delete|Ctrl-D"),
exec: function(env, args, request) { env.editor.removeRight(); }
});
canon.addCommand({
name: "backspace",
bindKey: bindKey(
"Ctrl-Backspace|Command-Backspace|Option-Backspace|Shift-Backspace|Backspace",
"Ctrl-Backspace|Command-Backspace|Shift-Backspace|Backspace|Ctrl-H"
),
exec: function(env, args, request) { env.editor.removeLeft(); }
});
canon.addCommand({
name: "removetolinestart",
bindKey: bindKey(null, "Option-Backspace"),
exec: function(env, args, request) { env.editor.removeToLineStart(); }
});
canon.addCommand({
name: "removetolineend",
bindKey: bindKey(null, "Ctrl-K"),
exec: function(env, args, request) { env.editor.removeToLineEnd(); }
});
canon.addCommand({
name: "removewordleft",
bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"),
exec: function(env, args, request) { env.editor.removeWordLeft(); }
});
canon.addCommand({
name: "removewordright",
bindKey: bindKey(null, "Alt-Delete"),
exec: function(env, args, request) { env.editor.removeWordRight(); }
});
canon.addCommand({
name: "outdent",
bindKey: bindKey("Shift-Tab", "Shift-Tab"),
exec: function(env, args, request) { env.editor.blockOutdent(); }
});
canon.addCommand({
name: "indent",
bindKey: bindKey("Tab", "Tab"),
exec: function(env, args, request) { env.editor.indent(); }
});
canon.addCommand({
name: "inserttext",
exec: function(env, args, request) {
env.editor.insert(lang.stringRepeat(args.text || "", args.times || 1));
}
});
canon.addCommand({
name: "centerselection",
bindKey: bindKey(null, "Ctrl-L"),
exec: function(env, args, request) { env.editor.centerSelection(); }
});
canon.addCommand({
name: "splitline",
bindKey: bindKey(null, "Ctrl-O"),
exec: function(env, args, request) { env.editor.splitLine(); }
});
canon.addCommand({
name: "transposeletters",
bindKey: bindKey("Ctrl-T", "Ctrl-T"),
exec: function(env, args, request) { env.editor.transposeLetters(); }
});
});/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/edit_session', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/lang', 'pilot/event_emitter', 'ace/selection', 'ace/mode/text', 'ace/range', 'ace/document', 'ace/background_tokenizer', 'ace/edit_session/folding'], function(require, exports, module) {
var oop = require("pilot/oop");
var lang = require("pilot/lang");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Selection = require("ace/selection").Selection;
var TextMode = require("ace/mode/text").Mode;
var Range = require("ace/range").Range;
var Document = require("ace/document").Document;
var BackgroundTokenizer = require("ace/background_tokenizer").BackgroundTokenizer;
var EditSession = function(text, mode) {
this.$modified = true;
this.$breakpoints = [];
this.$frontMarkers = {};
this.$backMarkers = {};
this.$markerId = 1;
this.$rowCache = [];
this.$wrapData = [];
this.$foldData = [];
this.$foldData.toString = function() {
var str = "";
this.forEach(function(foldLine) {
str += "\n" + foldLine.toString();
});
return str;
}
if (text instanceof Document) {
this.setDocument(text);
} else {
this.setDocument(new Document(text));
}
this.selection = new Selection(this);
if (mode)
this.setMode(mode);
else
this.setMode(new TextMode());
};
(function() {
oop.implement(this, EventEmitter);
this.setDocument = function(doc) {
if (this.doc)
throw new Error("Document is already set");
this.doc = doc;
doc.on("change", this.onChange.bind(this));
this.on("changeFold", this.onChangeFold.bind(this));
};
this.getDocument = function() {
return this.doc;
};
this.$resetRowCache = function(row) {
if (row == 0) {
this.$rowCache = [];
return;
}
var rowCache = this.$rowCache;
for (var i = 0; i < rowCache.length; i++) {
if (rowCache[i].docRow >= row) {
rowCache.splice(i, rowCache.length);
return;
}
}
};
this.onChangeFold = function(e) {
var fold = e.data;
this.$resetRowCache(fold.start.row);
};
this.onChange = function(e) {
var delta = e.data;
this.$modified = true;
this.$resetRowCache(delta.range.start.row);
var removedFolds = this.$updateInternalDataOnChange(e);
if (!this.$fromUndo && this.$undoManager && !delta.ignore) {
this.$deltasDoc.push(delta);
if (removedFolds && removedFolds.length != 0) {
this.$deltasFold.push({
action: "removeFolds",
folds: removedFolds
});
}
this.$informUndoManager.schedule();
}
this.bgTokenizer.start(delta.range.start.row);
this._dispatchEvent("change", e);
};
this.setValue = function(text) {
this.doc.setValue(text);
this.selection.moveCursorTo(0, 0);
this.selection.clearSelection();
this.$resetRowCache(0);
this.$deltas = [];
this.$deltasDoc = [];
this.$deltasFold = [];
this.getUndoManager().reset();
};
this.getValue =
this.toString = function() {
return this.doc.getValue();
};
this.getSelection = function() {
return this.selection;
};
this.getState = function(row) {
return this.bgTokenizer.getState(row);
};
this.getTokens = function(firstRow, lastRow) {
return this.bgTokenizer.getTokens(firstRow, lastRow);
};
this.setUndoManager = function(undoManager) {
this.$undoManager = undoManager;
this.$resetRowCache(0);
this.$deltas = [];
this.$deltasDoc = [];
this.$deltasFold = [];
if (this.$informUndoManager)
this.$informUndoManager.cancel();
if (undoManager) {
var self = this;
this.$syncInformUndoManager = function() {
self.$informUndoManager.cancel();
if (self.$deltasFold.length) {
self.$deltas.push({
group: "fold",
deltas: self.$deltasFold
});
self.$deltasFold = [];
}
if (self.$deltasDoc.length) {
self.$deltas.push({
group: "doc",
deltas: self.$deltasDoc
});
self.$deltasDoc = [];
}
if (self.$deltas.length > 0) {
undoManager.execute({
action: "aceupdate",
args: [self.$deltas, self]
});
}
self.$deltas = [];
}
this.$informUndoManager =
lang.deferredCall(this.$syncInformUndoManager);
}
};
this.$defaultUndoManager = {
undo: function() {},
redo: function() {},
reset: function() {}
};
this.getUndoManager = function() {
return this.$undoManager || this.$defaultUndoManager;
},
this.getTabString = function() {
if (this.getUseSoftTabs()) {
return lang.stringRepeat(" ", this.getTabSize());
} else {
return "\t";
}
};
this.$useSoftTabs = true;
this.setUseSoftTabs = function(useSoftTabs) {
if (this.$useSoftTabs === useSoftTabs) return;
this.$useSoftTabs = useSoftTabs;
};
this.getUseSoftTabs = function() {
return this.$useSoftTabs;
};
this.$tabSize = 4;
this.setTabSize = function(tabSize) {
if (isNaN(tabSize) || this.$tabSize === tabSize) return;
this.$modified = true;
this.$tabSize = tabSize;
this._dispatchEvent("changeTabSize");
};
this.getTabSize = function() {
return this.$tabSize;
};
this.isTabStop = function(position) {
return this.$useSoftTabs && (position.column % this.$tabSize == 0);
};
this.$overwrite = false;
this.setOverwrite = function(overwrite) {
if (this.$overwrite == overwrite) return;
this.$overwrite = overwrite;
this._dispatchEvent("changeOverwrite");
};
this.getOverwrite = function() {
return this.$overwrite;
};
this.toggleOverwrite = function() {
this.setOverwrite(!this.$overwrite);
};
this.getBreakpoints = function() {
return this.$breakpoints;
};
this.setBreakpoints = function(rows) {
this.$breakpoints = [];
for (var i=0; i<rows.length; i++) {
this.$breakpoints[rows[i]] = true;
}
this._dispatchEvent("changeBreakpoint", {});
};
this.clearBreakpoints = function() {
this.$breakpoints = [];
this._dispatchEvent("changeBreakpoint", {});
};
this.setBreakpoint = function(row) {
this.$breakpoints[row] = true;
this._dispatchEvent("changeBreakpoint", {});
};
this.clearBreakpoint = function(row) {
delete this.$breakpoints[row];
this._dispatchEvent("changeBreakpoint", {});
};
this.getBreakpoints = function() {
return this.$breakpoints;
};
this.addMarker = function(range, clazz, type, inFront) {
var id = this.$markerId++;
var marker = {
range : range,
type : type || "line",
renderer: typeof type == "function" ? type : null,
clazz : clazz,
inFront: !!inFront
}
if (inFront) {
this.$frontMarkers[id] = marker;
this._dispatchEvent("changeFrontMarker")
} else {
this.$backMarkers[id] = marker;
this._dispatchEvent("changeBackMarker")
}
return id;
};
this.removeMarker = function(markerId) {
var marker = this.$frontMarkers[markerId] || this.$backMarkers[markerId];
if (!marker)
return;
var markers = marker.inFront ? this.$frontMarkers : this.$backMarkers;
if (marker) {
delete (markers[markerId]);
this._dispatchEvent(marker.inFront ? "changeFrontMarker" : "changeBackMarker");
}
};
this.getMarkers = function(inFront) {
return inFront ? this.$frontMarkers : this.$backMarkers;
};
/**
* Error:
* {
* row: 12,
* column: 2, //can be undefined
* text: "Missing argument",
* type: "error" // or "warning" or "info"
* }
*/
this.setAnnotations = function(annotations) {
this.$annotations = {};
for (var i=0; i<annotations.length; i++) {
var annotation = annotations[i];
var row = annotation.row;
if (this.$annotations[row])
this.$annotations[row].push(annotation);
else
this.$annotations[row] = [annotation];
}
this._dispatchEvent("changeAnnotation", {});
};
this.getAnnotations = function() {
return this.$annotations;
};
this.clearAnnotations = function() {
this.$annotations = {};
this._dispatchEvent("changeAnnotation", {});
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r?\n)/m);
if (match) {
this.$autoNewLine = match[1];
} else {
this.$autoNewLine = "\n";
}
};
this.getWordRange = function(row, column) {
var line = this.getLine(row);
var inToken = false;
if (column > 0) {
inToken = !!line.charAt(column - 1).match(this.tokenRe);
}
if (!inToken) {
inToken = !!line.charAt(column).match(this.tokenRe);
}
var re = inToken ? this.tokenRe : this.nonTokenRe;
var start = column;
if (start > 0) {
do {
start--;
}
while (start >= 0 && line.charAt(start).match(re));
start++;
}
var end = column;
while (end < line.length && line.charAt(end).match(re)) {
end++;
}
return new Range(row, start, row, end);
};
this.setNewLineMode = function(newLineMode) {
this.doc.setNewLineMode(newLineMode);
};
this.getNewLineMode = function() {
return this.doc.getNewLineMode();
};
this.$useWorker = true;
this.setUseWorker = function(useWorker) {
if (this.$useWorker == useWorker)
return;
this.$useWorker = useWorker;
this.$stopWorker();
if (useWorker)
this.$startWorker();
};
this.getUseWorker = function() {
return this.$useWorker;
};
this.onReloadTokenizer = function(e) {
var rows = e.data;
this.bgTokenizer.start(rows.first);
this._dispatchEvent("tokenizerUpdate", e);
};
this.$mode = null;
this.setMode = function(mode) {
if (this.$mode === mode) return;
this.$mode = mode;
this.$stopWorker();
if (this.$useWorker)
this.$startWorker();
var tokenizer = mode.getTokenizer();
if(tokenizer.addEventListener !== undefined) {
var onReloadTokenizer = this.onReloadTokenizer.bind(this);
tokenizer.addEventListener("update", onReloadTokenizer);
}
if (!this.bgTokenizer) {
this.bgTokenizer = new BackgroundTokenizer(tokenizer);
var _self = this;
this.bgTokenizer.addEventListener("update", function(e) {
_self._dispatchEvent("tokenizerUpdate", e);
});
} else {
this.bgTokenizer.setTokenizer(tokenizer);
}
this.bgTokenizer.setDocument(this.getDocument());
this.bgTokenizer.start(0);
this.tokenRe = mode.tokenRe;
this.nonTokenRe = mode.nonTokenRe;
this._dispatchEvent("changeMode");
};
this.$stopWorker = function() {
if (this.$worker)
this.$worker.terminate();
this.$worker = null;
};
this.$startWorker = function() {
if (typeof Worker !== "undefined" && !require.noWorker) {
try {
this.$worker = this.$mode.createWorker(this);
} catch (e) {
console.log("Could not load worker");
console.log(e);
this.$worker = null;
}
}
else
this.$worker = null;
};
this.getMode = function() {
return this.$mode;
};
this.$scrollTop = 0;
this.setScrollTopRow = function(scrollTopRow) {
if (this.$scrollTop === scrollTopRow) return;
this.$scrollTop = scrollTopRow;
this._dispatchEvent("changeScrollTop");
};
this.getScrollTopRow = function() {
return this.$scrollTop;
};
this.getWidth = function() {
this.$computeWidth();
return this.width;
};
this.getScreenWidth = function() {
this.$computeWidth();
return this.screenWidth;
};
this.$computeWidth = function(force) {
if (this.$modified || force) {
this.$modified = false;
var lines = this.doc.getAllLines();
var longestLine = 0;
var longestScreenLine = 0;
for ( var i = 0; i < lines.length; i++) {
var foldLine = this.getFoldLine(i),
line, len;
line = lines[i];
if (foldLine) {
var end = foldLine.range.end;
line = this.getFoldDisplayLine(foldLine);
// Continue after the foldLine.end.row. All the lines in
// between are folded.
i = end.row;
}
len = line.length;
longestLine = Math.max(longestLine, len);
if (!this.$useWrapMode) {
longestScreenLine = Math.max(
longestScreenLine,
this.$getStringScreenWidth(line)[0]
);
}
}
this.width = longestLine;
if (this.$useWrapMode) {
this.screenWidth = this.$wrapLimit;
} else {
this.screenWidth = longestScreenLine;
}
}
};
/**
* Get a verbatim copy of the given line as it is in the document
*/
this.getLine = function(row) {
return this.doc.getLine(row);
};
this.getLines = function(firstRow, lastRow) {
return this.doc.getLines(firstRow, lastRow);
};
this.getLength = function() {
return this.doc.getLength();
};
this.getTextRange = function(range) {
return this.doc.getTextRange(range);
};
this.findMatchingBracket = function(position) {
if (position.column == 0) return null;
var charBeforeCursor = this.getLine(position.row).charAt(position.column-1);
if (charBeforeCursor == "") return null;
var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/);
if (!match) {
return null;
}
if (match[1]) {
return this.$findClosingBracket(match[1], position);
} else {
return this.$findOpeningBracket(match[2], position);
}
};
this.$brackets = {
")": "(",
"(": ")",
"]": "[",
"[": "]",
"{": "}",
"}": "{"
};
this.$findOpeningBracket = function(bracket, position) {
var openBracket = this.$brackets[bracket];
var column = position.column - 2;
var row = position.row;
var depth = 1;
var line = this.getLine(row);
while (true) {
while(column >= 0) {
var ch = line.charAt(column);
if (ch == openBracket) {
depth -= 1;
if (depth == 0) {
return {row: row, column: column};
}
}
else if (ch == bracket) {
depth +=1;
}
column -= 1;
}
row -=1;
if (row < 0) break;
var line = this.getLine(row);
var column = line.length-1;
}
return null;
};
this.$findClosingBracket = function(bracket, position) {
var closingBracket = this.$brackets[bracket];
var column = position.column;
var row = position.row;
var depth = 1;
var line = this.getLine(row);
var lineCount = this.getLength();
while (true) {
while(column < line.length) {
var ch = line.charAt(column);
if (ch == closingBracket) {
depth -= 1;
if (depth == 0) {
return {row: row, column: column};
}
}
else if (ch == bracket) {
depth +=1;
}
column += 1;
}
row +=1;
if (row >= lineCount) break;
var line = this.getLine(row);
var column = 0;
}
return null;
};
this.insert = function(position, text) {
return this.doc.insert(position, text);
};
this.remove = function(range) {
return this.doc.remove(range);
};
this.undoChanges = function(deltas, dontSelect) {
if (!deltas.length)
return;
this.$fromUndo = true;
var lastUndoRange = null;
for (var i = deltas.length - 1; i != -1; i--) {
delta = deltas[i];
if (delta.group == "doc") {
this.doc.revertDeltas(delta.deltas);
lastUndoRange =
this.$getUndoSelection(delta.deltas, true, lastUndoRange);
} else {
delta.deltas.forEach(function(foldDelta) {
this.addFolds(foldDelta.folds);
}, this);
}
}
this.$fromUndo = false;
lastUndoRange &&
!dontSelect &&
this.selection.setSelectionRange(lastUndoRange);
return lastUndoRange;
},
this.redoChanges = function(deltas, dontSelect) {
if (!deltas.length)
return;
this.$fromUndo = true;
var lastUndoRange = null;
for (var i = 0; i < deltas.length; i++) {
delta = deltas[i];
if (delta.group == "doc") {
this.doc.applyDeltas(delta.deltas);
lastUndoRange =
this.$getUndoSelection(delta.deltas, false, lastUndoRange);
}
}
this.$fromUndo = false;
lastUndoRange &&
!dontSelect &&
this.selection.setSelectionRange(lastUndoRange);
return lastUndoRange;
},
this.$getUndoSelection = function(deltas, isUndo, lastUndoRange) {
function isInsert(delta) {
var insert =
delta.action == "insertText" || delta.action == "insertLines";
return isUndo ? !insert : insert;
}
var delta = deltas[0];
var range, point;
var lastDeltaIsInsert = false;
if (isInsert(delta)) {
range = delta.range.clone();
lastDeltaIsInsert = true;
} else {
range = Range.fromPoints(delta.range.start, delta.range.start);
lastDeltaIsInsert = false;
}
for (var i = 1; i < deltas.length; i++) {
delta = deltas[i];
if (isInsert(delta)) {
point = delta.range.start;
if (range.compare(point.row, point.column) == -1) {
range.setStart(delta.range.start);
}
point = delta.range.end;
if (range.compare(point.row, point.column) == 1) {
range.setEnd(delta.range.end);
}
lastDeltaIsInsert = true;
} else {
point = delta.range.start;
if (range.compare(point.row, point.column) == -1) {
range =
Range.fromPoints(delta.range.start, delta.range.start);
}
lastDeltaIsInsert = false;
}
}
// Check if this range and the last undo range has something in common.
// If true, merge the ranges.
if (lastUndoRange != null) {
var cmp = lastUndoRange.compareRange(range);
if (cmp == 1) {
range.setStart(lastUndoRange.start);
} else if (cmp == -1) {
range.setEnd(lastUndoRange.end);
}
}
return range;
},
this.replace = function(range, text) {
return this.doc.replace(range, text);
};
/**
* Move a range of text from the given range to the given position.
*
* @param fromRange {Range} The range of text you want moved within the
* document.
* @param toPosition {Object} The location (row and column) where you want
* to move the text to.
* @return {Range} The new range where the text was moved to.
*/
this.moveText = function(fromRange, toPosition) {
var text = this.getTextRange(fromRange);
this.remove(fromRange);
var toRow = toPosition.row;
var toColumn = toPosition.column;
// Make sure to update the insert location, when text is removed in
// front of the chosen point of insertion.
if (!fromRange.isMultiLine() && fromRange.start.row == toRow &&
fromRange.end.column < toColumn)
toColumn -= text.length;
if (fromRange.isMultiLine() && fromRange.end.row < toRow) {
var lines = this.doc.$split(text);
toRow -= lines.length - 1;
}
var endRow = toRow + fromRange.end.row - fromRange.start.row;
var endColumn = fromRange.isMultiLine() ?
fromRange.end.column :
toColumn + fromRange.end.column - fromRange.start.column;
var toRange = new Range(toRow, toColumn, endRow, endColumn);
this.insert(toRange.start, text);
return toRange;
};
this.indentRows = function(startRow, endRow, indentString) {
indentString = indentString.replace(/\t/g, this.getTabString());
for (var row=startRow; row<=endRow; row++) {
this.insert({row: row, column:0}, indentString);
}
};
this.outdentRows = function (range) {
var rowRange = range.collapseRows();
var deleteRange = new Range(0, 0, 0, 0);
var size = this.getTabSize();
for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) {
var line = this.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
for (var j = 0; j < size; ++j)
if (line.charAt(j) != ' ')
break;
if (j < size && line.charAt(j) == '\t') {
deleteRange.start.column = j;
deleteRange.end.column = j + 1;
} else {
deleteRange.start.column = 0;
deleteRange.end.column = j;
}
this.remove(deleteRange);
}
};
this.moveLinesUp = function(firstRow, lastRow) {
if (firstRow <= 0) return 0;
var removed = this.doc.removeLines(firstRow, lastRow);
this.doc.insertLines(firstRow - 1, removed);
return -1;
};
this.moveLinesDown = function(firstRow, lastRow) {
if (lastRow >= this.doc.getLength()-1) return 0;
var removed = this.doc.removeLines(firstRow, lastRow);
this.doc.insertLines(firstRow+1, removed);
return 1;
};
this.duplicateLines = function(firstRow, lastRow) {
var firstRow = this.$clipRowToDocument(firstRow);
var lastRow = this.$clipRowToDocument(lastRow);
var lines = this.getLines(firstRow, lastRow);
this.doc.insertLines(firstRow, lines);
var addedRows = lastRow - firstRow + 1;
return addedRows;
};
this.$clipRowToDocument = function(row) {
return Math.max(0, Math.min(row, this.doc.getLength()-1));
};
this.$clipPositionToDocument = function(row, column) {
column = Math.max(0, column);
if (row < 0) {
row = 0;
column = 0;
} else {
var len = this.doc.getLength();
if (row >= len) {
row = len - 1;
column = this.doc.getLine(len-1).length;
} else {
column = Math.min(this.doc.getLine(row).length, column);
}
}
return {
row: row,
column: column
};
};
// WRAPMODE
this.$wrapLimit = 80;
this.$useWrapMode = false;
this.$wrapLimitRange = {
min : null,
max : null
};
this.setUseWrapMode = function(useWrapMode) {
if (useWrapMode != this.$useWrapMode) {
this.$useWrapMode = useWrapMode;
this.$modified = true;
this.$resetRowCache(0);
// If wrapMode is activaed, the wrapData array has to be initialized.
if (useWrapMode) {
var len = this.getLength();
this.$wrapData = [];
for (i = 0; i < len; i++) {
this.$wrapData.push([]);
}
this.$updateWrapData(0, len - 1);
}
this._dispatchEvent("changeWrapMode");
}
};
this.getUseWrapMode = function() {
return this.$useWrapMode;
};
// Allow the wrap limit to move freely between min and max. Either
// parameter can be null to allow the wrap limit to be unconstrained
// in that direction. Or set both parameters to the same number to pin
// the limit to that value.
this.setWrapLimitRange = function(min, max) {
if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) {
this.$wrapLimitRange.min = min;
this.$wrapLimitRange.max = max;
this.$modified = true;
// This will force a recalculation of the wrap limit
this._dispatchEvent("changeWrapMode");
}
};
// This should generally only be called by the renderer when a resize
// is detected.
this.adjustWrapLimit = function(desiredLimit) {
var wrapLimit = this.$constrainWrapLimit(desiredLimit);
if (wrapLimit != this.$wrapLimit && wrapLimit > 0) {
this.$wrapLimit = wrapLimit;
this.$modified = true;
if (this.$useWrapMode) {
this.$updateWrapData(0, this.getLength() - 1);
this.$resetRowCache(0)
this._dispatchEvent("changeWrapLimit");
}
return true;
}
return false;
};
this.$constrainWrapLimit = function(wrapLimit) {
var min = this.$wrapLimitRange.min;
if (min)
wrapLimit = Math.max(min, wrapLimit);
var max = this.$wrapLimitRange.max;
if (max)
wrapLimit = Math.min(max, wrapLimit);
// What would a limit of 0 even mean?
return Math.max(1, wrapLimit);
};
this.getWrapLimit = function() {
return this.$wrapLimit;
};
this.getWrapLimitRange = function() {
// Avoid unexpected mutation by returning a copy
return {
min : this.$wrapLimitRange.min,
max : this.$wrapLimitRange.max
};
};
this.$updateInternalDataOnChange = function(e) {
var useWrapMode = this.$useWrapMode;
var len;
var action = e.data.action;
var firstRow = e.data.range.start.row,
lastRow = e.data.range.end.row,
start = e.data.range.start,
end = e.data.range.end;
var removedFolds = null;
if (action.indexOf("Lines") != -1) {
if (action == "insertLines") {
lastRow = firstRow + (e.data.lines.length);
} else {
lastRow = firstRow;
}
len = e.data.lines.length;
} else {
len = lastRow - firstRow;
}
if (len != 0) {
if (action.indexOf("remove") != -1) {
useWrapMode && this.$wrapData.splice(firstRow, len);
var foldLines = this.$foldData;
removedFolds = this.getFoldsInRange(e.data.range);
this.removeFolds(removedFolds);
var foldLine = this.getFoldLine(end.row);
var idx = 0;
if (foldLine) {
foldLine.addRemoveChars(end.row, end.column, start.column - end.column);
foldLine.shiftRow(-len);
var foldLineBefore = this.getFoldLine(firstRow);
if (foldLineBefore && foldLineBefore !== foldLine) {
foldLineBefore.merge(foldLine);
foldLine = foldLineBefore;
}
idx = foldLines.indexOf(foldLine) + 1;
}
for (idx; idx < foldLines.length; idx++) {
var foldLine = foldLines[idx];
if (foldLine.start.row >= end.row) {
foldLine.shiftRow(-len);
}
}
lastRow = firstRow;
} else {
var args;
if (useWrapMode) {
args = [firstRow, 0];
for (var i = 0; i < len; i++) args.push([]);
this.$wrapData.splice.apply(this.$wrapData, args);
}
// If some new line is added inside of a foldLine, then split
// the fold line up.
var foldLines = this.$foldData;
var foldLine = this.getFoldLine(firstRow);
var idx = 0;
if (foldLine) {
var cmp = foldLine.range.compareInside(start.row, start.column)
// Inside of the foldLine range. Need to split stuff up.
if (cmp == 0) {
foldLine = foldLine.split(start.row, start.column);
foldLine.shiftRow(len);
foldLine.addRemoveChars(
lastRow, 0, end.column - start.column);
} else
// Infront of the foldLine but same row. Need to shift column.
if (cmp == -1) {
foldLine.addRemoveChars(firstRow, 0, end.column - start.column);
foldLine.shiftRow(len);
}
// Nothing to do if the insert is after the foldLine.
idx = foldLines.indexOf(foldLine) + 1;
}
for (idx; idx < foldLines.length; idx++) {
var foldLine = foldLines[idx];
if (foldLine.start.row >= firstRow) {
foldLine.shiftRow(len);
}
}
}
} else {
// Realign folds. E.g. if you add some new chars before a fold, the
// fold should "move" to the right.
var column;
len = Math.abs(e.data.range.start.column - e.data.range.end.column);
if (action.indexOf("remove") != -1) {
// Get all the folds in the change range and remove them.
removedFolds = this.getFoldsInRange(e.data.range);
this.removeFolds(removedFolds);
len = -len;
}
var foldLine = this.getFoldLine(firstRow);
if (foldLine) {
foldLine.addRemoveChars(firstRow, start.column, len);
}
}
if (useWrapMode && this.$wrapData.length != this.doc.getLength()) {
console.error("doc.getLength() and $wrapData.length have to be the same!");
}
useWrapMode && this.$updateWrapData(firstRow, lastRow);
return removedFolds;
};
this.$updateWrapData = function(firstRow, lastRow) {
var lines = this.doc.getAllLines();
var tabSize = this.getTabSize();
var wrapData = this.$wrapData;
var wrapLimit = this.$wrapLimit;
var tokens;
var foldLine;
var row = firstRow;
lastRow = Math.min(lastRow, lines.length - 1);
while (row <= lastRow) {
foldLine = this.getFoldLine(row);
if (!foldLine) {
tokens = this.$getDisplayTokens(lang.stringTrimRight(lines[row]));
} else {
tokens = [];
foldLine.walk(
function(placeholder, row, column, lastColumn) {
var walkTokens;
if (placeholder) {
walkTokens = this.$getDisplayTokens(
placeholder, tokens.length);
walkTokens[0] = PLACEHOLDER_START;
for (var i = 1; i < walkTokens.length; i++) {
walkTokens[i] = PLACEHOLDER_BODY;
}
} else {
walkTokens = this.$getDisplayTokens(
lines[row].substring(lastColumn, column),
tokens.length);
}
tokens = tokens.concat(walkTokens);
}.bind(this),
foldLine.end.row,
lines[foldLine.end.row].length + 1
);
// Remove spaces/tabs from the back of the token array.
while (tokens.length != 0
&& tokens[tokens.length - 1] >= SPACE)
{
tokens.pop();
}
}
wrapData[row] =
this.$computeWrapSplits(tokens, wrapLimit, tabSize);
row = this.getRowFoldEnd(row) + 1;
}
};
// "Tokens"
var CHAR = 1,
CHAR_EXT = 2,
PLACEHOLDER_START = 3,
PLACEHOLDER_BODY = 4,
SPACE = 10,
TAB = 11,
TAB_SPACE = 12;
this.$computeWrapSplits = function(tokens, wrapLimit, tabSize) {
if (tokens.length == 0) {
return [];
}
var tabSize = this.getTabSize();
var splits = [];
var displayLength = tokens.length;
var lastSplit = 0, lastDocSplit = 0;
function addSplit(screenPos) {
var displayed = tokens.slice(lastSplit, screenPos);
// The document size is the current size - the extra width for tabs
// and multipleWidth characters.
var len = displayed.length;
displayed.join("").
// Get all the TAB_SPACEs.
replace(/12/g, function(m) {
len -= 1;
}).
// Get all the CHAR_EXT/multipleWidth characters.
replace(/2/g, function(m) {
len -= 1;
});
lastDocSplit += len;
splits.push(lastDocSplit);
lastSplit = screenPos;
}
while (displayLength - lastSplit > wrapLimit) {
// This is, where the split should be.
var split = lastSplit + wrapLimit;
// If there is a space or tab at this split position, then making
// a split is simple.
if (tokens[split] >= SPACE) {
// Include all following spaces + tabs in this split as well.
while (tokens[split] >= SPACE) {
split ++;
}
addSplit(split);
continue;
}
// === ELSE ===
// Check if split is inside of a placeholder. Placeholder are
// not splitable. Therefore, seek the beginning of the placeholder
// and try to place the split beofre the placeholder's start.
if (tokens[split] == PLACEHOLDER_START
|| tokens[split] == PLACEHOLDER_BODY)
{
// Seek the start of the placeholder and do the split
// before the placeholder. By definition there always
// a PLACEHOLDER_START between split and lastSplit.
for (split; split != lastSplit - 1; split--) {
if (tokens[split] == PLACEHOLDER_START) {
// split++; << No incremental here as we want to
// have the position before the Placeholder.
break;
}
}
// If the PLACEHOLDER_START is not the index of the
// last split, then we can do the split
if (split > lastSplit) {
addSplit(split);
continue;
}
// If the PLACEHOLDER_START IS the index of the last
// split, then we have to place the split after the
// placeholder. So, let's seek for the end of the placeholder.
split = lastSplit + wrapLimit;
for (split; split < tokens.length; split++) {
if (tokens[split] != PLACEHOLDER_BODY)
{
break;
}
}
// If spilt == tokens.length, then the placeholder is the last
// thing in the line and adding a new split doesn't make sense.
if (split == tokens.length) {
break; // Breaks the while-loop.
}
// Finally, add the split...
addSplit(split);
continue;
}
// === ELSE ===
// Search for the first non space/tab/placeholder token backwards.
for (split; split != lastSplit - 1; split--) {
if (tokens[split] >= PLACEHOLDER_START) {
split++;
break;
}
}
// If we found one, then add the split.
if (split > lastSplit) {
addSplit(split);
continue;
}
// === ELSE ===
split = lastSplit + wrapLimit;
// The split is inside of a CHAR or CHAR_EXT token and no space
// around -> force a split.
addSplit(lastSplit + wrapLimit);
}
return splits;
}
/**
* @param
* offset: The offset in screenColumn at which position str starts.
* Important for calculating the realTabSize.
*/
this.$getDisplayTokens = function(str, offset) {
var arr = [];
var tabSize;
offset = offset || 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
// Tab
if (c == 9) {
tabSize = this.getScreenTabSize(arr.length + offset);
arr.push(TAB);
for (var n = 1; n < tabSize; n++) {
arr.push(TAB_SPACE);
}
}
// Space
else if(c == 32) {
arr.push(SPACE);
}
// full width characters
else if (isFullWidth(c)) {
arr.push(CHAR, CHAR_EXT);
} else {
arr.push(CHAR);
}
}
return arr;
}
/**
* Calculates the width of the a string on the screen while assuming that
* the string starts at the first column on the screen.
*
* @param string str String to calculate the screen width of
* @return array
* [0]: number of columns for str on screen.
* [1]: docColumn position that was read until (useful with screenColumn)
*/
this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) {
if (maxScreenColumn == 0) {
return [0, 0];
}
if (maxScreenColumn == null) {
maxScreenColumn = screenColumn +
str.length * Math.max(this.getTabSize(), 2);
}
screenColumn = screenColumn || 0;
var c, column;
for (column = 0; column < str.length; column++) {
c = str.charCodeAt(column);
// tab
if (c == 9) {
screenColumn += this.getScreenTabSize(screenColumn);
}
// full width characters
else if (isFullWidth(c)) {
screenColumn += 2;
} else {
screenColumn += 1;
}
if (screenColumn > maxScreenColumn) {
break
}
}
return [screenColumn, column];
}
/**
* Returns the number of rows required to render this row on the screen
*/
this.getRowLength = function(row) {
if (!this.$useWrapMode || !this.$wrapData[row]) {
return 1;
} else {
return this.$wrapData[row].length + 1;
}
}
/**
* Returns the height in pixels required to render this row on the screen
**/
this.getRowHeight = function(config, row) {
return this.getRowLength(row) * config.lineHeight;
}
this.getScreenLastRowColumn = function(screenRow) {
//return this.screenToDocumentColumn(screenRow, Number.MAX_VALUE / 10)
return this.documentToScreenColumn(screenRow, this.doc.getLine(screenRow).length);
};
this.getDocumentLastRowColumn = function(docRow, docColumn) {
var screenRow = this.documentToScreenRow(docRow, docColumn);
return this.getScreenLastRowColumn(screenRow);
};
this.getDocumentLastRowColumnPosition = function(docRow, docColumn) {
var screenRow = this.documentToScreenRow(docRow, docColumn);
return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10);
};
this.getRowSplitData = function(row) {
if (!this.$useWrapMode) {
return undefined;
} else {
return this.$wrapData[row];
}
};
/**
* Returns the width of a tab character at screenColumn.
*/
this.getScreenTabSize = function(screenColumn) {
return this.$tabSize - screenColumn % this.$tabSize;
};
this.screenToDocumentRow = function(screenRow, screenColumn) {
return this.screenToDocumentPosition(screenRow, screenColumn).row;
};
this.screenToDocumentColumn = function(screenRow, screenColumn) {
return this.screenToDocumentPosition(screenRow, screenColumn).column;
};
this.screenToDocumentPosition = function(screenRow, screenColumn) {
if (screenRow < 0) {
return {
row: 0,
column: 0
}
}
var line;
var docRow = 0;
var docColumn = 0;
var column;
var foldLineRowLength;
var row = 0;
var rowLength = 0;
var rowCache = this.$rowCache;
for (var i = 0; i < rowCache.length; i++) {
if (rowCache[i].screenRow < screenRow) {
row = rowCache[i].screenRow;
docRow = rowCache[i].docRow;
}
else {
break;
}
}
var doCache = !rowCache.length || i == rowCache.length;
// clamp row before clamping column, for selection on last line
var maxRow = this.getLength() - 1;
var foldLine = this.getNextFold(docRow);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (row <= screenRow) {
rowLength = this.getRowLength(docRow);
if (row + rowLength - 1 >= screenRow || docRow >= maxRow) {
break;
} else {
row += rowLength;
docRow++;
if (docRow > foldStart) {
docRow = foldLine.end.row+1;
foldLine = this.getNextFold(docRow);
foldStart = foldLine ? foldLine.start.row : Infinity;
}
}
if (doCache) {
rowCache.push({
docRow: docRow,
screenRow: row
});
}
}
if (foldLine && foldLine.start.row <= docRow)
line = this.getFoldDisplayLine(foldLine);
else {
line = this.getLine(docRow);
foldLine = null;
}
var splits = [];
if (this.$useWrapMode) {
splits = this.$wrapData[docRow];
if (splits) {
column = splits[screenRow - row]
if(screenRow > row && splits.length) {
docColumn = splits[screenRow - row - 1] || splits[splits.length - 1];
line = line.substring(docColumn);
}
}
}
docColumn += this.$getStringScreenWidth(line, screenColumn)[1];
// clip row at the end of the document
if (row + splits.length < screenRow)
docColumn = Number.MAX_VALUE;
// Need to do some clamping action here.
if (this.$useWrapMode) {
if (docColumn >= column) {
// We remove one character at the end such that the docColumn
// position returned is not associated to the next row on the
// screen.
docColumn = column - 1;
}
} else {
docColumn = Math.min(docColumn, line.length);
}
if (foldLine) {
return foldLine.idxToPosition(docColumn);
}
return {
row: docRow,
column: docColumn
}
};
this.documentToScreenPosition = function(docRow, docColumn) {
// Normalize the passed in arguments.
if (typeof docColumn === "undefined")
var pos = this.$clipPositionToDocument(docRow.row, docRow.column);
else
pos = this.$clipPositionToDocument(docRow, docColumn);
docRow = pos.row;
docColumn = pos.column;
var LL = this.$rowCache.length;
var wrapData;
// Special case in wrapMode if the doc is at the end of the document.
if (this.$useWrapMode) {
wrapData = this.$wrapData;
if (docRow > wrapData.length - 1) {
return {
row: this.getScreenLength(),
column: wrapData.length == 0
? 0
: (wrapData[wrapData.length - 1].length - 1)
};
}
}
var screenRow = 0;
var screenColumn = 0;
var foldStartRow = null;
var fold = null;
// Clamp the docRow position in case it's inside of a folded block.
fold = this.getFoldAt(docRow, docColumn, 1);
if (fold) {
docRow = fold.start.row;
docColumn = fold.start.column;
}
var rowEnd, row = 0;
var rowCache = this.$rowCache;
for (var i = 0; i < rowCache.length; i++) {
if (rowCache[i].docRow < docRow) {
screenRow = rowCache[i].screenRow;
row = rowCache[i].docRow;
} else {
break;
}
}
var doCache = !rowCache.length || i == rowCache.length;
var foldLine = this.getNextFold(row);
var foldStart = foldLine ?foldLine.start.row :Infinity;
while (row < docRow) {
if (row >= foldStart) {
rowEnd = foldLine.end.row + 1;
if (rowEnd > docRow)
break;
foldLine = this.getNextFold(rowEnd);
foldStart = foldLine ?foldLine.start.row :Infinity;
}
else {
rowEnd = row + 1;
}
screenRow += this.getRowLength(row);
row = rowEnd;
if (doCache) {
rowCache.push({
docRow: row,
screenRow: screenRow
});
}
}
// Calculate the text line that is displayed in docRow on the screen.
var textLine = "";
// Check if the final row we want to reach is inside of a fold.
if (foldLine && row >= foldStart) {
textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn);
foldStartRow = foldLine.start.row;
} else {
textLine = this.getLine(docRow).substring(0, docColumn);
foldStartRow = docRow;
}
// Clamp textLine if in wrapMode.
if (this.$useWrapMode) {
var wrapRow = wrapData[foldStartRow];
var screenRowOffset = 0;
while (textLine.length >= wrapRow[screenRowOffset]) {
screenRow ++;
screenRowOffset++;
}
textLine = textLine.substring(
wrapRow[screenRowOffset - 1] || 0, textLine.length
);
}
return {
row: screenRow,
column: this.$getStringScreenWidth(textLine)[0]
};
};
this.documentToScreenColumn = function(row, docColumn) {
return this.documentToScreenPosition(row, docColumn).column;
};
this.documentToScreenRow = function(docRow, docColumn) {
return this.documentToScreenPosition(docRow, docColumn).row;
};
this.getScreenLength = function() {
var screenRows = 0;
var lastFoldLine = null;
var foldLine = null;
if (!this.$useWrapMode) {
screenRows = this.getLength();
// Remove the folded lines again.
var foldData = this.$foldData;
for (var i = 0; i < foldData.length; i++) {
foldLine = foldData[i];
screenRows -= foldLine.end.row - foldLine.start.row;
}
} else {
for (var row = 0; row < this.$wrapData.length; row++) {
if (foldLine = this.getFoldLine(row, lastFoldLine)) {
row = foldLine.end.row;
screenRows += 1;
} else {
screenRows += this.$wrapData[row].length + 1;
}
}
}
return screenRows;
}
// For every keystroke this gets called once per char in the whole doc!!
// Wouldn't hurt to make it a bit faster for c >= 0x1100
function isFullWidth(c) {
if (c < 0x1100)
return false;
return c >= 0x1100 && c <= 0x115F ||
c >= 0x11A3 && c <= 0x11A7 ||
c >= 0x11FA && c <= 0x11FF ||
c >= 0x2329 && c <= 0x232A ||
c >= 0x2E80 && c <= 0x2E99 ||
c >= 0x2E9B && c <= 0x2EF3 ||
c >= 0x2F00 && c <= 0x2FD5 ||
c >= 0x2FF0 && c <= 0x2FFB ||
c >= 0x3000 && c <= 0x303E ||
c >= 0x3041 && c <= 0x3096 ||
c >= 0x3099 && c <= 0x30FF ||
c >= 0x3105 && c <= 0x312D ||
c >= 0x3131 && c <= 0x318E ||
c >= 0x3190 && c <= 0x31BA ||
c >= 0x31C0 && c <= 0x31E3 ||
c >= 0x31F0 && c <= 0x321E ||
c >= 0x3220 && c <= 0x3247 ||
c >= 0x3250 && c <= 0x32FE ||
c >= 0x3300 && c <= 0x4DBF ||
c >= 0x4E00 && c <= 0xA48C ||
c >= 0xA490 && c <= 0xA4C6 ||
c >= 0xA960 && c <= 0xA97C ||
c >= 0xAC00 && c <= 0xD7A3 ||
c >= 0xD7B0 && c <= 0xD7C6 ||
c >= 0xD7CB && c <= 0xD7FB ||
c >= 0xF900 && c <= 0xFAFF ||
c >= 0xFE10 && c <= 0xFE19 ||
c >= 0xFE30 && c <= 0xFE52 ||
c >= 0xFE54 && c <= 0xFE66 ||
c >= 0xFE68 && c <= 0xFE6B ||
c >= 0xFF01 && c <= 0xFF60 ||
c >= 0xFFE0 && c <= 0xFFE6;
};
}).call(EditSession.prototype);
require("ace/edit_session/folding").Folding.call(EditSession.prototype);
exports.EditSession = EditSession;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/selection', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/lang', 'pilot/event_emitter', 'ace/range'], function(require, exports, module) {
var oop = require("pilot/oop");
var lang = require("pilot/lang");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Range = require("ace/range").Range;
/**
* Keeps cursor position and the text selection of an edit session.
*
* The row/columns used in the selection are in document coordinates
* representing ths coordinates as thez appear in the document
* before applying soft wrap and folding.
*/
var Selection = function(session) {
this.session = session;
this.doc = session.getDocument();
this.clearSelection();
this.selectionLead = this.doc.createAnchor(0, 0);
this.selectionAnchor = this.doc.createAnchor(0, 0);
var _self = this;
this.selectionLead.on("change", function(e) {
_self._dispatchEvent("changeCursor");
if (!_self.$isEmpty)
_self._dispatchEvent("changeSelection");
if (!_self.$preventUpdateDesiredColumnOnChange && e.old.column != e.value.column)
_self.$updateDesiredColumn();
});
this.selectionAnchor.on("change", function() {
if (!_self.$isEmpty)
_self._dispatchEvent("changeSelection");
});
};
(function() {
oop.implement(this, EventEmitter);
this.isEmpty = function() {
return (this.$isEmpty || (
this.selectionAnchor.row == this.selectionLead.row &&
this.selectionAnchor.column == this.selectionLead.column
));
};
this.isMultiLine = function() {
if (this.isEmpty()) {
return false;
}
return this.getRange().isMultiLine();
};
this.getCursor = function() {
return this.selectionLead.getPosition();
};
this.setSelectionAnchor = function(row, column) {
this.selectionAnchor.setPosition(row, column);
if (this.$isEmpty) {
this.$isEmpty = false;
this._dispatchEvent("changeSelection");
}
};
this.getSelectionAnchor = function() {
if (this.$isEmpty)
return this.getSelectionLead()
else
return this.selectionAnchor.getPosition();
};
this.getSelectionLead = function() {
return this.selectionLead.getPosition();
};
this.shiftSelection = function(columns) {
if (this.$isEmpty) {
this.moveCursorTo(this.selectionLead.row, this.selectionLead.column + columns);
return;
};
var anchor = this.getSelectionAnchor();
var lead = this.getSelectionLead();
var isBackwards = this.isBackwards();
if (!isBackwards || anchor.column !== 0)
this.setSelectionAnchor(anchor.row, anchor.column + columns);
if (isBackwards || lead.column !== 0) {
this.$moveSelection(function() {
this.moveCursorTo(lead.row, lead.column + columns);
});
}
};
this.isBackwards = function() {
var anchor = this.selectionAnchor;
var lead = this.selectionLead;
return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column));
};
this.getRange = function() {
var anchor = this.selectionAnchor;
var lead = this.selectionLead;
if (this.isEmpty())
return Range.fromPoints(lead, lead);
if (this.isBackwards()) {
return Range.fromPoints(lead, anchor);
}
else {
return Range.fromPoints(anchor, lead);
}
};
this.clearSelection = function() {
if (!this.$isEmpty) {
this.$isEmpty = true;
this._dispatchEvent("changeSelection");
}
};
this.selectAll = function() {
var lastRow = this.doc.getLength() - 1;
this.setSelectionAnchor(lastRow, this.doc.getLine(lastRow).length);
this.moveCursorTo(0, 0);
};
this.setSelectionRange = function(range, reverse) {
if (reverse) {
this.setSelectionAnchor(range.end.row, range.end.column);
this.selectTo(range.start.row, range.start.column);
} else {
this.setSelectionAnchor(range.start.row, range.start.column);
this.selectTo(range.end.row, range.end.column);
}
this.$updateDesiredColumn();
};
this.$updateDesiredColumn = function() {
var cursor = this.getCursor();
this.$desiredColumn = this.session.documentToScreenColumn(cursor.row, cursor.column);
};
this.$moveSelection = function(mover) {
var lead = this.selectionLead;
if (this.$isEmpty)
this.setSelectionAnchor(lead.row, lead.column);
mover.call(this);
};
this.selectTo = function(row, column) {
this.$moveSelection(function() {
this.moveCursorTo(row, column);
});
};
this.selectToPosition = function(pos) {
this.$moveSelection(function() {
this.moveCursorToPosition(pos);
});
};
this.selectUp = function() {
this.$moveSelection(this.moveCursorUp);
};
this.selectDown = function() {
this.$moveSelection(this.moveCursorDown);
};
this.selectRight = function() {
this.$moveSelection(this.moveCursorRight);
};
this.selectLeft = function() {
this.$moveSelection(this.moveCursorLeft);
};
this.selectLineStart = function() {
this.$moveSelection(this.moveCursorLineStart);
};
this.selectLineEnd = function() {
this.$moveSelection(this.moveCursorLineEnd);
};
this.selectFileEnd = function() {
this.$moveSelection(this.moveCursorFileEnd);
};
this.selectFileStart = function() {
this.$moveSelection(this.moveCursorFileStart);
};
this.selectWordRight = function() {
this.$moveSelection(this.moveCursorWordRight);
};
this.selectWordLeft = function() {
this.$moveSelection(this.moveCursorWordLeft);
};
this.selectWord = function() {
var cursor = this.getCursor();
var range = this.session.getWordRange(cursor.row, cursor.column);
this.setSelectionRange(range);
};
this.selectLine = function() {
var rowStart = this.selectionLead.row;
var rowEnd;
var foldLine = this.session.getFoldLine(rowStart);
if (foldLine) {
rowStart = foldLine.start.row;
rowEnd = foldLine.end.row;
} else {
rowEnd = rowStart;
}
this.setSelectionAnchor(rowStart, 0);
this.$moveSelection(function() {
this.moveCursorTo(rowEnd + 1, 0);
});
};
this.moveCursorUp = function() {
this.moveCursorBy(-1, 0);
};
this.moveCursorDown = function() {
this.moveCursorBy(1, 0);
};
this.moveCursorLeft = function() {
var cursor = this.selectionLead.getPosition(),
fold;
if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) {
this.moveCursorTo(fold.start.row, fold.start.column);
} else if (cursor.column == 0) {
// cursor is a line (start
if (cursor.row > 0) {
this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length);
}
}
else {
var tabSize = this.session.getTabSize();
if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column-tabSize, cursor.column).split(" ").length-1 == tabSize)
this.moveCursorBy(0, -tabSize);
else
this.moveCursorBy(0, -1);
}
};
this.moveCursorRight = function() {
var cursor = this.selectionLead.getPosition(),
fold;
if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) {
this.moveCursorTo(fold.end.row, fold.end.column);
}
else if (this.selectionLead.column == this.doc.getLine(this.selectionLead.row).length) {
if (this.selectionLead.row < this.doc.getLength() - 1) {
this.moveCursorTo(this.selectionLead.row + 1, 0);
}
}
else {
var tabSize = this.session.getTabSize();
var cursor = this.selectionLead;
if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column, cursor.column+tabSize).split(" ").length-1 == tabSize)
this.moveCursorBy(0, tabSize);
else
this.moveCursorBy(0, 1);
}
};
this.moveCursorLineStart = function() {
var row = this.selectionLead.row;
var column = this.selectionLead.column;
var screenRow = this.session.documentToScreenRow(row, column);
// Determ the doc-position of the first character at the screen line.
var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0);
// Determ the line
var beforeCursor = this.session.getDisplayLine(
row, null,
firstColumnPosition.row, firstColumnPosition.column
);
var leadingSpace = beforeCursor.match(/^\s*/);
if (leadingSpace[0].length == column) {
this.moveCursorTo(
firstColumnPosition.row, firstColumnPosition.column
);
}
else {
this.moveCursorTo(
firstColumnPosition.row,
firstColumnPosition.column + leadingSpace[0].length
);
}
};
this.moveCursorLineEnd = function() {
var lead = this.selectionLead;
var lastRowColumnPosition =
this.session.getDocumentLastRowColumnPosition(lead.row, lead.column);
this.moveCursorTo(
lastRowColumnPosition.row,
lastRowColumnPosition.column
);
};
this.moveCursorFileEnd = function() {
var row = this.doc.getLength() - 1;
var column = this.doc.getLine(row).length;
this.moveCursorTo(row, column);
};
this.moveCursorFileStart = function() {
this.moveCursorTo(0, 0);
};
this.moveCursorWordRight = function() {
var row = this.selectionLead.row;
var column = this.selectionLead.column;
var line = this.doc.getLine(row);
var rightOfCursor = line.substring(column);
var match;
this.session.nonTokenRe.lastIndex = 0;
this.session.tokenRe.lastIndex = 0;
var fold;
if (fold = this.session.getFoldAt(row, column, 1)) {
this.moveCursorTo(fold.end.row, fold.end.column);
return;
} else if (column == line.length) {
this.moveCursorRight();
return;
}
else if (match = this.session.nonTokenRe.exec(rightOfCursor)) {
column += this.session.nonTokenRe.lastIndex;
this.session.nonTokenRe.lastIndex = 0;
}
else if (match = this.session.tokenRe.exec(rightOfCursor)) {
column += this.session.tokenRe.lastIndex;
this.session.tokenRe.lastIndex = 0;
}
this.moveCursorTo(row, column);
};
this.moveCursorWordLeft = function() {
var row = this.selectionLead.row;
var column = this.selectionLead.column;
var fold;
if (fold = this.session.getFoldAt(row, column, -1)) {
this.moveCursorTo(fold.start.row, fold.start.column);
return;
}
if (column == 0) {
this.moveCursorLeft();
return;
}
var str = this.session.getFoldStringAt(row, column, -1);
if (str == null) {
str = this.doc.getLine(row).substring(0, column)
}
var leftOfCursor = lang.stringReverse(str);
var match;
this.session.nonTokenRe.lastIndex = 0;
this.session.tokenRe.lastIndex = 0;
if (match = this.session.nonTokenRe.exec(leftOfCursor)) {
column -= this.session.nonTokenRe.lastIndex;
this.session.nonTokenRe.lastIndex = 0;
}
else if (match = this.session.tokenRe.exec(leftOfCursor)) {
column -= this.session.tokenRe.lastIndex;
this.session.tokenRe.lastIndex = 0;
}
this.moveCursorTo(row, column);
};
this.moveCursorBy = function(rows, chars) {
var screenPos = this.session.documentToScreenPosition(
this.selectionLead.row,
this.selectionLead.column
);
var screenCol = (chars == 0 && this.$desiredColumn) || screenPos.column;
var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenCol);
this.moveCursorTo(docPos.row, docPos.column + chars, chars == 0);
};
this.moveCursorToPosition = function(position) {
this.moveCursorTo(position.row, position.column);
};
this.moveCursorTo = function(row, column, preventUpdateDesiredColumn) {
// Ensure the row/column is not inside of a fold.
var fold = this.session.getFoldAt(row, column, 1);
if (fold) {
row = fold.start.row;
column = fold.start.column;
}
this.$preventUpdateDesiredColumnOnChange = true;
this.selectionLead.setPosition(row, column);
this.$preventUpdateDesiredColumnOnChange = false;
if (!preventUpdateDesiredColumn)
this.$updateDesiredColumn(this.selectionLead.column);
};
this.moveCursorToScreen = function(row, column, preventUpdateDesiredColumn) {
var pos = this.session.screenToDocumentPosition(row, column);
row = pos.row;
column = pos.column;
this.moveCursorTo(row, column, preventUpdateDesiredColumn);
};
}).call(Selection.prototype);
exports.Selection = Selection;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) {
var Range = function(startRow, startColumn, endRow, endColumn) {
this.start = {
row: startRow,
column: startColumn
};
this.end = {
row: endRow,
column: endColumn
};
};
(function() {
this.toString = function() {
return ("Range: [" + this.start.row + "/" + this.start.column +
"] -> [" + this.end.row + "/" + this.end.column + "]");
};
this.contains = function(row, column) {
return this.compare(row, column) == 0;
};
/**
* Compares this range (A) with another range (B), where B is the passed in
* range.
*
* Return values:
* -2: (B) is infront of (A) and doesn't intersect with (A)
* -1: (B) begins before (A) but ends inside of (A)
* 0: (B) is completly inside of (A) OR (A) is complety inside of (B)
* +1: (B) begins inside of (A) but ends outside of (A)
* +2: (B) is after (A) and doesn't intersect with (A)
*
* 42: FTW state: (B) ends in (A) but starts outside of (A)
*/
this.compareRange = function(range) {
var cmp,
end = range.end,
start = range.start;
cmp = this.compare(end.row, end.column);
if (cmp == 1) {
cmp = this.compare(start.row, start.column);
if (cmp == 1) {
return 2;
} else if (cmp == 0) {
return 1;
} else {
return 0;
}
} else if (cmp == -1) {
return -2;
} else {
cmp = this.compare(start.row, start.column);
if (cmp == -1) {
return -1;
} else if (cmp == 1) {
return 42;
} else {
return 0;
}
}
}
this.containsRange = function(range) {
var cmp = this.compareRange(range);
return (cmp == -1 || cmp == 0 || cmp == 1);
}
this.isEnd = function(row, column) {
return this.end.row == row && this.end.column == column;
}
this.isStart = function(row, column) {
return this.start.row == row && this.start.column == column;
}
this.setStart = function(row, column) {
if (typeof row == "object") {
this.start.column = row.column;
this.start.row = row.row;
} else {
this.start.row = row;
this.start.column = column;
}
}
this.setEnd = function(row, column) {
if (typeof row == "object") {
this.end.column = row.column;
this.end.row = row.row;
} else {
this.end.row = row;
this.end.column = column;
}
}
this.inside = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column) || this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
this.insideStart = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
this.insideEnd = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
this.compare = function(row, column) {
if (!this.isMultiLine()) {
if (row === this.start.row) {
return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
};
}
if (row < this.start.row)
return -1;
if (row > this.end.row)
return 1;
if (this.start.row === row)
return column >= this.start.column ? 0 : -1;
if (this.end.row === row)
return column <= this.end.column ? 0 : 1;
return 0;
};
/**
* Like .compare(), but if isStart is true, return -1;
*/
this.compareStart = function(row, column) {
if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
}
/**
* Like .compare(), but if isEnd is true, return 1;
*/
this.compareEnd = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else {
return this.compare(row, column);
}
}
this.compareInside = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
}
this.clipRows = function(firstRow, lastRow) {
if (this.end.row > lastRow) {
var end = {
row: lastRow+1,
column: 0
};
}
if (this.start.row > lastRow) {
var start = {
row: lastRow+1,
column: 0
};
}
if (this.start.row < firstRow) {
var start = {
row: firstRow,
column: 0
};
}
if (this.end.row < firstRow) {
var end = {
row: firstRow,
column: 0
};
}
return Range.fromPoints(start || this.start, end || this.end);
};
this.extend = function(row, column) {
var cmp = this.compare(row, column);
if (cmp == 0)
return this;
else if (cmp == -1)
var start = {row: row, column: column};
else
var end = {row: row, column: column};
return Range.fromPoints(start || this.start, end || this.end);
};
this.isEmpty = function() {
return (this.start.row == this.end.row && this.start.column == this.end.column);
};
this.isMultiLine = function() {
return (this.start.row !== this.end.row);
};
this.clone = function() {
return Range.fromPoints(this.start, this.end);
};
this.collapseRows = function() {
if (this.end.column == 0)
return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
else
return new Range(this.start.row, 0, this.end.row, 0)
};
this.toScreenRange = function(session) {
var screenPosStart =
session.documentToScreenPosition(this.start);
var screenPosEnd =
session.documentToScreenPosition(this.end);
return new Range(
screenPosStart.row, screenPosStart.column,
screenPosEnd.row, screenPosEnd.column
);
};
}).call(Range.prototype);
Range.fromPoints = function(start, end) {
return new Range(start.row, start.column, end.row, end.column);
};
exports.Range = Range;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
* Chris Spencer <chris.ag.spencer AT googlemail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/text', ['require', 'exports', 'module' , 'ace/tokenizer', 'ace/mode/text_highlight_rules', 'ace/mode/behaviour', 'ace/unicode'], function(require, exports, module) {
var Tokenizer = require("ace/tokenizer").Tokenizer;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var Behaviour = require("ace/mode/behaviour").Behaviour;
var unicode = require("ace/unicode");
var Mode = function() {
this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
this.$behaviour = new Behaviour();
};
(function() {
this.tokenRe = new RegExp("^["
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]+", "g"
);
this.nonTokenRe = new RegExp("^(?:[^"
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]|\s])+", "g"
);
this.getTokenizer = function() {
return this.$tokenizer;
};
this.toggleCommentLines = function(state, doc, startRow, endRow) {
};
this.getNextLineIndent = function(state, line, tab) {
return "";
};
this.checkOutdent = function(state, line, input) {
return false;
};
this.autoOutdent = function(state, doc, row) {
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
this.createWorker = function(session) {
return null;
};
this.highlightSelection = function(editor) {
var session = editor.session;
if (!session.$selectionOccurrences)
session.$selectionOccurrences = [];
if (session.$selectionOccurrences.length)
this.clearSelectionHighlight(editor);
var selection = editor.getSelectionRange();
if (selection.isEmpty() || selection.isMultiLine())
return;
var startOuter = selection.start.column - 1;
var endOuter = selection.end.column + 1;
var line = session.getLine(selection.start.row);
var lineCols = line.length;
var needle = line.substring(Math.max(startOuter, 0),
Math.min(endOuter, lineCols));
// Make sure the outer characters are not part of the word.
if ((startOuter >= 0 && /^[\w\d]/.test(needle)) ||
(endOuter <= lineCols && /[\w\d]$/.test(needle)))
return;
needle = line.substring(selection.start.column, selection.end.column);
if (!/^[\w\d]+$/.test(needle))
return;
var cursor = editor.getCursorPosition();
var newOptions = {
wrap: true,
wholeWord: true,
caseSensitive: true,
needle: needle
};
var currentOptions = editor.$search.getOptions();
editor.$search.set(newOptions);
var ranges = editor.$search.findAll(session);
ranges.forEach(function(range) {
if (!range.contains(cursor.row, cursor.column)) {
var marker = session.addMarker(range, "ace_selected_word", "text");
session.$selectionOccurrences.push(marker);
}
});
editor.$search.set(currentOptions);
};
this.clearSelectionHighlight = function(editor) {
if (!editor.session.$selectionOccurrences)
return;
editor.session.$selectionOccurrences.forEach(function(marker) {
editor.session.removeMarker(marker);
});
editor.session.$selectionOccurrences = [];
};
this.createModeDelegates = function (mapping) {
if (!this.$embeds) {
return;
}
this.$modes = {};
for (var i = 0; i < this.$embeds.length; i++) {
if (mapping[this.$embeds[i]]) {
this.$modes[this.$embeds[i]] = new mapping[this.$embeds[i]]();
}
}
var delegations = ['toggleCommentLines', 'getNextLineIndent', 'checkOutdent', 'autoOutdent', 'transformAction'];
for (var i = 0; i < delegations.length; i++) {
(function(scope) {
var functionName = delegations[i];
var defaultHandler = scope[functionName];
scope[delegations[i]] = function() {
return this.$delegator(functionName, arguments, defaultHandler);
}
} (this));
}
}
this.$delegator = function(method, args, defaultHandler) {
var state = args[0];
for (var i = 0; i < this.$embeds.length; i++) {
if (!this.$modes[this.$embeds[i]]) continue;
var split = state.split(this.$embeds[i]);
if (!split[0] && split[1]) {
args[0] = split[1];
var mode = this.$modes[this.$embeds[i]];
return mode[method].apply(mode, args);
}
}
var ret = defaultHandler.apply(this, args);
return defaultHandler ? ret : undefined;
};
this.transformAction = function(state, action, editor, session, param) {
if (this.$behaviour) {
var behaviours = this.$behaviour.getBehaviours();
for (var key in behaviours) {
if (behaviours[key][action]) {
var ret = behaviours[key][action].apply(this, arguments);
if (ret !== false) {
return ret;
}
}
}
}
return false;
}
}).call(Mode.prototype);
exports.Mode = Mode;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/tokenizer', ['require', 'exports', 'module' ], function(require, exports, module) {
var Tokenizer = function(rules) {
this.rules = rules;
this.regExps = {};
this.matchMappings = {};
for ( var key in this.rules) {
var rule = this.rules[key];
var state = rule;
var ruleRegExps = [];
var matchTotal = 0;
var mapping = this.matchMappings[key] = {};
for ( var i = 0; i < state.length; i++) {
// Count number of matching groups. 2 extra groups from the full match
// And the catch-all on the end (used to force a match);
var matchcount = new RegExp("(?:(" + state[i].regex + ")|(.))").exec("a").length - 2;
// Replace any backreferences and offset appropriately.
var adjustedregex = state[i].regex.replace(/\\([0-9]+)/g, function (match, digit) {
return "\\" + (parseInt(digit, 10) + matchTotal + 1);
});
mapping[matchTotal] = {
rule: i,
len: matchcount
};
matchTotal += matchcount;
ruleRegExps.push(adjustedregex);
}
this.regExps[key] = new RegExp("(?:(" + ruleRegExps.join(")|(") + ")|(.))", "g");
}
};
(function() {
this.getLineTokens = function(line, startState) {
var currentState = startState;
var state = this.rules[currentState];
var mapping = this.matchMappings[currentState];
var re = this.regExps[currentState];
re.lastIndex = 0;
var match, tokens = [];
var lastIndex = 0;
var token = {
type: null,
value: ""
};
while (match = re.exec(line)) {
var type = "text";
var rule = null;
var value = [match[0]];
for (var i = 0; i < match.length-2; i++) {
if (match[i + 1] !== undefined) {
rule = state[mapping[i].rule];
if (mapping[i].len > 1) {
value = match.slice(i+2, i+1+mapping[i].len);
}
// compute token type
if (typeof rule.token == "function")
type = rule.token.apply(this, value);
else
type = rule.token;
var next = rule.next;
if (next && next !== currentState) {
currentState = next;
state = this.rules[currentState];
mapping = this.matchMappings[currentState];
lastIndex = re.lastIndex;
re = this.regExps[currentState];
re.lastIndex = lastIndex;
}
break;
}
};
if (value[0]) {
if (typeof type == "string") {
value = [value.join("")];
type = [type];
}
for (var i = 0; i < value.length; i++) {
if ((!rule || rule.merge || type[i] === "text") && token.type === type[i]) {
token.value += value[i];
} else {
if (token.type) {
tokens.push(token);
}
token = {
type: type[i],
value: value[i]
}
}
}
}
if (lastIndex == line.length)
break;
lastIndex = re.lastIndex;
};
if (token.type)
tokens.push(token);
return {
tokens : tokens,
state : currentState
};
};
}).call(Tokenizer.prototype);
exports.Tokenizer = Tokenizer;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/text_highlight_rules', ['require', 'exports', 'module' , 'pilot/lang'], function(require, exports, module) {
var lang = require("pilot/lang");
var TextHighlightRules = function() {
// regexp must not have capturing parentheses
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [{
token : "empty_line",
regex : '^$'
}, {
token : "text",
regex : ".+"
}]
};
};
(function() {
this.addRules = function(rules, prefix) {
for (var key in rules) {
var state = rules[key];
for (var i=0; i<state.length; i++) {
var rule = state[i];
if (rule.next) {
rule.next = prefix + rule.next;
} else {
rule.next = prefix + key;
}
}
this.$rules[prefix + key] = state;
}
};
this.getRules = function() {
return this.$rules;
};
this.embedRules = function (HighlightRules, prefix, escapeRules, states) {
var embedRules = new HighlightRules().getRules();
if (states) {
for (var i = 0; i < states.length; i++) {
states[i] = prefix + states[i];
}
} else {
states = [];
for (var key in embedRules) {
states.push(prefix + key);
}
}
this.addRules(embedRules, prefix);
for (var i = 0; i < states.length; i++) {
Array.prototype.unshift.apply(this.$rules[states[i]], lang.deepCopy(escapeRules));
}
if (!this.$embeds) {
this.$embeds = [];
}
this.$embeds.push(prefix);
}
this.getEmbeds = function() {
return this.$embeds;
}
}).call(TextHighlightRules.prototype);
exports.TextHighlightRules = TextHighlightRules;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Chris Spencer <chris.ag.spencer AT googlemail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/behaviour', ['require', 'exports', 'module' ], function(require, exports, module) {
var Behaviour = function() {
this.$behaviours = {};
};
(function () {
this.add = function (name, action, callback) {
switch (undefined) {
case this.$behaviours:
this.$behaviours = {};
case this.$behaviours[name]:
this.$behaviours[name] = {};
}
this.$behaviours[name][action] = callback;
}
this.addBehaviours = function (behaviours) {
for (var key in behaviours) {
for (var action in behaviours[key]) {
this.add(key, action, behaviours[key][action]);
}
}
}
this.remove = function (name) {
if (this.$behaviours && this.$behaviours[name]) {
delete this.$behaviours[name];
}
}
this.inherit = function (mode, filter) {
if (typeof mode === "function") {
var behaviours = new mode().getBehaviours(filter);
} else {
var behaviours = mode.getBehaviours(filter);
}
this.addBehaviours(behaviours);
}
this.getBehaviours = function (filter) {
if (!filter) {
return this.$behaviours;
} else {
var ret = {}
for (var i = 0; i < filter.length; i++) {
if (this.$behaviours[filter[i]]) {
ret[filter[i]] = this.$behaviours[filter[i]];
}
}
return ret;
}
}
}).call(Behaviour.prototype);
exports.Behaviour = Behaviour;
});define('ace/unicode', ['require', 'exports', 'module' ], function(require, exports, module) {
/*
XRegExp Unicode plugin pack: Categories 1.0
(c) 2010 Steven Levithan
MIT License
<http://xregexp.com>
Uses the Unicode 5.2 character database
This package for the XRegExp Unicode plugin enables the following Unicode categories (aka properties):
L - Letter (the top-level Letter category is included in the Unicode plugin base script)
Ll - Lowercase letter
Lu - Uppercase letter
Lt - Titlecase letter
Lm - Modifier letter
Lo - Letter without case
M - Mark
Mn - Non-spacing mark
Mc - Spacing combining mark
Me - Enclosing mark
N - Number
Nd - Decimal digit
Nl - Letter number
No - Other number
P - Punctuation
Pd - Dash punctuation
Ps - Open punctuation
Pe - Close punctuation
Pi - Initial punctuation
Pf - Final punctuation
Pc - Connector punctuation
Po - Other punctuation
S - Symbol
Sm - Math symbol
Sc - Currency symbol
Sk - Modifier symbol
So - Other symbol
Z - Separator
Zs - Space separator
Zl - Line separator
Zp - Paragraph separator
C - Other
Cc - Control
Cf - Format
Co - Private use
Cs - Surrogate
Cn - Unassigned
Example usage:
\p{N}
\p{Cn}
*/
// will be populated by addUnicodePackage
exports.packages = {};
addUnicodePackage({
L: "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
Ll: "0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A",
Lu: "0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A",
Lt: "01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC",
Lm: "02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F",
Lo: "01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
M: "0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26",
Mn: "0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26",
Mc: "0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC",
Me: "0488048906DE20DD-20E020E2-20E4A670-A672",
N: "0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
Nd: "0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
Nl: "16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF",
No: "00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835",
P: "0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65",
Pd: "002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D",
Ps: "0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62",
Pe: "0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63",
Pi: "00AB2018201B201C201F20392E022E042E092E0C2E1C2E20",
Pf: "00BB2019201D203A2E032E052E0A2E0D2E1D2E21",
Pc: "005F203F20402054FE33FE34FE4D-FE4FFF3F",
Po: "0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65",
S: "0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD",
Sm: "002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC",
Sc: "002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6",
Sk: "005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3",
So: "00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD",
Z: "002000A01680180E2000-200A20282029202F205F3000",
Zs: "002000A01680180E2000-200A202F205F3000",
Zl: "2028",
Zp: "2029",
C: "0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF",
Cc: "0000-001F007F-009F",
Cf: "00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB",
Co: "E000-F8FF",
Cs: "D800-DFFF",
Cn: "03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF"
});
function addUnicodePackage (pack) {
var codePoint = /\w{4}/g;
for (var name in pack)
exports.packages[name] = pack[name].replace(codePoint, "\\u$&");
};
});/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/document', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) {
var oop = require("pilot/oop");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Range = require("ace/range").Range;
var Anchor = require("ace/anchor").Anchor;
var Document = function(text) {
this.$lines = [];
if (Array.isArray(text)) {
this.insertLines(0, text);
}
// There has to be one line at least in the document. If you pass an empty
// string to the insert function, nothing will happen. Workaround.
else if (text.length == 0) {
this.$lines = [""];
} else {
this.insert({row: 0, column:0}, text);
}
};
(function() {
oop.implement(this, EventEmitter);
this.setValue = function(text) {
var len = this.getLength();
this.remove(new Range(0, 0, len, this.getLine(len-1).length));
this.insert({row: 0, column:0}, text);
};
this.getValue = function() {
return this.getAllLines().join(this.getNewLineCharacter());
};
this.createAnchor = function(row, column) {
return new Anchor(this, row, column);
};
// check for IE split bug
if ("aaa".split(/a/).length == 0)
this.$split = function(text) {
return text.replace(/\r\n|\r/g, "\n").split("\n");
}
else
this.$split = function(text) {
return text.split(/\r\n|\r|\n/);
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r?\n)/m);
if (match) {
this.$autoNewLine = match[1];
} else {
this.$autoNewLine = "\n";
}
};
this.getNewLineCharacter = function() {
switch (this.$newLineMode) {
case "windows":
return "\r\n";
case "unix":
return "\n";
case "auto":
return this.$autoNewLine;
}
},
this.$autoNewLine = "\n";
this.$newLineMode = "auto";
this.setNewLineMode = function(newLineMode) {
if (this.$newLineMode === newLineMode) return;
this.$newLineMode = newLineMode;
};
this.getNewLineMode = function() {
return this.$newLineMode;
};
this.isNewLine = function(text) {
return (text == "\r\n" || text == "\r" || text == "\n");
};
/**
* Get a verbatim copy of the given line as it is in the document
*/
this.getLine = function(row) {
return this.$lines[row] || "";
};
this.getLines = function(firstRow, lastRow) {
return this.$lines.slice(firstRow, lastRow + 1);
};
/**
* Returns all lines in the document as string array. Warning: The caller
* should not modify this array!
*/
this.getAllLines = function() {
return this.getLines(0, this.getLength());
};
this.getLength = function() {
return this.$lines.length;
};
this.getTextRange = function(range) {
if (range.start.row == range.end.row) {
return this.$lines[range.start.row].substring(range.start.column,
range.end.column);
}
else {
var lines = [];
lines.push(this.$lines[range.start.row].substring(range.start.column));
lines.push.apply(lines, this.getLines(range.start.row+1, range.end.row-1));
lines.push(this.$lines[range.end.row].substring(0, range.end.column));
return lines.join(this.getNewLineCharacter());
}
};
this.$clipPosition = function(position) {
var length = this.getLength();
if (position.row >= length) {
position.row = Math.max(0, length - 1);
position.column = this.getLine(length-1).length;
}
return position;
}
this.insert = function(position, text) {
if (text.length == 0)
return position;
position = this.$clipPosition(position);
if (this.getLength() <= 1)
this.$detectNewLine(text);
var lines = this.$split(text);
var firstLine = lines.splice(0, 1)[0];
var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0];
position = this.insertInLine(position, firstLine);
if (lastLine !== null) {
position = this.insertNewLine(position); // terminate first line
position = this.insertLines(position.row, lines);
position = this.insertInLine(position, lastLine || "");
}
return position;
};
this.insertLines = function(row, lines) {
if (lines.length == 0)
return {row: row, column: 0};
var args = [row, 0];
args.push.apply(args, lines);
this.$lines.splice.apply(this.$lines, args);
var range = new Range(row, 0, row + lines.length, 0);
var delta = {
action: "insertLines",
range: range,
lines: lines
};
this._dispatchEvent("change", { data: delta });
return range.end;
},
this.insertNewLine = function(position) {
position = this.$clipPosition(position);
var line = this.$lines[position.row] || "";
this.$lines[position.row] = line.substring(0, position.column);
this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length));
var end = {
row : position.row + 1,
column : 0
};
var delta = {
action: "insertText",
range: Range.fromPoints(position, end),
text: this.getNewLineCharacter()
};
this._dispatchEvent("change", { data: delta });
return end;
};
this.insertInLine = function(position, text) {
if (text.length == 0)
return position;
var line = this.$lines[position.row] || "";
this.$lines[position.row] = line.substring(0, position.column) + text
+ line.substring(position.column);
var end = {
row : position.row,
column : position.column + text.length
};
var delta = {
action: "insertText",
range: Range.fromPoints(position, end),
text: text
};
this._dispatchEvent("change", { data: delta });
return end;
};
this.remove = function(range) {
// clip to document
range.start = this.$clipPosition(range.start);
range.end = this.$clipPosition(range.end);
if (range.isEmpty())
return range.start;
var firstRow = range.start.row;
var lastRow = range.end.row;
if (range.isMultiLine()) {
var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1;
var lastFullRow = lastRow - 1;
if (range.end.column > 0)
this.removeInLine(lastRow, 0, range.end.column);
if (lastFullRow >= firstFullRow)
this.removeLines(firstFullRow, lastFullRow);
if (firstFullRow != firstRow) {
this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length);
this.removeNewLine(range.start.row);
}
}
else {
this.removeInLine(firstRow, range.start.column, range.end.column);
}
return range.start;
};
this.removeInLine = function(row, startColumn, endColumn) {
if (startColumn == endColumn)
return;
var range = new Range(row, startColumn, row, endColumn);
var line = this.getLine(row);
var removed = line.substring(startColumn, endColumn);
var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length);
this.$lines.splice(row, 1, newLine);
var delta = {
action: "removeText",
range: range,
text: removed
};
this._dispatchEvent("change", { data: delta });
return range.start;
};
/**
* Removes a range of full lines
*
* @param firstRow {Integer} The first row to be removed
* @param lastRow {Integer} The last row to be removed
* @return {String[]} The removed lines
*/
this.removeLines = function(firstRow, lastRow) {
var range = new Range(firstRow, 0, lastRow + 1, 0);
var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1);
var delta = {
action: "removeLines",
range: range,
nl: this.getNewLineCharacter(),
lines: removed
};
this._dispatchEvent("change", { data: delta });
return removed;
};
this.removeNewLine = function(row) {
var firstLine = this.getLine(row);
var secondLine = this.getLine(row+1);
var range = new Range(row, firstLine.length, row+1, 0);
var line = firstLine + secondLine;
this.$lines.splice(row, 2, line);
var delta = {
action: "removeText",
range: range,
text: this.getNewLineCharacter()
};
this._dispatchEvent("change", { data: delta });
};
this.replace = function(range, text) {
if (text.length == 0 && range.isEmpty())
return range.start;
// Shortcut: If the text we want to insert is the same as it is already
// in the document, we don't have to replace anything.
if (text == this.getTextRange(range))
return range.end;
this.remove(range);
if (text) {
var end = this.insert(range.start, text);
}
else {
end = range.start;
}
return end;
};
this.applyDeltas = function(deltas) {
for (var i=0; i<deltas.length; i++) {
var delta = deltas[i];
var range = Range.fromPoints(delta.range.start, delta.range.end);
if (delta.action == "insertLines")
this.insertLines(range.start.row, delta.lines)
else if (delta.action == "insertText")
this.insert(range.start, delta.text)
else if (delta.action == "removeLines")
this.removeLines(range.start.row, range.end.row - 1)
else if (delta.action == "removeText")
this.remove(range)
}
};
this.revertDeltas = function(deltas) {
for (var i=deltas.length-1; i>=0; i--) {
var delta = deltas[i];
var range = Range.fromPoints(delta.range.start, delta.range.end);
if (delta.action == "insertLines")
this.removeLines(range.start.row, range.end.row - 1)
else if (delta.action == "insertText")
this.remove(range)
else if (delta.action == "removeLines")
this.insertLines(range.start.row, delta.lines)
else if (delta.action == "removeText")
this.insert(range.start, delta.text)
}
};
}).call(Document.prototype);
exports.Document = Document;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/anchor', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
/**
* An Anchor is a floating pointer in the document. Whenever text is inserted or
* deleted before the cursor, the position of the cursor is updated
*/
var Anchor = exports.Anchor = function(doc, row, column) {
this.document = doc;
if (typeof column == "undefined")
this.setPosition(row.row, row.column);
else
this.setPosition(row, column);
this.$onChange = this.onChange.bind(this);
doc.on("change", this.$onChange);
};
(function() {
oop.implement(this, EventEmitter);
this.getPosition = function() {
return this.$clipPositionToDocument(this.row, this.column);
};
this.getDocument = function() {
return this.document;
};
this.onChange = function(e) {
var delta = e.data;
var range = delta.range;
if (range.start.row == range.end.row && range.start.row != this.row)
return;
if (range.start.row > this.row)
return;
if (range.start.row == this.row && range.start.column > this.column)
return;
var row = this.row;
var column = this.column;
if (delta.action === "insertText") {
if (range.start.row === row && range.start.column <= column) {
if (range.start.row === range.end.row) {
column += range.end.column - range.start.column;
}
else {
column -= range.start.column;
row += range.end.row - range.start.row;
}
}
else if (range.start.row !== range.end.row && range.start.row < row) {
row += range.end.row - range.start.row;
}
} else if (delta.action === "insertLines") {
if (range.start.row <= row) {
row += range.end.row - range.start.row;
}
}
else if (delta.action == "removeText") {
if (range.start.row == row && range.start.column < column) {
if (range.end.column >= column)
column = range.start.column;
else
column = Math.max(0, column - (range.end.column - range.start.column));
} else if (range.start.row !== range.end.row && range.start.row < row) {
if (range.end.row == row) {
column = Math.max(0, column - range.end.column) + range.start.column;
}
row -= (range.end.row - range.start.row);
}
else if (range.end.row == row) {
row -= range.end.row - range.start.row;
column = Math.max(0, column - range.end.column) + range.start.column;
}
} else if (delta.action == "removeLines") {
if (range.start.row <= row) {
if (range.end.row <= row)
row -= range.end.row - range.start.row;
else {
row = range.start.row;
column = 0;
}
}
}
this.setPosition(row, column, true);
};
this.setPosition = function(row, column, noClip) {
var pos;
if (noClip) {
pos = {
row: row,
column: column
};
}
else {
pos = this.$clipPositionToDocument(row, column);
}
if (this.row == pos.row && this.column == pos.column)
return;
var old = {
row: this.row,
column: this.column
};
this.row = pos.row;
this.column = pos.column;
this._dispatchEvent("change", {
old: old,
value: pos
});
};
this.detach = function() {
this.document.removeEventListener("change", this.$onChange);
};
this.$clipPositionToDocument = function(row, column) {
var pos = {};
if (row >= this.document.getLength()) {
pos.row = Math.max(0, this.document.getLength() - 1);
pos.column = this.document.getLine(pos.row).length;
}
else if (row < 0) {
pos.row = 0;
pos.column = 0;
}
else {
pos.row = row;
pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
}
if (column < 0)
pos.column = 0;
return pos;
};
}).call(Anchor.prototype);
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/background_tokenizer', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var BackgroundTokenizer = function(tokenizer, editor) {
this.running = false;
this.lines = [];
this.currentLine = 0;
this.tokenizer = tokenizer;
var self = this;
this.$worker = function() {
if (!self.running) { return; }
var workerStart = new Date();
var startLine = self.currentLine;
var doc = self.doc;
var processedLines = 0;
var len = doc.getLength();
while (self.currentLine < len) {
self.lines[self.currentLine] = self.$tokenizeRows(self.currentLine, self.currentLine)[0];
self.currentLine++;
// only check every 5 lines
processedLines += 1;
if ((processedLines % 5 == 0) && (new Date() - workerStart) > 20) {
self.fireUpdateEvent(startLine, self.currentLine-1);
self.running = setTimeout(self.$worker, 20);
return;
}
}
self.running = false;
self.fireUpdateEvent(startLine, len - 1);
};
};
(function(){
oop.implement(this, EventEmitter);
this.setTokenizer = function(tokenizer) {
this.tokenizer = tokenizer;
this.lines = [];
this.start(0);
};
this.setDocument = function(doc) {
this.doc = doc;
this.lines = [];
this.stop();
};
this.fireUpdateEvent = function(firstRow, lastRow) {
var data = {
first: firstRow,
last: lastRow
};
this._dispatchEvent("update", {data: data});
};
this.start = function(startRow) {
this.currentLine = Math.min(startRow || 0, this.currentLine,
this.doc.getLength());
// remove all cached items below this line
this.lines.splice(this.currentLine, this.lines.length);
this.stop();
// pretty long delay to prevent the tokenizer from interfering with the user
this.running = setTimeout(this.$worker, 700);
};
this.stop = function() {
if (this.running)
clearTimeout(this.running);
this.running = false;
};
this.getTokens = function(firstRow, lastRow) {
return this.$tokenizeRows(firstRow, lastRow);
};
this.getState = function(row) {
return this.$tokenizeRows(row, row)[0].state;
};
this.$tokenizeRows = function(firstRow, lastRow) {
if (!this.doc)
return [];
var rows = [];
// determine start state
var state = "start";
var doCache = false;
if (firstRow > 0 && this.lines[firstRow - 1]) {
state = this.lines[firstRow - 1].state;
doCache = true;
} else if (firstRow == 0) {
state = "start";
doCache = true;
} else if (this.lines.length > 0) {
// Guess that we haven't changed state.
state = this.lines[this.lines.length-1].state;
}
var lines = this.doc.getLines(firstRow, lastRow);
for (var row=firstRow; row<=lastRow; row++) {
if (!this.lines[row]) {
var tokens = this.tokenizer.getLineTokens(lines[row-firstRow] || "", state);
var state = tokens.state;
rows.push(tokens);
if (doCache) {
this.lines[row] = tokens;
}
}
else {
var tokens = this.lines[row];
state = tokens.state;
rows.push(tokens);
}
}
return rows;
};
}).call(BackgroundTokenizer.prototype);
exports.BackgroundTokenizer = BackgroundTokenizer;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/edit_session/folding', ['require', 'exports', 'module' , 'ace/range', 'ace/edit_session/fold_line', 'ace/edit_session/fold'], function(require, exports, module) {
var Range = require("ace/range").Range;
var FoldLine = require("ace/edit_session/fold_line").FoldLine;
var Fold = require("ace/edit_session/fold").Fold;
function Folding() {
/**
* Looks up a fold at a given row/column. Possible values for side:
* -1: ignore a fold if fold.start = row/column
* +1: ignore a fold if fold.end = row/column
*/
this.getFoldAt = function(row, column, side) {
var foldLine = this.getFoldLine(row);
if (!foldLine)
return null;
var folds = foldLine.folds;
for (var i = 0; i < folds.length; i++) {
var fold = folds[i];
if (fold.range.contains(row, column)) {
if (side == 1 && fold.range.isEnd(row, column)) {
continue;
} else if (side == -1 && fold.range.isStart(row, column)) {
continue;
}
return fold;
}
}
};
/**
* Returns all folds in the given range. Note, that this will return folds
*
*/
this.getFoldsInRange = function(range) {
range = range.clone();
var start = range.start;
var end = range.end;
var foldLines = this.$foldData;
var foundFolds = [];
start.column += 1;
end.column -= 1;
for (var i = 0; i < foldLines.length; i++) {
var cmp = foldLines[i].range.compareRange(range);
if (cmp == 2) {
// Range is before foldLine. No intersection. This means,
// there might be other foldLines that intersect.
continue;
}
else if (cmp == -2) {
// Range is after foldLine. There can't be any other foldLines then,
// so let's give up.
break;
}
var folds = foldLines[i].folds;
for (var j = 0; j < folds.length; j++) {
var fold = folds[j];
cmp = fold.range.compareRange(range);
if (cmp == -2) {
break;
} else if (cmp == 2) {
continue;
} else
// WTF-state: Can happen due to -1/+1 to start/end column.
if (cmp == 42) {
break;
}
foundFolds.push(fold);
}
}
return foundFolds;
}
/**
* Returns the string between folds at the given position.
* E.g.
* foo<fold>b|ar<fold>wolrd -> "bar"
* foo<fold>bar<fold>wol|rd -> "world"
* foo<fold>bar<fo|ld>wolrd -> <null>
*
* where | means the position of row/column
*
* The trim option determs if the return string should be trimed according
* to the "side" passed with the trim value:
*
* E.g.
* foo<fold>b|ar<fold>wolrd -trim=-1> "b"
* foo<fold>bar<fold>wol|rd -trim=+1> "rld"
* fo|o<fold>bar<fold>wolrd -trim=00> "foo"
*/
this.getFoldStringAt = function(row, column, trim, foldLine) {
var foldLine = foldLine || this.getFoldLine(row);
if (!foldLine)
return null;
var lastFold = {
end: { column: 0 }
};
// TODO: Refactor to use getNextFoldTo function.
for (var i = 0; i < foldLine.folds.length; i++) {
var fold = foldLine.folds[i];
var cmp = fold.range.compareEnd(row, column);
if (cmp == -1) {
var str = this
.getLine(fold.start.row)
.substring(lastFold.end.column, fold.start.column);
break;
}
else if (cmp == 0) {
return null;
}
lastFold = fold;
}
if (!str)
str = this.getLine(fold.start.row).substring(lastFold.end.column);
if (trim == -1)
return str.substring(0, column - lastFold.end.column);
else if (trim == 1)
return str.substring(column - lastFold.end.column)
else
return str;
}
this.getFoldLine = function(docRow, startFoldLine) {
var foldData = this.$foldData;
var i = 0;
if (startFoldLine)
i = foldData.indexOf(startFoldLine);
if (i == -1)
i = 0;
for (i; i < foldData.length; i++) {
var foldLine = foldData[i];
if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) {
return foldLine;
} else if (foldLine.end.row > docRow) {
return null;
}
}
return null;
}
// returns the fold which starts after or contains docRow
this.getNextFold = function(docRow, startFoldLine) {
var foldData = this.$foldData, ans;
var i = 0;
if (startFoldLine)
i = foldData.indexOf(startFoldLine);
if (i == -1)
i = 0;
for (i; i < foldData.length; i++) {
var foldLine = foldData[i];
if (foldLine.end.row >= docRow) {
return foldLine;
}
}
return null;
}
this.getFoldedRowCount = function(first, last) {
var foldData = this.$foldData, rowCount = last-first+1;
for (var i = 0; i < foldData.length; i++) {
var foldLine = foldData[i],
end = foldLine.end.row,
start = foldLine.start.row;
if (end >= last) {
if(start < last) {
if(start >= first)
rowCount -= last-start;
else
rowCount = 0;//in one fold
}
break;
} else if(end >= first){
if (start >= first) //fold inside range
rowCount -= end-start;
else
rowCount -= end-first+1;
}
}
return rowCount;
}
this.$addFoldLine = function(foldLine) {
this.$foldData.push(foldLine);
this.$foldData.sort(function(a, b) {
return a.start.row - b.start.row;
});
return foldLine;
}
/**
* Adds a new fold.
*
* @returns
* The new created Fold object or an existing fold object in case the
* passed in range fits an existing fold exactly.
*/
this.addFold = function(placeholder, range) {
var foldData = this.$foldData;
var added = false;
if (placeholder instanceof Fold)
var fold = placeholder;
else
fold = new Fold(range, placeholder);
var startRow = fold.start.row;
var startColumn = fold.start.column;
var endRow = fold.end.row;
var endColumn = fold.end.column;
// --- Some checking ---
if (fold.placeholder.length < 2)
throw "Placeholder has to be at least 2 characters";
if (startRow == endRow && endColumn - startColumn < 2)
throw "The range has to be at least 2 characters width";
var existingFold = this.getFoldAt(startRow, startColumn, 1);
if (
existingFold
&& existingFold.range.isEnd(endRow, endColumn)
&& existingFold.range.isStart(startRow, startColumn)
) {
return fold;
}
existingFold = this.getFoldAt(startRow, startColumn, 1);
if (existingFold && !existingFold.range.isStart(startRow, startColumn))
throw "A fold can't start inside of an already existing fold";
existingFold = this.getFoldAt(endRow, endColumn, -1);
if (existingFold && !existingFold.range.isEnd(endRow, endColumn))
throw "A fold can't end inside of an already existing fold";
if (endRow >= this.doc.getLength())
throw "End of fold is outside of the document.";
if (endColumn > this.getLine(endRow).length || startColumn > this.getLine(startRow).length)
throw "End of fold is outside of the document.";
// Check if there are folds in the range we create the new fold for.
var folds = this.getFoldsInRange(fold.range);
if (folds.length > 0) {
// Remove the folds from fold data.
this.removeFolds(folds);
// Add the removed folds as subfolds on the new fold.
fold.subFolds = folds;
}
for (var i = 0; i < foldData.length; i++) {
var foldLine = foldData[i];
if (endRow == foldLine.start.row) {
foldLine.addFold(fold);
added = true;
break;
}
else if (startRow == foldLine.end.row) {
foldLine.addFold(fold);
added = true;
if (!fold.sameRow) {
// Check if we might have to merge two FoldLines.
foldLineNext = foldData[i + 1];
if (foldLineNext && foldLineNext.start.row == endRow) {
// We need to merge!
foldLine.merge(foldLineNext);
break;
}
}
break;
}
else if (endRow <= foldLine.start.row) {
break;
}
}
if (!added)
foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold));
if (this.$useWrapMode)
this.$updateWrapData(foldLine.start.row, foldLine.start.row);
// Notify that fold data has changed.
this.$modified = true;
this._dispatchEvent("changeFold", { data: fold });
return fold;
};
this.addFolds = function(folds) {
folds.forEach(function(fold) {
this.addFold(fold);
}, this);
};
this.removeFold = function(fold) {
var foldLine = fold.foldLine;
var startRow = foldLine.start.row;
var endRow = foldLine.end.row;
var foldLines = this.$foldData,
folds = foldLine.folds;
// Simple case where there is only one fold in the FoldLine such that
// the entire fold line can get removed directly.
if (folds.length == 1) {
foldLines.splice(foldLines.indexOf(foldLine), 1);
} else
// If the fold is the last fold of the foldLine, just remove it.
if (foldLine.range.isEnd(fold.end.row, fold.end.column)) {
folds.pop();
foldLine.end.row = folds[folds.length - 1].end.row;
foldLine.end.column = folds[folds.length - 1].end.column;
} else
// If the fold is the first fold of the foldLine, just remove it.
if (foldLine.range.isStart(fold.start.row, fold.start.column)) {
folds.shift();
foldLine.start.row = folds[0].start.row;
foldLine.start.column = folds[0].start.column;
} else
// We know there are more then 2 folds and the fold is not at the edge.
// This means, the fold is somewhere in between.
//
// If the fold is in one row, we just can remove it.
if (fold.sameRow) {
folds.splice(folds.indexOf(fold), 1);
} else
// The fold goes over more then one row. This means remvoing this fold
// will cause the fold line to get splitted up.
{
var newFoldLine = foldLine.split(fold.start.row, fold.start.column);
newFoldLine.folds.shift();
foldLine.start.row = folds[0].start.row;
foldLine.start.column = folds[0].start.column;
this.$addFoldLine(newFoldLine);
}
if (this.$useWrapMode) {
this.$updateWrapData(startRow, endRow);
}
// Notify that fold data has changed.
this.$modified = true;
this._dispatchEvent("changeFold", { data: fold });
}
this.removeFolds = function(folds) {
// We need to clone the folds array passed in as it might be the folds
// array of a fold line and as we call this.removeFold(fold), folds
// are removed from folds and changes the current index.
var cloneFolds = [];
for (var i = 0; i < folds.length; i++) {
cloneFolds.push(folds[i]);
}
cloneFolds.forEach(function(fold) {
this.removeFold(fold);
}, this);
this.$modified = true;
}
this.expandFold = function(fold) {
this.removeFold(fold);
fold.subFolds.forEach(function(fold) {
this.addFold(fold);
}, this);
fold.subFolds = [];
}
this.expandFolds = function(folds) {
folds.forEach(function(fold) {
this.expandFold(fold);
}, this);
}
/**
* Checks if a given documentRow is folded. This is true if there are some
* folded parts such that some parts of the line is still visible.
**/
this.isRowFolded = function(docRow, startFoldRow) {
return !!this.getFoldLine(docRow, startFoldRow);
};
this.getRowFoldEnd = function(docRow, startFoldRow) {
var foldLine = this.getFoldLine(docRow, startFoldRow);
return (foldLine
? foldLine.end.row
: docRow)
};
this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) {
if (startRow == null) {
startRow = foldLine.start.row;
startColumn = 0;
}
if (endRow == null) {
endRow = foldLine.end.row;
endColumn = this.getLine(endRow).length;
}
// Build the textline using the FoldLine walker.
var line = "";
var doc = this.doc;
var textLine = "";
foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
if (row < startRow) {
return;
} else if (row == startRow) {
if (column < startColumn) {
return;
}
lastColumn = Math.max(startColumn, lastColumn);
}
if (placeholder) {
textLine += placeholder;
} else {
textLine += doc.getLine(row).substring(lastColumn, column);
}
}.bind(this), endRow, endColumn);
return textLine;
};
this.getDisplayLine = function(row, endColumn, startRow, startColumn) {
var foldLine = this.getFoldLine(row);
if (!foldLine) {
var line;
line = this.doc.getLine(row);
return line.substring(startColumn || 0, endColumn || line.length);
} else {
return this.getFoldDisplayLine(
foldLine, row, endColumn, startRow, startColumn);
}
};
this.$cloneFoldData = function() {
var foldData = this.$foldData;
var fd = [];
fd = this.$foldData.map(function(foldLine) {
var folds = foldLine.folds.map(function(fold) {
return fold.clone();
});
return new FoldLine(fd, folds);
});
return fd;
};
}
exports.Folding = Folding;
});/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/edit_session/fold_line', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("ace/range").Range;
/**
* If the an array is passed in, the folds are expected to be sorted already.
*/
function FoldLine(foldData, folds) {
this.foldData = foldData;
if (Array.isArray(folds)) {
this.folds = folds;
} else {
folds = this.folds = [ folds ];
}
var last = folds[folds.length - 1]
this.range = new Range(folds[0].start.row, folds[0].start.column,
last.end.row, last.end.column);
this.start = this.range.start;
this.end = this.range.end;
this.folds.forEach(function(fold) {
fold.setFoldLine(this);
}, this);
}
(function() {
/**
* Note: This doesn't update wrapData!
*/
this.shiftRow = function(shift) {
this.start.row += shift;
this.end.row += shift;
this.folds.forEach(function(fold) {
fold.start.row += shift;
fold.end.row += shift;
});
}
this.addFold = function(fold) {
if (fold.sameRow) {
if (fold.start.row < this.startRow || fold.endRow > this.endRow) {
throw "Can't add a fold to this FoldLine as it has no connection";
}
this.folds.push(fold);
this.folds.sort(function(a, b) {
return -a.range.compareEnd(b.start.row, b.start.column);
});
if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) {
this.end.row = fold.end.row;
this.end.column = fold.end.column;
} else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) {
this.start.row = fold.start.row;
this.start.column = fold.start.column;
}
} else if (fold.start.row == this.end.row) {
this.folds.push(fold);
this.end.row = fold.end.row;
this.end.column = fold.end.column;
} else if (fold.end.row == this.start.row) {
this.folds.unshift(fold);
this.start.row = fold.start.row;
this.start.column = fold.start.column;
} else {
throw "Trying to add fold to FoldRow that doesn't have a matching row";
}
fold.foldLine = this;
}
this.containsRow = function(row) {
return row >= this.start.row && row <= this.end.row;
}
this.walk = function(callback, endRow, endColumn) {
var lastEnd = 0,
folds = this.folds,
fold,
comp, stop, isNewRow = true;
if (endRow == null) {
endRow = this.end.row;
endColumn = this.end.column;
}
for (var i = 0; i < folds.length; i++) {
fold = folds[i];
comp = fold.range.compareStart(endRow, endColumn);
// This fold is after the endRow/Column.
if (comp == -1) {
callback(null, endRow, endColumn, lastEnd, isNewRow);
return;
}
stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow);
stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd);
// If the user requested to stop the walk or endRow/endColumn is
// inside of this fold (comp == 0), then end here.
if (stop || comp == 0) {
return;
}
// Note the new lastEnd might not be on the same line. However,
// it's the callback's job to recognize this.
isNewRow = !fold.sameRow;
lastEnd = fold.end.column;
}
callback(null, endRow, endColumn, lastEnd, isNewRow);
}
this.getNextFoldTo = function(row, column) {
var fold, cmp;
for (var i = 0; i < this.folds.length; i++) {
fold = this.folds[i];
cmp = fold.range.compareEnd(row, column);
if (cmp == -1) {
return {
fold: fold,
kind: "after"
};
} else if (cmp == 0) {
return {
fold: fold,
kind: "inside"
}
}
}
return null;
}
this.addRemoveChars = function(row, column, len) {
var ret = this.getNextFoldTo(row, column),
fold, folds;
if (ret) {
fold = ret.fold;
if (ret.kind == "inside"
&& fold.start.column != column
&& fold.start.row != row)
{
throw "Moving characters inside of a fold should never be reached";
} else if (fold.start.row == row) {
folds = this.folds;
var i = folds.indexOf(fold);
if (i == 0) {
this.start.column += len;
}
for (i; i < folds.length; i++) {
fold = folds[i];
fold.start.column += len;
if (!fold.sameRow) {
return;
}
fold.end.column += len;
}
this.end.column += len;
}
}
}
this.split = function(row, column) {
var fold = this.getNextFoldTo(row, column).fold,
folds = this.folds;
var foldData = this.foldData;
if (!fold) {
return null;
}
var i = folds.indexOf(fold);
var foldBefore = folds[i - 1];
this.end.row = foldBefore.end.row;
this.end.column = foldBefore.end.column;
// Remove the folds after row/column and create a new FoldLine
// containing these removed folds.
folds = folds.splice(i, folds.length - i);
var newFoldLine = new FoldLine(foldData, folds);
foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine);
return newFoldLine;
}
this.merge = function(foldLineNext) {
var folds = foldLineNext.folds;
for (var i = 0; i < folds.length; i++) {
this.addFold(folds[i]);
}
// Remove the foldLineNext - no longer needed, as
// it's merged now with foldLineNext.
var foldData = this.foldData;
foldData.splice(foldData.indexOf(foldLineNext), 1);
}
this.toString = function() {
var ret = [this.range.toString() + ": [" ];
this.folds.forEach(function(fold) {
ret.push(" " + fold.toString());
});
ret.push("]")
return ret.join("\n");
}
this.idxToPosition = function(idx) {
var lastFoldEndColumn = 0;
var fold;
for (var i = 0; i < this.folds.length; i++) {
var fold = this.folds[i];
idx -= fold.start.column - lastFoldEndColumn;
if (idx < 0) {
return {
row: fold.start.row,
column: fold.start.column + idx
};
}
idx -= fold.placeholder.length;
if (idx < 0) {
return fold.start;
}
lastFoldEndColumn = fold.end.column;
}
return {
row: this.end.row,
column: this.end.column + idx
};
}
}).call(FoldLine.prototype);
exports.FoldLine = FoldLine;
});/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/edit_session/fold', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* Simple fold-data struct.
**/
var Fold = exports.Fold = function(range, placeholder) {
this.foldLine = null;
this.placeholder = placeholder;
this.range = range;
this.start = range.start;
this.end = range.end;
this.sameRow = range.start.row == range.end.row;
this.subFolds = [];
};
(function() {
this.toString = function() {
return '"' + this.placeholder + '" ' + this.range.toString();
};
this.setFoldLine = function(foldLine) {
this.foldLine = foldLine;
this.subFolds.forEach(function(fold) {
fold.setFoldLine(foldLine);
});
};
this.clone = function() {
var range = this.range.clone();
var fold = new Fold(range, this.placeholder);
this.subFolds.forEach(function(subFold) {
fold.subFolds.push(subFold.clone());
});
return fold;
};
}).call(Fold.prototype);
});/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/search', ['require', 'exports', 'module' , 'pilot/lang', 'pilot/oop', 'ace/range'], function(require, exports, module) {
var lang = require("pilot/lang");
var oop = require("pilot/oop");
var Range = require("ace/range").Range;
var Search = function() {
this.$options = {
needle: "",
backwards: false,
wrap: false,
caseSensitive: false,
wholeWord: false,
scope: Search.ALL,
regExp: false
};
};
Search.ALL = 1;
Search.SELECTION = 2;
(function() {
this.set = function(options) {
oop.mixin(this.$options, options);
return this;
};
this.getOptions = function() {
return lang.copyObject(this.$options);
};
this.find = function(session) {
if (!this.$options.needle)
return null;
if (this.$options.backwards) {
var iterator = this.$backwardMatchIterator(session);
} else {
iterator = this.$forwardMatchIterator(session);
}
var firstRange = null;
iterator.forEach(function(range) {
firstRange = range;
return true;
});
return firstRange;
};
this.findAll = function(session) {
if (!this.$options.needle)
return [];
if (this.$options.backwards) {
var iterator = this.$backwardMatchIterator(session);
} else {
iterator = this.$forwardMatchIterator(session);
}
var ranges = [];
iterator.forEach(function(range) {
ranges.push(range);
});
return ranges;
};
this.replace = function(input, replacement) {
var re = this.$assembleRegExp();
var match = re.exec(input);
if (match && match[0].length == input.length) {
if (this.$options.regExp) {
return input.replace(re, replacement);
} else {
return replacement;
}
} else {
return null;
}
};
this.$forwardMatchIterator = function(session) {
var re = this.$assembleRegExp();
var self = this;
return {
forEach: function(callback) {
self.$forwardLineIterator(session).forEach(function(line, startIndex, row) {
if (startIndex) {
line = line.substring(startIndex);
}
var matches = [];
line.replace(re, function(str) {
var offset = arguments[arguments.length-2];
matches.push({
str: str,
offset: startIndex + offset
});
return str;
});
for (var i=0; i<matches.length; i++) {
var match = matches[i];
var range = self.$rangeFromMatch(row, match.offset, match.str.length);
if (callback(range))
return true;
}
});
}
};
};
this.$backwardMatchIterator = function(session) {
var re = this.$assembleRegExp();
var self = this;
return {
forEach: function(callback) {
self.$backwardLineIterator(session).forEach(function(line, startIndex, row) {
if (startIndex) {
line = line.substring(startIndex);
}
var matches = [];
line.replace(re, function(str, offset) {
matches.push({
str: str,
offset: startIndex + offset
});
return str;
});
for (var i=matches.length-1; i>= 0; i--) {
var match = matches[i];
var range = self.$rangeFromMatch(row, match.offset, match.str.length);
if (callback(range))
return true;
}
});
}
};
};
this.$rangeFromMatch = function(row, column, length) {
return new Range(row, column, row, column+length);
};
this.$assembleRegExp = function() {
if (this.$options.regExp) {
var needle = this.$options.needle;
} else {
needle = lang.escapeRegExp(this.$options.needle);
}
if (this.$options.wholeWord) {
needle = "\\b" + needle + "\\b";
}
var modifier = "g";
if (!this.$options.caseSensitive) {
modifier += "i";
}
var re = new RegExp(needle, modifier);
return re;
};
this.$forwardLineIterator = function(session) {
var searchSelection = this.$options.scope == Search.SELECTION;
var range = session.getSelection().getRange();
var start = session.getSelection().getCursor();
var firstRow = searchSelection ? range.start.row : 0;
var firstColumn = searchSelection ? range.start.column : 0;
var lastRow = searchSelection ? range.end.row : session.getLength() - 1;
var wrap = this.$options.wrap;
var inWrap = false;
function getLine(row) {
var line = session.getLine(row);
if (searchSelection && row == range.end.row) {
line = line.substring(0, range.end.column);
}
if (inWrap && row == start.row) {
line = line.substring(0, start.column);
}
return line;
}
return {
forEach: function(callback) {
var row = start.row;
var line = getLine(row);
var startIndex = start.column;
var stop = false;
inWrap = false;
while (!callback(line, startIndex, row)) {
if (stop) {
return;
}
row++;
startIndex = 0;
if (row > lastRow) {
if (wrap) {
row = firstRow;
startIndex = firstColumn;
inWrap = true;
} else {
return;
}
}
if (row == start.row)
stop = true;
line = getLine(row);
}
}
};
};
this.$backwardLineIterator = function(session) {
var searchSelection = this.$options.scope == Search.SELECTION;
var range = session.getSelection().getRange();
var start = searchSelection ? range.end : range.start;
var firstRow = searchSelection ? range.start.row : 0;
var firstColumn = searchSelection ? range.start.column : 0;
var lastRow = searchSelection ? range.end.row : session.getLength() - 1;
var wrap = this.$options.wrap;
return {
forEach : function(callback) {
var row = start.row;
var line = session.getLine(row).substring(0, start.column);
var startIndex = 0;
var stop = false;
var inWrap = false;
while (!callback(line, startIndex, row)) {
if (stop)
return;
row--;
startIndex = 0;
if (row < firstRow) {
if (wrap) {
row = lastRow;
inWrap = true;
} else {
return;
}
}
if (row == start.row)
stop = true;
line = session.getLine(row);
if (searchSelection) {
if (row == firstRow)
startIndex = firstColumn;
else if (row == lastRow)
line = line.substring(0, range.end.column);
}
if (inWrap && row == start.row)
startIndex = start.column;
}
}
};
};
}).call(Search.prototype);
exports.Search = Search;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/undomanager', ['require', 'exports', 'module' ], function(require, exports, module) {
var UndoManager = function() {
this.reset();
};
(function() {
this.execute = function(options) {
var deltas = options.args[0];
this.$doc = options.args[1];
this.$undoStack.push(deltas);
this.$redoStack = [];
};
this.undo = function(dontSelect) {
var deltas = this.$undoStack.pop();
var undoSelectionRange = null;
if (deltas) {
undoSelectionRange =
this.$doc.undoChanges(deltas, dontSelect);
this.$redoStack.push(deltas);
}
return undoSelectionRange;
};
this.redo = function(dontSelect) {
var deltas = this.$redoStack.pop();
var redoSelectionRange = null;
if (deltas) {
redoSelectionRange =
this.$doc.redoChanges(deltas, dontSelect);
this.$undoStack.push(deltas);
}
return redoSelectionRange;
};
this.reset = function() {
this.$undoStack = [];
this.$redoStack = [];
};
this.hasUndo = function() {
return this.$undoStack.length > 0;
};
this.hasRedo = function() {
return this.$redoStack.length > 0;
};
}).call(UndoManager.prototype);
exports.UndoManager = UndoManager;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian@ajax.org>
* Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/virtual_renderer', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/dom', 'pilot/event', 'pilot/useragent', 'ace/layer/gutter', 'ace/layer/marker', 'ace/layer/text', 'ace/layer/cursor', 'ace/scrollbar', 'ace/renderloop', 'pilot/event_emitter', 'text/ace/css/editor.css'], function(require, exports, module) {
var oop = require("pilot/oop");
var dom = require("pilot/dom");
var event = require("pilot/event");
var useragent = require("pilot/useragent");
var GutterLayer = require("ace/layer/gutter").Gutter;
var MarkerLayer = require("ace/layer/marker").Marker;
var TextLayer = require("ace/layer/text").Text;
var CursorLayer = require("ace/layer/cursor").Cursor;
var ScrollBar = require("ace/scrollbar").ScrollBar;
var RenderLoop = require("ace/renderloop").RenderLoop;
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var editorCss = require("text/ace/css/editor.css");
// import CSS once
dom.importCssString(editorCss);
var VirtualRenderer = function(container, theme) {
this.container = container;
dom.addCssClass(this.container, "ace_editor");
this.setTheme(theme);
this.$gutter = dom.createElement("div");
this.$gutter.className = "ace_gutter";
this.container.appendChild(this.$gutter);
this.scroller = dom.createElement("div");
this.scroller.className = "ace_scroller";
this.container.appendChild(this.scroller);
this.content = dom.createElement("div");
this.content.className = "ace_content";
this.scroller.appendChild(this.content);
this.$gutterLayer = new GutterLayer(this.$gutter);
this.$markerBack = new MarkerLayer(this.content);
var textLayer = this.$textLayer = new TextLayer(this.content);
this.canvas = textLayer.element;
this.$markerFront = new MarkerLayer(this.content);
this.characterWidth = textLayer.getCharacterWidth();
this.lineHeight = textLayer.getLineHeight();
this.$cursorLayer = new CursorLayer(this.content);
this.$cursorPadding = 8;
// Indicates whether the horizontal scrollbar is visible
this.$horizScroll = true;
this.$horizScrollAlwaysVisible = true;
this.scrollBar = new ScrollBar(container);
this.scrollBar.addEventListener("scroll", this.onScroll.bind(this));
this.scrollTop = 0;
this.cursorPos = {
row : 0,
column : 0
};
var _self = this;
this.$textLayer.addEventListener("changeCharaterSize", function() {
_self.characterWidth = textLayer.getCharacterWidth();
_self.lineHeight = textLayer.getLineHeight();
_self.$updatePrintMargin();
_self.onResize(true);
_self.$loop.schedule(_self.CHANGE_FULL);
});
event.addListener(this.$gutter, "click", this.$onGutterClick.bind(this));
event.addListener(this.$gutter, "dblclick", this.$onGutterClick.bind(this));
this.$size = {
width: 0,
height: 0,
scrollerHeight: 0,
scrollerWidth: 0
};
this.layerConfig = {
width : 1,
padding : 0,
firstRow : 0,
firstRowScreen: 0,
lastRow : 0,
lineHeight : 1,
characterWidth : 1,
minHeight : 1,
maxHeight : 1,
offset : 0,
height : 1
};
this.$loop = new RenderLoop(this.$renderChanges.bind(this));
this.$loop.schedule(this.CHANGE_FULL);
this.setPadding(4);
this.$updatePrintMargin();
};
(function() {
this.showGutter = true;
this.CHANGE_CURSOR = 1;
this.CHANGE_MARKER = 2;
this.CHANGE_GUTTER = 4;
this.CHANGE_SCROLL = 8;
this.CHANGE_LINES = 16;
this.CHANGE_TEXT = 32;
this.CHANGE_SIZE = 64;
this.CHANGE_MARKER_BACK = 128;
this.CHANGE_MARKER_FRONT = 256;
this.CHANGE_FULL = 512;
oop.implement(this, EventEmitter);
this.setSession = function(session) {
this.session = session;
this.$cursorLayer.setSession(session);
this.$markerBack.setSession(session);
this.$markerFront.setSession(session);
this.$gutterLayer.setSession(session);
this.$textLayer.setSession(session);
this.$loop.schedule(this.CHANGE_FULL);
};
/**
* Triggers partial update of the text layer
*/
this.updateLines = function(firstRow, lastRow) {
if (lastRow === undefined)
lastRow = Infinity;
if (!this.$changedLines) {
this.$changedLines = {
firstRow: firstRow,
lastRow: lastRow
};
}
else {
if (this.$changedLines.firstRow > firstRow)
this.$changedLines.firstRow = firstRow;
if (this.$changedLines.lastRow < lastRow)
this.$changedLines.lastRow = lastRow;
}
this.$loop.schedule(this.CHANGE_LINES);
};
/**
* Triggers full update of the text layer
*/
this.updateText = function() {
this.$loop.schedule(this.CHANGE_TEXT);
};
/**
* Triggers a full update of all layers
*/
this.updateFull = function() {
this.$loop.schedule(this.CHANGE_FULL);
};
this.updateFontSize = function() {
this.$textLayer.checkForSizeChanges();
};
/**
* Triggers resize of the editor
*/
this.onResize = function(force) {
var changes = this.CHANGE_SIZE;
var size = this.$size;
var height = dom.getInnerHeight(this.container);
if (force || size.height != height) {
size.height = height;
this.scroller.style.height = height + "px";
size.scrollerHeight = this.scroller.clientHeight;
this.scrollBar.setHeight(size.scrollerHeight);
if (this.session) {
this.scrollToY(this.getScrollTop());
changes = changes | this.CHANGE_FULL;
}
}
var width = dom.getInnerWidth(this.container);
if (force || size.width != width) {
size.width = width;
var gutterWidth = this.showGutter ? this.$gutter.offsetWidth : 0;
this.scroller.style.left = gutterWidth + "px";
size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBar.getWidth())
this.scroller.style.width = size.scrollerWidth + "px";
if (this.session.getUseWrapMode() && this.adjustWrapLimit() || force)
changes = changes | this.CHANGE_FULL;
}
this.$loop.schedule(changes);
};
this.adjustWrapLimit = function(){
var availableWidth = this.$size.scrollerWidth - this.$padding * 2;
var limit = Math.floor(availableWidth / this.characterWidth) - 1;
return this.session.adjustWrapLimit(limit);
};
this.$onGutterClick = function(e) {
var pageX = event.getDocumentX(e);
var pageY = event.getDocumentY(e);
this._dispatchEvent("gutter" + e.type, {
row: this.screenToTextCoordinates(pageX, pageY).row,
htmlEvent: e
});
};
this.setShowInvisibles = function(showInvisibles) {
if (this.$textLayer.setShowInvisibles(showInvisibles))
this.$loop.schedule(this.CHANGE_TEXT);
};
this.getShowInvisibles = function() {
return this.$textLayer.showInvisibles;
};
this.$showPrintMargin = true;
this.setShowPrintMargin = function(showPrintMargin) {
this.$showPrintMargin = showPrintMargin;
this.$updatePrintMargin();
};
this.getShowPrintMargin = function() {
return this.$showPrintMargin;
};
this.$printMarginColumn = 80;
this.setPrintMarginColumn = function(showPrintMargin) {
this.$printMarginColumn = showPrintMargin;
this.$updatePrintMargin();
};
this.getPrintMarginColumn = function() {
return this.$printMarginColumn;
};
this.getShowGutter = function(){
return this.showGutter;
};
this.setShowGutter = function(show){
if(this.showGutter === show)
return;
this.$gutter.style.display = show ? "block" : "none";
this.showGutter = show;
this.onResize(true);
};
this.$updatePrintMargin = function() {
var containerEl;
if (!this.$showPrintMargin && !this.$printMarginEl)
return;
if (!this.$printMarginEl) {
containerEl = dom.createElement("div");
containerEl.className = "ace_print_margin_layer";
this.$printMarginEl = dom.createElement("div");
this.$printMarginEl.className = "ace_print_margin";
containerEl.appendChild(this.$printMarginEl);
this.content.insertBefore(containerEl, this.$textLayer.element);
}
var style = this.$printMarginEl.style;
style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding * 2) + "px";
style.visibility = this.$showPrintMargin ? "visible" : "hidden";
};
this.getContainerElement = function() {
return this.container;
};
this.getMouseEventTarget = function() {
return this.content;
};
this.getTextAreaContainer = function() {
return this.container;
};
this.moveTextAreaToCursor = function(textarea) {
// in IE the native cursor always shines through
if (useragent.isIE)
return;
var pos = this.$cursorLayer.getPixelPosition();
if (!pos)
return;
var bounds = this.content.getBoundingClientRect();
var offset = this.layerConfig.offset;
textarea.style.left = (bounds.left + pos.left + this.$padding) + "px";
textarea.style.top = (bounds.top + pos.top - this.scrollTop + offset) + "px";
};
this.getFirstVisibleRow = function() {
return this.layerConfig.firstRow;
};
this.getFirstFullyVisibleRow = function() {
return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1);
};
this.getLastFullyVisibleRow = function() {
var flint = Math.floor((this.layerConfig.height + this.layerConfig.offset) / this.layerConfig.lineHeight);
return this.layerConfig.firstRow - 1 + flint;
};
this.getLastVisibleRow = function() {
return this.layerConfig.lastRow;
};
this.$padding = null;
this.setPadding = function(padding) {
this.$padding = padding;
this.$textLayer.setPadding(padding);
this.$cursorLayer.setPadding(padding);
this.$markerFront.setPadding(padding);
this.$markerBack.setPadding(padding);
this.$loop.schedule(this.CHANGE_FULL);
this.$updatePrintMargin();
};
this.getHScrollBarAlwaysVisible = function() {
return this.$horizScrollAlwaysVisible;
};
this.setHScrollBarAlwaysVisible = function(alwaysVisible) {
if (this.$horizScrollAlwaysVisible != alwaysVisible) {
this.$horizScrollAlwaysVisible = alwaysVisible;
if (!this.$horizScrollAlwaysVisible || !this.$horizScroll)
this.$loop.schedule(this.CHANGE_SCROLL);
}
};
this.onScroll = function(e) {
this.scrollToY(e.data);
};
this.$updateScrollBar = function() {
this.scrollBar.setInnerHeight(this.layerConfig.maxHeight);
this.scrollBar.setScrollTop(this.scrollTop);
};
this.$renderChanges = function(changes) {
if (!changes || !this.session)
return;
// text, scrolling and resize changes can cause the view port size to change
if (changes & this.CHANGE_FULL ||
changes & this.CHANGE_SIZE ||
changes & this.CHANGE_TEXT ||
changes & this.CHANGE_LINES ||
changes & this.CHANGE_SCROLL
)
this.$computeLayerConfig();
// full
if (changes & this.CHANGE_FULL) {
this.$textLayer.update(this.layerConfig);
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
this.$markerBack.update(this.layerConfig);
this.$markerFront.update(this.layerConfig);
this.$cursorLayer.update(this.layerConfig);
this.$updateScrollBar();
return;
}
// scrolling
if (changes & this.CHANGE_SCROLL) {
if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES)
this.$textLayer.update(this.layerConfig);
else
this.$textLayer.scrollLines(this.layerConfig);
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
this.$markerBack.update(this.layerConfig);
this.$markerFront.update(this.layerConfig);
this.$cursorLayer.update(this.layerConfig);
this.$updateScrollBar();
return;
}
if (changes & this.CHANGE_TEXT) {
this.$textLayer.update(this.layerConfig);
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
}
else if (changes & this.CHANGE_LINES) {
this.$updateLines();
this.$updateScrollBar();
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
} else if (changes & this.CHANGE_GUTTER) {
if (this.showGutter)
this.$gutterLayer.update(this.layerConfig);
}
if (changes & this.CHANGE_CURSOR)
this.$cursorLayer.update(this.layerConfig);
if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) {
this.$markerFront.update(this.layerConfig);
}
if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) {
this.$markerBack.update(this.layerConfig);
}
if (changes & this.CHANGE_SIZE)
this.$updateScrollBar();
};
this.$computeLayerConfig = function() {
var session = this.session;
var offset = this.scrollTop % this.lineHeight;
var minHeight = this.$size.scrollerHeight + this.lineHeight;
var longestLine = this.$getLongestLine();
var widthChanged = this.layerConfig.width != longestLine;
var horizScroll = this.$horizScrollAlwaysVisible || this.$size.scrollerWidth - longestLine < 0;
var horizScrollChanged = this.$horizScroll !== horizScroll;
this.$horizScroll = horizScroll;
if (horizScrollChanged)
this.scroller.style.overflowX = horizScroll ? "scroll" : "hidden";
var maxHeight = this.session.getScreenLength() * this.lineHeight;
this.scrollTop = Math.max(0, Math.min(this.scrollTop, maxHeight - this.$size.scrollerHeight));
var lineCount = Math.ceil(minHeight / this.lineHeight) - 1;
var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight));
var lastRow = firstRow + lineCount;
// Map lines on the screen to lines in the document.
var firstRowScreen, firstRowHeight;
var lineHeight = { lineHeight: this.lineHeight };
firstRow = session.screenToDocumentRow(firstRow, 0);
// Check if firstRow is inside of a foldLine. If true, then use the first
// row of the foldLine.
var foldLine = session.getFoldLine(firstRow);
if (foldLine) {
firstRow = foldLine.start.row;
}
firstRowScreen = session.documentToScreenRow(firstRow, 0);
firstRowHeight = session.getRowHeight(lineHeight, firstRow);
lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1);
minHeight = this.$size.scrollerHeight + session.getRowHeight(lineHeight, lastRow)+
firstRowHeight;
offset = this.scrollTop - firstRowScreen * this.lineHeight;
this.layerConfig = {
width : longestLine,
padding : this.$padding,
firstRow : firstRow,
firstRowScreen: firstRowScreen,
lastRow : lastRow,
lineHeight : this.lineHeight,
characterWidth : this.characterWidth,
minHeight : minHeight,
maxHeight : maxHeight,
offset : offset,
height : this.$size.scrollerHeight
};
// For debugging.
// console.log(JSON.stringify(this.layerConfig));
this.$gutterLayer.element.style.marginTop = (-offset) + "px";
this.content.style.marginTop = (-offset) + "px";
this.content.style.width = longestLine + "px";
this.content.style.height = minHeight + "px";
// scroller.scrollWidth was smaller than scrollLeft we needed
if (this.$desiredScrollLeft) {
this.scrollToX(this.$desiredScrollLeft);
this.$desiredScrollLeft = 0;
}
// Horizontal scrollbar visibility may have changed, which changes
// the client height of the scroller
if (horizScrollChanged)
this.onResize(true);
};
this.$updateLines = function() {
var firstRow = this.$changedLines.firstRow;
var lastRow = this.$changedLines.lastRow;
this.$changedLines = null;
var layerConfig = this.layerConfig;
// if the update changes the width of the document do a full redraw
if (layerConfig.width != this.$getLongestLine())
return this.$textLayer.update(layerConfig);
if (firstRow > layerConfig.lastRow + 1) { return; }
if (lastRow < layerConfig.firstRow) { return; }
// if the last row is unknown -> redraw everything
if (lastRow === Infinity) {
if (this.showGutter)
this.$gutterLayer.update(layerConfig);
this.$textLayer.update(layerConfig);
return;
}
// else update only the changed rows
this.$textLayer.updateLines(layerConfig, firstRow, lastRow);
};
this.$getLongestLine = function() {
var charCount = this.session.getScreenWidth() + 1;
if (this.$textLayer.showInvisibles)
charCount += 1;
return Math.max(this.$size.scrollerWidth, Math.round(charCount * this.characterWidth));
};
this.updateFrontMarkers = function() {
this.$markerFront.setMarkers(this.session.getMarkers(true));
this.$loop.schedule(this.CHANGE_MARKER_FRONT);
};
this.updateBackMarkers = function() {
this.$markerBack.setMarkers(this.session.getMarkers());
this.$loop.schedule(this.CHANGE_MARKER_BACK);
};
this.addGutterDecoration = function(row, className){
this.$gutterLayer.addGutterDecoration(row, className);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.removeGutterDecoration = function(row, className){
this.$gutterLayer.removeGutterDecoration(row, className);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.setBreakpoints = function(rows) {
this.$gutterLayer.setBreakpoints(rows);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.setAnnotations = function(annotations) {
this.$gutterLayer.setAnnotations(annotations);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.updateCursor = function() {
this.$loop.schedule(this.CHANGE_CURSOR);
};
this.hideCursor = function() {
this.$cursorLayer.hideCursor();
};
this.showCursor = function() {
this.$cursorLayer.showCursor();
};
this.scrollCursorIntoView = function() {
// the editor is not visible
if (this.$size.scrollerHeight === 0)
return;
var pos = this.$cursorLayer.getPixelPosition();
var left = pos.left + this.$padding;
var top = pos.top;
if (this.scrollTop > top) {
this.scrollToY(top);
}
if (this.scrollTop + this.$size.scrollerHeight < top + this.lineHeight) {
this.scrollToY(top + this.lineHeight - this.$size.scrollerHeight);
}
var scrollLeft = this.scroller.scrollLeft;
if (scrollLeft > left) {
this.scrollToX(left);
}
if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) {
if (left > this.layerConfig.width)
this.$desiredScrollLeft = left + 2 * this.characterWidth;
else
this.scrollToX(Math.round(left + this.characterWidth - this.$size.scrollerWidth));
}
};
this.getScrollTop = function() {
return this.scrollTop;
};
this.getScrollLeft = function() {
return this.scroller.scrollLeft;
};
this.getScrollTopRow = function() {
return this.scrollTop / this.lineHeight;
};
this.getScrollBottomRow = function() {
return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1);
};
this.scrollToRow = function(row) {
this.scrollToY(row * this.lineHeight);
};
this.scrollToLine = function(line, center) {
var lineHeight = { lineHeight: this.lineHeight };
var offset = 0;
for (var l = 1; l < line; l++) {
offset += this.session.getRowHeight(lineHeight, l-1);
}
if (center) {
offset -= this.$size.scrollerHeight / 2;
}
this.scrollToY(offset);
};
this.scrollToY = function(scrollTop) {
// after calling scrollBar.setScrollTop
// scrollbar sends us event with same scrollTop. ignore it
scrollTop = Math.max(0, scrollTop);
if (this.scrollTop !== scrollTop) {
this.$loop.schedule(this.CHANGE_SCROLL);
this.scrollTop = scrollTop;
}
};
this.scrollToX = function(scrollLeft) {
if (scrollLeft <= this.$padding)
scrollLeft = 0;
this.scroller.scrollLeft = scrollLeft;
};
this.scrollBy = function(deltaX, deltaY) {
deltaY && this.scrollToY(this.scrollTop + deltaY);
deltaX && this.scrollToX(this.scroller.scrollLeft + deltaX);
};
this.screenToTextCoordinates = function(pageX, pageY) {
var canvasPos = this.scroller.getBoundingClientRect();
var col = Math.round((pageX + this.scroller.scrollLeft - canvasPos.left - this.$padding - dom.getPageScrollLeft())
/ this.characterWidth);
var row = Math.floor((pageY + this.scrollTop - canvasPos.top - dom.getPageScrollTop())
/ this.lineHeight);
return this.session.screenToDocumentPosition(row, Math.max(col, 0));
};
this.textToScreenCoordinates = function(row, column) {
var canvasPos = this.scroller.getBoundingClientRect();
var pos = this.session.documentToScreenPosition(row, column);
var x = this.$padding + Math.round(pos.column * this.characterWidth);
var y = pos.row * this.lineHeight;
return {
pageX: canvasPos.left + x - this.getScrollLeft(),
pageY: canvasPos.top + y - this.getScrollTop()
};
};
this.visualizeFocus = function() {
dom.addCssClass(this.container, "ace_focus");
};
this.visualizeBlur = function() {
dom.removeCssClass(this.container, "ace_focus");
};
this.showComposition = function(position) {
if (!this.$composition) {
this.$composition = dom.createElement("div");
this.$composition.className = "ace_composition";
this.content.appendChild(this.$composition);
}
this.$composition.innerHTML = " ";
var pos = this.$cursorLayer.getPixelPosition();
var style = this.$composition.style;
style.top = pos.top + "px";
style.left = (pos.left + this.$padding) + "px";
style.height = this.lineHeight + "px";
this.hideCursor();
};
this.setCompositionText = function(text) {
dom.setInnerText(this.$composition, text);
};
this.hideComposition = function() {
this.showCursor();
if (!this.$composition)
return;
var style = this.$composition.style;
style.top = "-10000px";
style.left = "-10000px";
};
this.setTheme = function(theme) {
var _self = this;
this.$themeValue = theme;
if (!theme || typeof theme == "string") {
theme = theme || "ace/theme/textmate";
require([theme], function(theme) {
afterLoad(theme);
});
} else {
afterLoad(theme);
}
function afterLoad(theme) {
if (_self.$theme)
dom.removeCssClass(_self.container, _self.$theme);
_self.$theme = theme ? theme.cssClass : null;
if (_self.$theme)
dom.addCssClass(_self.container, _self.$theme);
// force re-measure of the gutter width
if (_self.$size) {
_self.$size.width = 0;
_self.onResize();
}
}
};
this.getTheme = function() {
return this.$themeValue;
};
// Methods allows to add / remove CSS classnames to the editor element.
// This feature can be used by plug-ins to provide a visual indication of
// a certain mode that editor is in.
this.setStyle = function setStyle(style) {
dom.addCssClass(this.container, style);
};
this.unsetStyle = function unsetStyle(style) {
dom.removeCssClass(this.container, style);
};
this.destroy = function() {
this.$textLayer.destroy();
this.$cursorLayer.destroy();
};
}).call(VirtualRenderer.prototype);
exports.VirtualRenderer = VirtualRenderer;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian DOT viereck AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/layer/gutter', ['require', 'exports', 'module' , 'pilot/dom'], function(require, exports, module) {
var dom = require("pilot/dom");
var Gutter = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_gutter-layer";
parentEl.appendChild(this.element);
this.$breakpoints = [];
this.$annotations = [];
this.$decorations = [];
};
(function() {
this.setSession = function(session) {
this.session = session;
};
this.addGutterDecoration = function(row, className){
if (!this.$decorations[row])
this.$decorations[row] = "";
this.$decorations[row] += " ace_" + className;
}
this.removeGutterDecoration = function(row, className){
this.$decorations[row] = this.$decorations[row].replace(" ace_" + className, "");
};
this.setBreakpoints = function(rows) {
this.$breakpoints = rows.concat();
};
this.setAnnotations = function(annotations) {
// iterate over sparse array
this.$annotations = [];
for (var row in annotations) if (annotations.hasOwnProperty(row)) {
var rowAnnotations = annotations[row];
if (!rowAnnotations)
continue;
var rowInfo = this.$annotations[row] = {
text: []
};
for (var i=0; i<rowAnnotations.length; i++) {
var annotation = rowAnnotations[i];
rowInfo.text.push(annotation.text.replace(/"/g, """).replace(/'/g, "’").replace(/</, "<"));
var type = annotation.type;
if (type == "error")
rowInfo.className = "ace_error";
else if (type == "warning" && rowInfo.className != "ace_error")
rowInfo.className = "ace_warning";
else if (type == "info" && (!rowInfo.className))
rowInfo.className = "ace_info";
}
}
};
this.update = function(config) {
this.$config = config;
var emptyAnno = {className: "", text: []};
var html = [];
var i = config.firstRow;
var lastRow = config.lastRow;
var fold = this.session.getNextFold(i);
var foldStart = fold ? fold.start.row : Infinity;
while (true) {
if(i > foldStart) {
i = fold.end.row + 1;
fold = this.session.getNextFold(i);
foldStart = fold ?fold.start.row :Infinity;
}
if(i > lastRow)
break;
var annotation = this.$annotations[i] || emptyAnno;
html.push("<div class='ace_gutter-cell",
this.$decorations[i] || "",
this.$breakpoints[i] ? " ace_breakpoint " : " ",
annotation.className,
"' title='", annotation.text.join("\n"),
"' style='height:", config.lineHeight, "px;'>", (i+1));
var wrappedRowLength = this.session.getRowLength(i) - 1;
while (wrappedRowLength--) {
html.push("</div><div class='ace_gutter-cell' style='height:", config.lineHeight, "px'>¦</div>");
}
html.push("</div>");
i++;
}
this.element = dom.setInnerHtml(this.element, html.join(""));
this.element.style.height = config.minHeight + "px";
};
}).call(Gutter.prototype);
exports.Gutter = Gutter;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/layer/marker', ['require', 'exports', 'module' , 'ace/range', 'pilot/dom'], function(require, exports, module) {
var Range = require("ace/range").Range;
var dom = require("pilot/dom");
var Marker = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_marker-layer";
parentEl.appendChild(this.element);
};
(function() {
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
};
this.setSession = function(session) {
this.session = session;
};
this.setMarkers = function(markers) {
this.markers = markers;
};
this.update = function(config) {
var config = config || this.config;
if (!config)
return;
this.config = config;
var html = [];
for ( var key in this.markers) {
var marker = this.markers[key];
var range = marker.range.clipRows(config.firstRow, config.lastRow);
if (range.isEmpty()) continue;
range = range.toScreenRange(this.session);
if (marker.renderer) {
var top = this.$getTop(range.start.row, config);
var left = Math.round(
this.$padding + range.start.column * config.characterWidth
);
marker.renderer(html, range, left, top, config);
}
else if (range.isMultiLine()) {
if (marker.type == "text") {
this.drawTextMarker(html, range, marker.clazz, config);
} else {
this.drawMultiLineMarker(
html, range, marker.clazz, config,
marker.type
);
}
}
else {
this.drawSingleLineMarker(
html, range, marker.clazz, config,
null, marker.type
);
}
}
this.element = dom.setInnerHtml(this.element, html.join(""));
};
this.$getTop = function(row, layerConfig) {
return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight;
};
/**
* Draws a marker, which spans a range of text in a single line
*/
this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig) {
// selection start
var row = range.start.row;
var lineRange = new Range(
row, range.start.column,
row, this.session.getScreenLastRowColumn(row)
);
this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 1, "text");
// selection end
row = range.end.row;
lineRange = new Range(row, 0, row, range.end.column);
this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 0, "text");
for (row = range.start.row + 1; row < range.end.row; row++) {
lineRange.start.row = row;
lineRange.end.row = row;
lineRange.end.column = this.session.getScreenLastRowColumn(row);
this.drawSingleLineMarker(stringBuilder, lineRange, clazz, layerConfig, 1, "text");
}
};
/**
* Draws a multi line marker, where lines span the full width
*/
this.drawMultiLineMarker = function(stringBuilder, range, clazz, layerConfig, type) {
// from selection start to the end of the line
var padding = type === "background" ? 0 : this.$padding;
var height = layerConfig.lineHeight;
var width = Math.round(layerConfig.width - (range.start.column * layerConfig.characterWidth));
var top = this.$getTop(range.start.row, layerConfig);
var left = Math.round(
padding + range.start.column * layerConfig.characterWidth
);
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", left, "px;'></div>"
);
// from start of the last line to the selection end
top = this.$getTop(range.end.row, layerConfig);
width = Math.round(range.end.column * layerConfig.characterWidth);
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", padding, "px;'></div>"
);
// all the complete lines
height = (range.end.row - range.start.row - 1) * layerConfig.lineHeight;
if (height < 0)
return;
top = this.$getTop(range.start.row + 1, layerConfig);
width = layerConfig.width;
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", padding, "px;'></div>"
);
};
/**
* Draws a marker which covers one single full line
*/
this.drawSingleLineMarker = function(stringBuilder, range, clazz, layerConfig, extraLength, type) {
var padding = type === "background" ? 0 : this.$padding;
var height = layerConfig.lineHeight;
if (type === "background")
var width = layerConfig.width;
else
width = Math.round((range.end.column + (extraLength || 0) - range.start.column) * layerConfig.characterWidth);
var top = this.$getTop(range.start.row, layerConfig);
var left = Math.round(
padding + range.start.column * layerConfig.characterWidth
);
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", left,"px;'></div>"
);
};
}).call(Marker.prototype);
exports.Marker = Marker;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian DOT viereck AT gmail DOT com>
* Mihai Sucan <mihai.sucan@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/layer/text', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/dom', 'pilot/lang', 'pilot/useragent', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var dom = require("pilot/dom");
var lang = require("pilot/lang");
var useragent = require("pilot/useragent");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Text = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_text-layer";
this.element.style.width = "auto";
parentEl.appendChild(this.element);
this.$characterSize = this.$measureSizes() || {width: 0, height: 0};
this.$pollSizeChanges();
};
(function() {
oop.implement(this, EventEmitter);
this.EOF_CHAR = "¶";
this.EOL_CHAR = "¬";
this.TAB_CHAR = "→";
this.SPACE_CHAR = "·";
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
this.element.style.padding = "0 " + padding + "px";
};
this.getLineHeight = function() {
return this.$characterSize.height || 1;
};
this.getCharacterWidth = function() {
return this.$characterSize.width || 1;
};
this.checkForSizeChanges = function() {
var size = this.$measureSizes();
if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
this.$characterSize = size;
this._dispatchEvent("changeCharaterSize", {data: size});
}
};
this.$pollSizeChanges = function() {
var self = this;
this.$pollSizeChangesTimer = setInterval(function() {
self.checkForSizeChanges();
}, 500);
};
this.$fontStyles = {
fontFamily : 1,
fontSize : 1,
fontWeight : 1,
fontStyle : 1,
lineHeight : 1
};
this.$measureSizes = function() {
var n = 1000;
if (!this.$measureNode) {
var measureNode = this.$measureNode = dom.createElement("div");
var style = measureNode.style;
style.width = style.height = "auto";
style.left = style.top = (-n * 40) + "px";
style.visibility = "hidden";
style.position = "absolute";
style.overflow = "visible";
style.whiteSpace = "nowrap";
// in FF 3.6 monospace fonts can have a fixed sub pixel width.
// that's why we have to measure many characters
// Note: characterWidth can be a float!
measureNode.innerHTML = lang.stringRepeat("Xy", n);
if (document.body) {
document.body.appendChild(measureNode);
} else {
var container = this.element.parentNode;
while (!dom.hasCssClass(container, "ace_editor"))
container = container.parentNode;
container.appendChild(measureNode);
}
}
var style = this.$measureNode.style;
var computedStyle = dom.computedStyle(this.element);
for (var prop in this.$fontStyles)
style[prop] = computedStyle[prop];
var size = {
height: this.$measureNode.offsetHeight,
width: this.$measureNode.offsetWidth / (n * 2)
};
// Size and width can be null if the editor is not visible or
// detached from the document
if (size.width == 0 && size.height == 0)
return null;
return size;
};
this.setSession = function(session) {
this.session = session;
};
this.showInvisibles = false;
this.setShowInvisibles = function(showInvisibles) {
if (this.showInvisibles == showInvisibles)
return false;
this.showInvisibles = showInvisibles;
return true;
};
this.$tabStrings = [];
this.$computeTabString = function() {
var tabSize = this.session.getTabSize();
var tabStr = this.$tabStrings = [0];
for (var i = 1; i < tabSize + 1; i++) {
if (this.showInvisibles) {
tabStr.push("<span class='ace_invisible'>"
+ this.TAB_CHAR
+ new Array(i).join(" ")
+ "</span>");
} else {
tabStr.push(new Array(i+1).join(" "));
}
}
};
this.updateLines = function(config, firstRow, lastRow) {
this.$computeTabString();
// Due to wrap line changes there can be new lines if e.g.
// the line to updated wrapped in the meantime.
if (this.config.lastRow != config.lastRow ||
this.config.firstRow != config.firstRow) {
this.scrollLines(config);
}
this.config = config;
var first = Math.max(firstRow, config.firstRow);
var last = Math.min(lastRow, config.lastRow);
var lineElements = this.element.childNodes;
var lineElementsIdx = 0;
for (var row = config.firstRow; row < first; row++) {
var foldLine = this.session.getFoldLine(row);
if (foldLine) {
if (foldLine.containsRow(first)) {
break;
} else {
row = foldLine.end.row;
}
}
lineElementsIdx ++;
}
for (var i=first; i<=last; i++) {
var lineElement = lineElements[lineElementsIdx++];
if (!lineElement)
continue;
var html = [];
var tokens = this.session.getTokens(i, i);
this.$renderLine(html, i, tokens[0].tokens, true);
lineElement = dom.setInnerHtml(lineElement, html.join(""));
i = this.session.getRowFoldEnd(i);
}
};
this.scrollLines = function(config) {
this.$computeTabString();
var oldConfig = this.config;
this.config = config;
if (!oldConfig || oldConfig.lastRow < config.firstRow)
return this.update(config);
if (config.lastRow < oldConfig.firstRow)
return this.update(config);
var el = this.element;
if (oldConfig.firstRow < config.firstRow)
for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--)
el.removeChild(el.firstChild);
if (oldConfig.lastRow > config.lastRow)
for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--)
el.removeChild(el.lastChild);
if (config.firstRow < oldConfig.firstRow) {
var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1);
if (el.firstChild)
el.insertBefore(fragment, el.firstChild);
else
el.appendChild(fragment);
}
if (config.lastRow > oldConfig.lastRow) {
var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow);
el.appendChild(fragment);
}
};
this.$renderLinesFragment = function(config, firstRow, lastRow) {
var fragment = document.createDocumentFragment(),
row = firstRow,
fold = this.session.getNextFold(row),
foldStart = fold ?fold.start.row :Infinity;
while (true) {
if(row > foldStart) {
row = fold.end.row+1;
fold = this.session.getNextFold(row);
foldStart = fold ?fold.start.row :Infinity;
}
if(row > lastRow)
break;
var container = dom.createElement("div");
var html = [];
// Get the tokens per line as there might be some lines in between
// beeing folded.
// OPTIMIZE: If there is a long block of unfolded lines, just make
// this call once for that big block of unfolded lines.
var tokens = this.session.getTokens(row, row);
if (tokens.length == 1)
this.$renderLine(html, row, tokens[0].tokens, false);
// don't use setInnerHtml since we are working with an empty DIV
container.innerHTML = html.join("");
var lines = container.childNodes
while(lines.length)
fragment.appendChild(lines[0]);
row++;
}
return fragment;
};
this.update = function(config) {
this.$computeTabString();
this.config = config;
var html = [];
var firstRow = config.firstRow, lastRow = config.lastRow;
var row = firstRow,
fold = this.session.getNextFold(row),
foldStart = fold ?fold.start.row :Infinity;
while (true) {
if(row > foldStart) {
row = fold.end.row+1;
fold = this.session.getNextFold(row);
foldStart = fold ?fold.start.row :Infinity;
}
if(row > lastRow)
break;
// Get the tokens per line as there might be some lines in between
// beeing folded.
// OPTIMIZE: If there is a long block of unfolded lines, just make
// this call once for that big block of unfolded lines.
var tokens = this.session.getTokens(row, row);
if (tokens.length == 1)
this.$renderLine(html, row, tokens[0].tokens, false);
row++;
}
this.element = dom.setInnerHtml(this.element, html.join(""));
};
this.$textToken = {
"text": true,
"rparen": true,
"lparen": true
};
this.$renderToken = function(stringBuilder, screenColumn, token, value) {
var self = this;
var replaceReg = /\t|&|<|( +)|([\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000])|[\u1100-\u115F]|[\u11A3-\u11A7]|[\u11FA-\u11FF]|[\u2329-\u232A]|[\u2E80-\u2E99]|[\u2E9B-\u2EF3]|[\u2F00-\u2FD5]|[\u2FF0-\u2FFB]|[\u3000-\u303E]|[\u3041-\u3096]|[\u3099-\u30FF]|[\u3105-\u312D]|[\u3131-\u318E]|[\u3190-\u31BA]|[\u31C0-\u31E3]|[\u31F0-\u321E]|[\u3220-\u3247]|[\u3250-\u32FE]|[\u3300-\u4DBF]|[\u4E00-\uA48C]|[\uA490-\uA4C6]|[\uA960-\uA97C]|[\uAC00-\uD7A3]|[\uD7B0-\uD7C6]|[\uD7CB-\uD7FB]|[\uF900-\uFAFF]|[\uFE10-\uFE19]|[\uFE30-\uFE52]|[\uFE54-\uFE66]|[\uFE68-\uFE6B]|[\uFF01-\uFF60]|[\uFFE0-\uFFE6]/g;
var replaceFunc = function(c, a, b, tabIdx, idx4) {
if (c.charCodeAt(0) == 32) {
return new Array(c.length+1).join(" ");
} else if (c == "\t") {
var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx);
screenColumn += tabSize - 1;
return self.$tabStrings[tabSize];
} else if (c == "&") {
if (useragent.isOldGecko)
return "&";
else
return "&";
} else if (c == "<") {
return "<";
} else if (c.match(/[\v\f \u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000]/)) {
if (self.showInvisibles) {
var space = new Array(c.length+1).join(self.SPACE_CHAR);
return "<span class='ace_invisible'>" + space + "</span>";
} else {
return " ";
}
} else {
screenColumn += 1;
return "<span class='ace_cjk' style='width:" +
(self.config.characterWidth * 2) +
"px'>" + c + "</span>";
}
};
var output = value.replace(replaceReg, replaceFunc);
if (!this.$textToken[token.type]) {
var classes = "ace_" + token.type.replace(/\./g, " ace_");
stringBuilder.push("<span class='", classes, "'>", output, "</span>");
}
else {
stringBuilder.push(output);
}
return screenColumn + value.length;
};
this.$renderLineCore = function(stringBuilder, lastRow, tokens, splits, onlyContents) {
var chars = 0;
var split = 0;
var splitChars;
var characterWidth = this.config.characterWidth;
var screenColumn = 0;
var self = this;
if (!splits || splits.length == 0)
splitChars = Number.MAX_VALUE;
else
splitChars = splits[0];
if (!onlyContents) {
stringBuilder.push("<div class='ace_line' style='height:",
this.config.lineHeight, "px",
"'>"
);
}
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
var value = token.value;
if (chars + value.length < splitChars) {
screenColumn = self.$renderToken(
stringBuilder, screenColumn, token, value
);
chars += value.length;
}
else {
while (chars + value.length >= splitChars) {
screenColumn = self.$renderToken(
stringBuilder, screenColumn,
token, value.substring(0, splitChars - chars)
);
value = value.substring(splitChars - chars);
chars = splitChars;
if (!onlyContents) {
stringBuilder.push("</div>",
"<div class='ace_line' style='height:",
this.config.lineHeight, "px",
"'>"
);
}
split ++;
screenColumn = 0;
splitChars = splits[split] || Number.MAX_VALUE;
}
if (value.length != 0) {
chars += value.length;
screenColumn = self.$renderToken(
stringBuilder, screenColumn, token, value
);
}
}
}
if (this.showInvisibles) {
if (lastRow !== this.session.getLength() - 1)
stringBuilder.push("<span class='ace_invisible'>" + this.EOL_CHAR + "</span>");
else
stringBuilder.push("<span class='ace_invisible'>" + this.EOF_CHAR + "</span>");
}
stringBuilder.push("</div>");
};
this.$renderLine = function(stringBuilder, row, tokens, onlyContents) {
// Check if the line to render is folded or not. If not, things are
// simple, otherwise, we need to fake some things...
if (!this.session.isRowFolded(row)) {
var splits = this.session.getRowSplitData(row);
this.$renderLineCore(stringBuilder, row, tokens, splits, onlyContents);
} else {
this.$renderFoldLine(stringBuilder, row, tokens, onlyContents);
}
};
this.$renderFoldLine = function(stringBuilder, row, tokens, onlyContents) {
var session = this.session,
foldLine = session.getFoldLine(row),
renderTokens = [];
function addTokens(tokens, from, to) {
var idx = 0, col = 0;
while ((col + tokens[idx].value.length) < from) {
col += tokens[idx].value.length;
idx++;
if (idx == tokens.length) {
return;
}
}
if (col != from) {
var value = tokens[idx].value.substring(from - col);
// Check if the token value is longer then the from...to spacing.
if (value.length > (to - from)) {
value = value.substring(0, to - from);
}
renderTokens.push({
type: tokens[idx].type,
value: value
});
col = from + value.length;
idx += 1;
}
while (col < to) {
var value = tokens[idx].value;
if (value.length + col > to) {
value = value.substring(0, to - col);
}
renderTokens.push({
type: tokens[idx].type,
value: value
});
col += value.length;
idx += 1;
}
}
foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
if (placeholder) {
renderTokens.push({
type: "fold",
value: placeholder
});
} else {
if (isNewRow) {
tokens = this.session.getTokens(row, row)[0].tokens;
}
if (tokens.length != 0) {
addTokens(tokens, lastColumn, column);
}
}
}.bind(this), foldLine.end.row, this.session.getLine(foldLine.end.row).length);
// TODO: Build a fake splits array!
var splits = this.session.$useWrapMode?this.session.$wrapData[row]:null;
this.$renderLineCore(stringBuilder, row, renderTokens, splits, onlyContents);
};
this.destroy = function() {
clearInterval(this.$pollSizeChangesTimer);
if (this.$measureNode)
this.$measureNode.parentNode.removeChild(this.$measureNode);
delete this.$measureNode;
};
}).call(Text.prototype);
exports.Text = Text;
});
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Julian Viereck <julian.viereck@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/layer/cursor', ['require', 'exports', 'module' , 'pilot/dom'], function(require, exports, module) {
var dom = require("pilot/dom");
var Cursor = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_cursor-layer";
parentEl.appendChild(this.element);
this.cursor = dom.createElement("div");
this.cursor.className = "ace_cursor ace_hidden";
this.element.appendChild(this.cursor);
this.isVisible = false;
};
(function() {
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
};
this.setSession = function(session) {
this.session = session;
};
this.hideCursor = function() {
this.isVisible = false;
dom.addCssClass(this.cursor, "ace_hidden");
clearInterval(this.blinkId);
};
this.showCursor = function() {
this.isVisible = true;
dom.removeCssClass(this.cursor, "ace_hidden");
this.cursor.style.visibility = "visible";
this.restartTimer();
};
this.restartTimer = function() {
clearInterval(this.blinkId);
if (!this.isVisible) {
return;
}
var cursor = this.cursor;
this.blinkId = setInterval(function() {
cursor.style.visibility = "hidden";
setTimeout(function() {
cursor.style.visibility = "visible";
}, 400);
}, 1000);
};
this.getPixelPosition = function(onScreen) {
if (!this.config || !this.session) {
return {
left : 0,
top : 0
};
}
var position = this.session.selection.getCursor();
var pos = this.session.documentToScreenPosition(position);
var cursorLeft = Math.round(this.$padding +
pos.column * this.config.characterWidth);
var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) *
this.config.lineHeight;
return {
left : cursorLeft,
top : cursorTop
};
};
this.update = function(config) {
this.config = config;
this.pixelPos = this.getPixelPosition(true);
this.cursor.style.left = this.pixelPos.left + "px";
this.cursor.style.top = this.pixelPos.top + "px";
this.cursor.style.width = config.characterWidth + "px";
this.cursor.style.height = config.lineHeight + "px";
var overwrite = this.session.getOverwrite()
if (overwrite != this.overwrite) {
this.overwrite = overwrite;
if (overwrite)
dom.addCssClass(this.cursor, "ace_overwrite");
else
dom.removeCssClass(this.cursor, "ace_overwrite");
}
this.restartTimer();
};
this.destroy = function() {
clearInterval(this.blinkId);
}
}).call(Cursor.prototype);
exports.Cursor = Cursor;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/scrollbar', ['require', 'exports', 'module' , 'pilot/oop', 'pilot/dom', 'pilot/event', 'pilot/event_emitter'], function(require, exports, module) {
var oop = require("pilot/oop");
var dom = require("pilot/dom");
var event = require("pilot/event");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var ScrollBar = function(parent) {
this.element = dom.createElement("div");
this.element.className = "ace_sb";
this.inner = dom.createElement("div");
this.element.appendChild(this.inner);
parent.appendChild(this.element);
// in OSX lion the scrollbars appear to have no width. In this case resize
// the to show the scrollbar but still pretend that the scrollbar has a width
// of 0px
this.width = dom.scrollbarWidth();
this.element.style.width = (this.width || 15) + "px";
event.addListener(this.element, "scroll", this.onScroll.bind(this));
};
(function() {
oop.implement(this, EventEmitter);
this.onScroll = function() {
this._dispatchEvent("scroll", {data: this.element.scrollTop});
};
this.getWidth = function() {
return this.width;
};
this.setHeight = function(height) {
this.element.style.height = height + "px";
};
this.setInnerHeight = function(height) {
this.inner.style.height = height + "px";
};
this.setScrollTop = function(scrollTop) {
this.element.scrollTop = scrollTop;
};
}).call(ScrollBar.prototype);
exports.ScrollBar = ScrollBar;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/renderloop', ['require', 'exports', 'module' , 'pilot/event'], function(require, exports, module) {
var event = require("pilot/event");
var RenderLoop = function(onRender) {
this.onRender = onRender;
this.pending = false;
this.changes = 0;
};
(function() {
this.schedule = function(change) {
//this.onRender(change);
//return;
this.changes = this.changes | change;
if (!this.pending) {
this.pending = true;
var _self = this;
this.setTimeoutZero(function() {
_self.pending = false;
var changes = _self.changes;
_self.changes = 0;
_self.onRender(changes);
})
}
};
this.setTimeoutZero = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
if (this.setTimeoutZero) {
this.setTimeoutZero = this.setTimeoutZero.bind(window)
} else if (window.postMessage) {
this.messageName = "zero-timeout-message";
this.setTimeoutZero = function(callback) {
if (!this.attached) {
var _self = this;
event.addListener(window, "message", function(e) {
if (_self.callback && e.data == _self.messageName) {
event.stopPropagation(e);
_self.callback();
}
});
this.attached = true;
}
this.callback = callback;
window.postMessage(this.messageName, "*");
}
} else {
this.setTimeoutZero = function(callback) {
setTimeout(callback, 0);
}
}
}).call(RenderLoop.prototype);
exports.RenderLoop = RenderLoop;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/textmate', ['require', 'exports', 'module' , 'pilot/dom'], function(require, exports, module) {
var dom = require("pilot/dom");
var cssText = ".ace-tm .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-tm .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-tm .ace_gutter {\
width: 50px;\
background: #e8e8e8;\
color: #333;\
overflow : hidden;\
}\
\
.ace-tm .ace_gutter-layer {\
width: 100%;\
text-align: right;\
}\
\
.ace-tm .ace_gutter-layer .ace_gutter-cell {\
padding-right: 6px;\
}\
\
.ace-tm .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-tm .ace_text-layer {\
cursor: text;\
}\
\
.ace-tm .ace_cursor {\
border-left: 2px solid black;\
}\
\
.ace-tm .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid black;\
}\
\
.ace-tm .ace_line .ace_invisible {\
color: rgb(191, 191, 191);\
}\
\
.ace-tm .ace_line .ace_keyword {\
color: blue;\
}\
\
.ace-tm .ace_line .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
\
.ace-tm .ace_line .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
\
.ace-tm .ace_line .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
\
.ace-tm .ace_line .ace_invalid {\
background-color: rgb(153, 0, 0);\
color: white;\
}\
\
.ace-tm .ace_line .ace_fold {\
background-color: #E4E4E4;\
border-radius: 3px;\
}\
\
.ace-tm .ace_line .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
\
.ace-tm .ace_line .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
\
.ace-tm .ace_line .ace_support.ace_type,\
.ace-tm .ace_line .ace_support.ace_class {\
color: rgb(109, 121, 222);\
}\
\
.ace-tm .ace_line .ace_keyword.ace_operator {\
color: rgb(104, 118, 135);\
}\
\
.ace-tm .ace_line .ace_string {\
color: rgb(3, 106, 7);\
}\
\
.ace-tm .ace_line .ace_comment {\
color: rgb(76, 136, 107);\
}\
\
.ace-tm .ace_line .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
\
.ace-tm .ace_line .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
\
.ace-tm .ace_line .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
\
.ace-tm .ace_line .ace_variable {\
color: rgb(49, 132, 149);\
}\
\
.ace-tm .ace_line .ace_xml_pe {\
color: rgb(104, 104, 91);\
}\
\
.ace-tm .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
\
.ace-tm .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
\
.ace-tm .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
\
.ace-tm .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
\
.ace-tm .ace_marker-layer .ace_active_line {\
background: rgba(0, 0, 0, 0.07);\
}\
\
.ace-tm .ace_marker-layer .ace_selected_word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
\
.ace-tm .ace_string.ace_regex {\
color: rgb(255, 0, 0)\
}";
// import CSS once
dom.importCssString(cssText);
exports.cssClass = "ace-tm";
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is DomTemplate.
*
* The Initial Developer of the Original Code is Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com) (original author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/environment', ['require', 'exports', 'module' , 'pilot/settings'], function(require, exports, module) {
var settings = require("pilot/settings").settings;
/**
* Create an environment object
*/
function create() {
return {
settings: settings
};
};
exports.create = create;
});
define("text/cockpit/ui/cli_view.css", [], "" +
"#cockpitInput { padding-left: 16px; }" +
"" +
".cptOutput { overflow: auto; position: absolute; z-index: 999; display: none; }" +
"" +
".cptCompletion { padding: 0; position: absolute; z-index: -1000; }" +
".cptCompletion.VALID { background: #FFF; }" +
".cptCompletion.INCOMPLETE { background: #DDD; }" +
".cptCompletion.INVALID { background: #DDD; }" +
".cptCompletion span { color: #FFF; }" +
".cptCompletion span.INCOMPLETE { color: #DDD; border-bottom: 2px dotted #F80; }" +
".cptCompletion span.INVALID { color: #DDD; border-bottom: 2px dotted #F00; }" +
"span.cptPrompt { color: #66F; font-weight: bold; }" +
"" +
"" +
".cptHints {" +
" color: #000;" +
" position: absolute;" +
" border: 1px solid rgba(230, 230, 230, 0.8);" +
" background: rgba(250, 250, 250, 0.8);" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 10px; border-top-right-radius: 10px;" +
" z-index: 1000;" +
" padding: 8px;" +
" display: none;" +
"}" +
"" +
".cptFocusPopup { display: block; }" +
".cptFocusPopup.cptNoPopup { display: none; }" +
"" +
".cptHints ul { margin: 0; padding: 0 15px; }" +
"" +
".cptGt { font-weight: bold; font-size: 120%; }" +
"");
define("text/cockpit/ui/request_view.css", [], "" +
".cptRowIn {" +
" display: box; display: -moz-box; display: -webkit-box;" +
" box-orient: horizontal; -moz-box-orient: horizontal; -webkit-box-orient: horizontal;" +
" box-align: center; -moz-box-align: center; -webkit-box-align: center;" +
" color: #333;" +
" background-color: #EEE;" +
" width: 100%;" +
" font-family: consolas, courier, monospace;" +
"}" +
".cptRowIn > * { padding-left: 2px; padding-right: 2px; }" +
".cptRowIn > img { cursor: pointer; }" +
".cptHover { display: none; }" +
".cptRowIn:hover > .cptHover { display: block; }" +
".cptRowIn:hover > .cptHover.cptHidden { display: none; }" +
".cptOutTyped {" +
" box-flex: 1; -moz-box-flex: 1; -webkit-box-flex: 1;" +
" font-weight: bold; color: #000; font-size: 120%;" +
"}" +
".cptRowOutput { padding-left: 10px; line-height: 1.2em; }" +
".cptRowOutput strong," +
".cptRowOutput b," +
".cptRowOutput th," +
".cptRowOutput h1," +
".cptRowOutput h2," +
".cptRowOutput h3 { color: #000; }" +
".cptRowOutput a { font-weight: bold; color: #666; text-decoration: none; }" +
".cptRowOutput a: hover { text-decoration: underline; cursor: pointer; }" +
".cptRowOutput input[type=password]," +
".cptRowOutput input[type=text]," +
".cptRowOutput textarea {" +
" color: #000; font-size: 120%;" +
" background: transparent; padding: 3px;" +
" border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;" +
"}" +
".cptRowOutput table," +
".cptRowOutput td," +
".cptRowOutput th { border: 0; padding: 0 2px; }" +
".cptRowOutput .right { text-align: right; }" +
"");
define("text/ace/css/editor.css", [], ".ace_editor {" +
" position: absolute;" +
" overflow: hidden;" +
" font-family: Monaco, \"Menlo\", \"Courier New\", monospace;" +
" font-size: 12px;" +
"}" +
"" +
".ace_scroller {" +
" position: absolute;" +
" overflow-x: scroll;" +
" overflow-y: hidden;" +
"}" +
"" +
".ace_content {" +
" position: absolute;" +
" box-sizing: border-box;" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
"}" +
"" +
".ace_composition {" +
" position: absolute;" +
" background: #555;" +
" color: #DDD;" +
" z-index: 4;" +
"}" +
"" +
".ace_gutter {" +
" position: absolute;" +
" overflow-x: hidden;" +
" overflow-y: hidden;" +
" height: 100%;" +
"}" +
"" +
".ace_gutter-cell.ace_error {" +
" background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%F5or%F5%87%88%F5nr%F4ns%EBmq%F5z%7F%DDJT%DEKS%DFOW%F1Yc%F2ah%CE(7%CE)8%D18E%DD%40M%F2KZ%EBU%60%F4%60m%DCir%C8%16(%C8%19*%CE%255%F1%3FR%F1%3FS%E6%AB%B5%CA%5DI%CEn%5E%F7%A2%9A%C9G%3E%E0a%5B%F7%89%85%F5yy%F6%82%80%ED%82%80%FF%BF%BF%E3%C4%C4%FF%FF%FF%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%25%00%2C%00%00%00%00%10%00%10%00%00%06p%C0%92pH%2C%1A%8F%C8%D2H%93%E1d4%23%E4%88%D3%09mB%1DN%B48%F5%90%40%60%92G%5B%94%20%3E%22%D2%87%24%FA%20%24%C5%06A%00%20%B1%07%02B%A38%89X.v%17%82%11%13q%10%0Fi%24%0F%8B%10%7BD%12%0Ei%09%92%09%0EpD%18%15%24%0A%9Ci%05%0C%18F%18%0B%07%04%01%04%06%A0H%18%12%0D%14%0D%12%A1I%B3%B4%B5IA%00%3B\");" +
" background-repeat: no-repeat;" +
" background-position: 4px center;" +
"}" +
"" +
".ace_gutter-cell.ace_warning {" +
" background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%FF%DBr%FF%DE%81%FF%E2%8D%FF%E2%8F%FF%E4%96%FF%E3%97%FF%E5%9D%FF%E6%9E%FF%EE%C1%FF%C8Z%FF%CDk%FF%D0s%FF%D4%81%FF%D5%82%FF%D5%83%FF%DC%97%FF%DE%9D%FF%E7%B8%FF%CCl%7BQ%13%80U%15%82W%16%81U%16%89%5B%18%87%5B%18%8C%5E%1A%94d%1D%C5%83-%C9%87%2F%C6%84.%C6%85.%CD%8B2%C9%871%CB%8A3%CD%8B5%DC%98%3F%DF%9BB%E0%9CC%E1%A5U%CB%871%CF%8B5%D1%8D6%DB%97%40%DF%9AB%DD%99B%E3%B0p%E7%CC%AE%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%2F%00%2C%00%00%00%00%10%00%10%00%00%06a%C0%97pH%2C%1A%8FH%A1%ABTr%25%87%2B%04%82%F4%7C%B9X%91%08%CB%99%1C!%26%13%84*iJ9(%15G%CA%84%14%01%1A%97%0C%03%80%3A%9A%3E%81%84%3E%11%08%B1%8B%20%02%12%0F%18%1A%0F%0A%03'F%1C%04%0B%10%16%18%10%0B%05%1CF%1D-%06%07%9A%9A-%1EG%1B%A0%A1%A0U%A4%A5%A6BA%00%3B\");" +
" background-repeat: no-repeat;" +
" background-position: 4px center;" +
"}" +
"" +
".ace_editor .ace_sb {" +
" position: absolute;" +
" overflow-x: hidden;" +
" overflow-y: scroll;" +
" right: 0;" +
"}" +
"" +
".ace_editor .ace_sb div {" +
" position: absolute;" +
" width: 1px;" +
" left: 0;" +
"}" +
"" +
".ace_editor .ace_print_margin_layer {" +
" z-index: 0;" +
" position: absolute;" +
" overflow: hidden;" +
" margin: 0;" +
" left: 0;" +
" height: 100%;" +
" width: 100%;" +
"}" +
"" +
".ace_editor .ace_print_margin {" +
" position: absolute;" +
" height: 100%;" +
"}" +
"" +
".ace_editor textarea {" +
" position: fixed;" +
" z-index: -1;" +
" width: 10px;" +
" height: 30px;" +
" opacity: 0;" +
" background: transparent;" +
" appearance: none;" +
" -moz-appearance: none;" +
" border: none;" +
" resize: none;" +
" outline: none;" +
" overflow: hidden;" +
"}" +
"" +
".ace_layer {" +
" z-index: 1;" +
" position: absolute;" +
" overflow: hidden;" +
" white-space: nowrap;" +
" height: 100%;" +
" width: 100%;" +
"}" +
"" +
".ace_text-layer {" +
" color: black;" +
"}" +
"" +
".ace_cjk {" +
" display: inline-block;" +
" text-align: center;" +
"}" +
"" +
".ace_cursor-layer {" +
" z-index: 4;" +
" cursor: text;" +
" /* setting pointer-events: none; here will break mouse wheel scrolling in Safari */" +
"}" +
"" +
".ace_cursor {" +
" z-index: 4;" +
" position: absolute;" +
"}" +
"" +
".ace_cursor.ace_hidden {" +
" opacity: 0.2;" +
"}" +
"" +
".ace_line {" +
" white-space: nowrap;" +
"}" +
"" +
".ace_marker-layer {" +
" cursor: text;" +
" pointer-events: none;" +
"}" +
"" +
".ace_marker-layer .ace_step {" +
" position: absolute;" +
" z-index: 3;" +
"}" +
"" +
".ace_marker-layer .ace_selection {" +
" position: absolute;" +
" z-index: 4;" +
"}" +
"" +
".ace_marker-layer .ace_bracket {" +
" position: absolute;" +
" z-index: 5;" +
"}" +
"" +
".ace_marker-layer .ace_active_line {" +
" position: absolute;" +
" z-index: 2;" +
"}" +
"" +
".ace_marker-layer .ace_selected_word {" +
" position: absolute;" +
" z-index: 6;" +
" box-sizing: border-box;" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
"}" +
"" +
".ace_line .ace_fold {" +
" cursor: pointer;" +
"}" +
"" +
".ace_dragging .ace_marker-layer, .ace_dragging .ace_text-layer {" +
" cursor: move;" +
"}" +
"");
define("text/build/demo/styles.css", [], "html {" +
" height: 100%;" +
" width: 100%;" +
" overflow: hidden;" +
"}" +
"" +
"body {" +
" overflow: hidden;" +
" margin: 0;" +
" padding: 0;" +
" height: 100%;" +
" width: 100%;" +
" font-family: Arial, Helvetica, sans-serif, Tahoma, Verdana, sans-serif;" +
" font-size: 12px;" +
" background: rgb(14, 98, 165);" +
" color: white;" +
"}" +
"" +
"#logo {" +
" padding: 15px;" +
" margin-left: 65px;" +
"}" +
"" +
"#editor {" +
" position: absolute;" +
" top: 0px;" +
" left: 280px;" +
" bottom: 0px;" +
" right: 0px;" +
" background: white;" +
"}" +
"" +
"#controls {" +
" padding: 5px;" +
"}" +
"" +
"#controls td {" +
" text-align: right;" +
"}" +
"" +
"#controls td + td {" +
" text-align: left;" +
"}" +
"" +
"#cockpitInput {" +
" position: absolute;" +
" left: 280px;" +
" right: 0px;" +
" bottom: 0;" +
"" +
" border: none; outline: none;" +
" font-family: consolas, courier, monospace;" +
" font-size: 120%;" +
"}" +
"" +
"#cockpitOutput {" +
" padding: 10px;" +
" margin: 0 15px;" +
" border: 1px solid #AAA;" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 4px; border-top-right-radius: 4px;" +
" background: #DDD; color: #000;" +
"}");
define("text/build_support/style.css", [], "body {" +
" margin:0;" +
" padding:0;" +
" background-color:#e6f5fc;" +
" " +
"}" +
"" +
"H2, H3, H4 {" +
" font-family:Trebuchet MS;" +
" font-weight:bold;" +
" margin:0;" +
" padding:0;" +
"}" +
"" +
"H2 {" +
" font-size:28px;" +
" color:#263842;" +
" padding-bottom:6px;" +
"}" +
"" +
"H3 {" +
" font-family:Trebuchet MS;" +
" font-weight:bold;" +
" font-size:22px;" +
" color:#253741;" +
" margin-top:43px;" +
" margin-bottom:8px;" +
"}" +
"" +
"H4 {" +
" font-family:Trebuchet MS;" +
" font-weight:bold;" +
" font-size:21px;" +
" color:#222222;" +
" margin-bottom:4px;" +
"}" +
"" +
"P {" +
" padding:13px 0;" +
" margin:0;" +
" line-height:22px;" +
"}" +
"" +
"UL{" +
" line-height : 22px;" +
"}" +
"" +
"PRE{" +
" background : #333;" +
" color : white;" +
" padding : 10px;" +
"}" +
"" +
"#header {" +
" height : 227px;" +
" position:relative;" +
" overflow:hidden;" +
" background: url(images/background.png) repeat-x 0 0;" +
" border-bottom:1px solid #c9e8fa; " +
"}" +
"" +
"#header .content .signature {" +
" font-family:Trebuchet MS;" +
" font-size:11px;" +
" color:#ebe4d6;" +
" position:absolute;" +
" bottom:5px;" +
" right:42px;" +
" letter-spacing : 1px;" +
"}" +
"" +
".content {" +
" width:970px;" +
" position:relative;" +
" overflow:hidden;" +
" margin:0 auto;" +
"}" +
"" +
"#header .content {" +
" height:184px;" +
" margin-top:22px;" +
"}" +
"" +
"#header .content .logo {" +
" width : 282px;" +
" height : 184px;" +
" background:url(images/logo.png) no-repeat 0 0;" +
" position:absolute;" +
" top:0;" +
" left:0;" +
"}" +
"" +
"#header .content .title {" +
" width : 605px;" +
" height : 58px;" +
" background:url(images/ace.png) no-repeat 0 0;" +
" position:absolute;" +
" top:98px;" +
" left:329px;" +
"}" +
"" +
"#wrapper {" +
" background:url(images/body_background.png) repeat-x 0 0;" +
" min-height:250px;" +
"}" +
"" +
"#wrapper .content {" +
" font-family:Arial;" +
" font-size:14px;" +
" color:#222222;" +
" width:1000px;" +
"}" +
"" +
"#wrapper .content .column1 {" +
" position:relative;" +
" overflow:hidden;" +
" float:left;" +
" width:315px;" +
" margin-right:31px;" +
"}" +
"" +
"#wrapper .content .column2 {" +
" position:relative;" +
" overflow:hidden;" +
" float:left;" +
" width:600px;" +
" padding-top:47px;" +
"}" +
"" +
".fork_on_github {" +
" width:310px;" +
" height:80px;" +
" background:url(images/fork_on_github.png) no-repeat 0 0;" +
" position:relative;" +
" overflow:hidden;" +
" margin-top:49px;" +
" cursor:pointer;" +
"}" +
"" +
".fork_on_github:hover {" +
" background-position:0 -80px;" +
"}" +
"" +
".divider {" +
" height:3px;" +
" background-color:#bedaea;" +
" margin-bottom:3px;" +
"}" +
"" +
".menu {" +
" padding:23px 0 0 24px;" +
"}" +
"" +
"UL.content-list {" +
" padding:15px;" +
" margin:0;" +
"}" +
"" +
"UL.menu-list {" +
" padding:0;" +
" margin:0 0 20px 0;" +
" list-style-type:none;" +
" line-height : 16px;" +
"}" +
"" +
"UL.menu-list LI {" +
" color:#2557b4;" +
" font-family:Trebuchet MS;" +
" font-size:14px;" +
" padding:7px 0;" +
" border-bottom:1px dotted #d6e2e7;" +
"}" +
"" +
"UL.menu-list LI:last-child {" +
" border-bottom:0;" +
"}" +
"" +
"A {" +
" color:#2557b4;" +
" text-decoration:none;" +
"}" +
"" +
"A:hover {" +
" text-decoration:underline;" +
"}" +
"" +
"P#first{" +
" background : rgba(255,255,255,0.5);" +
" padding : 20px;" +
" font-size : 16px;" +
" line-height : 24px;" +
" margin : 0 0 20px 0;" +
"}" +
"" +
"#footer {" +
" height:40px;" +
" position:relative;" +
" overflow:hidden;" +
" background:url(images/bottombar.png) repeat-x 0 0;" +
" position:relative;" +
" margin-top:40px;" +
"}" +
"" +
"UL.menu-footer {" +
" padding:0;" +
" margin:8px 11px 0 0;" +
" list-style-type:none;" +
" float:right;" +
"}" +
"" +
"UL.menu-footer LI {" +
" color:white;" +
" font-family:Arial;" +
" font-size:12px;" +
" display:inline-block;" +
" margin:0 1px;" +
"}" +
"" +
"UL.menu-footer LI A {" +
" color:#8dd0ff;" +
" text-decoration:none;" +
"}" +
"" +
"UL.menu-footer LI A:hover {" +
" text-decoration:underline;" +
"}" +
"" +
"" +
"" +
"" +
"");
define("text/demo/styles.css", [], "html {" +
" height: 100%;" +
" width: 100%;" +
" overflow: hidden;" +
"}" +
"" +
"body {" +
" overflow: hidden;" +
" margin: 0;" +
" padding: 0;" +
" height: 100%;" +
" width: 100%;" +
" font-family: Arial, Helvetica, sans-serif, Tahoma, Verdana, sans-serif;" +
" font-size: 12px;" +
" background: rgb(14, 98, 165);" +
" color: white;" +
"}" +
"" +
"#logo {" +
" padding: 15px;" +
" margin-left: 65px;" +
"}" +
"" +
"#editor {" +
" position: absolute;" +
" top: 0px;" +
" left: 280px;" +
" bottom: 0px;" +
" right: 0px;" +
" background: white;" +
"}" +
"" +
"#controls {" +
" padding: 5px;" +
"}" +
"" +
"#controls td {" +
" text-align: right;" +
"}" +
"" +
"#controls td + td {" +
" text-align: left;" +
"}" +
"" +
"#cockpitInput {" +
" position: absolute;" +
" left: 280px;" +
" right: 0px;" +
" bottom: 0;" +
"" +
" border: none; outline: none;" +
" font-family: consolas, courier, monospace;" +
" font-size: 120%;" +
"}" +
"" +
"#cockpitOutput {" +
" padding: 10px;" +
" margin: 0 15px;" +
" border: 1px solid #AAA;" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 4px; border-top-right-radius: 4px;" +
" background: #DDD; color: #000;" +
"}");
define("text/deps/csslint/demos/demo.css", [], "@charset \"UTF-8\";" +
"" +
"@import url(\"booya.css\") print,screen;" +
"@import \"whatup.css\" screen;" +
"@import \"wicked.css\";" +
"" +
"@namespace \"http://www.w3.org/1999/xhtml\";" +
"@namespace svg \"http://www.w3.org/2000/svg\";" +
"" +
"li.inline #foo {" +
" background: url(\"something.png\");" +
" display: inline;" +
" padding-left: 3px;" +
" padding-right: 7px;" +
" border-right: 1px dotted #066;" +
"}" +
"" +
"li.last.first {" +
" display: inline;" +
" padding-left: 3px !important;" +
" padding-right: 3px;" +
" border-right: 0px;" +
"}" +
"" +
"@media print {" +
" li.inline {" +
" color: black;" +
" }" +
"" +
"" +
"@charset \"UTF-8\"; " +
"" +
"@page {" +
" margin: 10%;" +
" counter-increment: page;" +
"" +
" @top-center {" +
" font-family: sans-serif;" +
" font-weight: bold;" +
" font-size: 2em;" +
" content: counter(page);" +
" }" +
"}");
define("text/deps/requirejs/dist/ie.css", [], "" +
"body .sect {" +
" display: none;" +
"}" +
"" +
"" +
"#content ul.index {" +
" list-style: none;" +
"}" +
"");
define("text/deps/requirejs/dist/main.css", [], "@font-face {" +
" font-family: Inconsolata;" +
" src: url(\"fonts/Inconsolata.ttf\");" +
"}" +
"" +
"* {" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
" box-sizing: border-box;" +
" margin: 0;" +
" padding: 0;" +
"}" +
"" +
"body {" +
" font-size: 12px;" +
" line-height: 21px;" +
" background-color: #fff;" +
" font-family: \"Helvetica Neue\", Helvetica, Arial, Verdana, sans-serif;" +
" color: #0a0a0a;" +
"}" +
"" +
"#wrapper {" +
" margin: 0;" +
"}" +
"" +
"#grid {" +
" position: fixed;" +
" top: 0;" +
" left: 0;" +
" width: 796px;" +
" background-image: url(\"i/grid.png\");" +
" z-index: 100;" +
"}" +
"" +
"pre {" +
" line-height: 18px;" +
" font-size: 13px;" +
" margin: 7px 0 21px;" +
" padding: 5px 10px;" +
" overflow: auto;" +
" background-color: #fafafa;" +
" border: 1px solid #e6e6e6;" +
" -moz-border-radius: 5px;" +
" -webkit-border-radius: 5px;" +
" border-radius: 5px;" +
" -moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);" +
" -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);" +
" box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);" +
"}" +
"" +
"/*" +
" typography stuff" +
"*/" +
".mono {" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
"}" +
"" +
".sans {" +
" font-family: \"Helvetica Neue\", Helvetica, Arial, Verdana, sans-serif;" +
"}" +
"" +
".serif {" +
" font-family: \"Georgia\", Times New Roman, Times, serif;" +
"}" +
"" +
"a {" +
" color: #2e87dd;" +
" text-decoration: none;" +
"}" +
"" +
"a:hover {" +
" text-decoration: underline;" +
"}" +
"" +
"/*" +
" navigation" +
"*/" +
"" +
"#navBg {" +
" background-color: #f2f2f2;" +
" background-image: url(\"i/shadow.png\");" +
" background-position: right top;" +
" background-repeat: repeat-y;" +
" width: 220px;" +
" position: fixed;" +
" top: 0;" +
" left: 0;" +
" z-index: 0;" +
"}" +
"" +
"#nav {" +
" background-image: url(\"i/logo.png\");" +
" background-repeat: no-repeat;" +
" background-position: center 10px;" +
" width: 220px;" +
" float: left;" +
" margin: 0;" +
" padding: 150px 20px 0;" +
" font-size: 13px;" +
" text-shadow: 1px 1px #fff;" +
" position: relative;" +
" z-index: 1;" +
"}" +
"" +
"#nav .homeImageLink {" +
" position: absolute;" +
" display: block;" +
" top: 10px;" +
" left: 0;" +
" width: 220px;" +
" height: 138px;" +
"}" +
"#nav ul {" +
" list-style-type:none;" +
" padding: 0;" +
" margin: 21px 0 0 0;" +
"}" +
"" +
"#nav ul li {" +
" width: 100%;" +
"}" +
"" +
"#nav ul li.version {" +
" text-align: center;" +
" color: #4d4d4d;" +
"}" +
"" +
"#nav h1 {" +
" color: #4d4d4d;" +
" text-align: center;" +
" font-size: 15px;" +
" font-weight: normal;" +
" text-transform: uppercase;" +
" letter-spacing: 3px;" +
"}" +
"" +
"span.spacer {" +
" color: #2e87dd;" +
" margin: 0 3px 0 5px;" +
" background-image: url(\"i/dot.png\");" +
" background-repeat: repeat-x;" +
" background-position: left 13px;" +
"}" +
"" +
"/*" +
" icons" +
"*/" +
"" +
"span.icon {" +
" width: 16px;" +
" display: block;" +
" background-image: url(\"i/sprite.png\");" +
" background-repeat: no-repeat;" +
"}" +
"" +
"span.icon.home {" +
" background-position: center 5px;" +
"}" +
"" +
"span.icon.start {" +
" background-position: center -27px;" +
"}" +
"" +
"span.icon.download {" +
" background-position: center -59px;" +
"}" +
"" +
"span.icon.api {" +
" background-position: center -89px;" +
"}" +
"" +
"span.icon.optimize {" +
" background-position: center -119px;" +
"}" +
"" +
"span.icon.script {" +
" background-position: center -150px;" +
"}" +
"" +
"span.icon.question {" +
" background-position: center -182px;" +
"}" +
"" +
"span.icon.requirement {" +
" background-position: center -214px;" +
"}" +
"" +
"span.icon.history {" +
" background-position: center -247px;" +
"}" +
"" +
"span.icon.help {" +
" background-position: center -279px;" +
"}" +
"" +
"span.icon.blog {" +
" background-position: center -311px;" +
"}" +
"" +
"span.icon.twitter {" +
" background-position: center -343px;" +
"}" +
"" +
"span.icon.git {" +
" background-position: center -375px;" +
"}" +
"" +
"span.icon.fork {" +
" background-position: center -407px;" +
"}" +
"" +
"/*" +
" content" +
"*/" +
"" +
"#content {" +
" margin: 0 0 0 220px;" +
" padding: 0 20px;" +
" background-color: #fff;" +
" font-family: \"Georgia\", Times New Roman, Times, serif;" +
" position: relative;" +
"}" +
"" +
"#content p {" +
" padding: 7px 0;" +
" color: #333;" +
" font-size: 14px;" +
"}" +
"" +
"#content h1," +
"#content h2," +
"#content h3," +
"#content h4," +
"#content h5 {" +
" font-weight: normal;" +
" padding: 21px 0 7px;" +
"}" +
"" +
"#content h1 {" +
" font-size: 21px;" +
"}" +
"" +
"#content h2 {" +
" padding: 0 0 18px 0;" +
" margin: 0 0 7px 0;" +
" font-weight: normal;" +
" font-size: 21px;" +
" line-height: 24px;" +
" text-align: center;" +
" color: #222;" +
" background-image: url(\"i/arrow.png\");" +
" background-repeat: no-repeat;" +
" background-position: center bottom;" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
" text-transform: uppercase;" +
" letter-spacing: 2px;" +
" text-shadow: 1px 1px 0 #fff;" +
"}" +
"" +
"#content h2 a {" +
" color: #222;" +
"}" +
"" +
"#content h2 a:hover," +
"#content h3 a:hover," +
"#content h4 a:hover {" +
" text-decoration: none;" +
"}" +
"" +
"span.sectionMark {" +
" display: block;" +
" color: #aaa;" +
" text-shadow: 1px 1px 0 #fff;" +
" font-size: 15px;" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
"}" +
"" +
"#content h3 {" +
" font-size: 17px;" +
"}" +
"" +
"#content h4 {" +
" padding-top: 0;" +
" font-size: 15px;" +
"}" +
"" +
"#content h5 {" +
" font-size: 10px;" +
"}" +
"" +
"#content ul {" +
" list-style-type: disc;" +
"}" +
"" +
"#content ul," +
"#content ol {" +
" /* border-left: 1px solid #333; */" +
" color: #333;" +
" font-size: 14px;" +
" list-style-position: outside;" +
" margin: 7px 0 21px 0;" +
" /* padding: 0 0 0 28px; */" +
"}" +
"" +
"#content ul {" +
" font-style: italic;" +
"}" +
"" +
"#content ol {" +
" border: none;" +
" list-style-position: inside;" +
" padding: 0;" +
" font-family: \"Georgia\", Times New Roman, Times, serif;" +
"}" +
"" +
"#content ul ul," +
"#content ol ol {" +
" border: none;" +
" padding: 0;" +
" margin: 0 0 0 28px;" +
"}" +
"" +
"#content .section {" +
" padding: 48px 0;" +
" background-image: url(\"i/line.png\");" +
" background-repeat: no-repeat;" +
" background-position: center bottom;" +
" width: 576px;" +
" margin: 0 auto;" +
"}" +
"" +
"#content .section .subSection {" +
" padding: 0 0 0 48px;" +
" margin: 28px 0 0 0;" +
" display: block;" +
" border-left: 2px solid #ddd;" +
"}" +
"" +
"#content .section:last-child {" +
" background-image: none;" +
"}" +
"" +
"#content .note {" +
" color: #222;" +
" background-color: #ffff99;" +
" padding: 5px 10px;" +
" margin: 7px 0;" +
" display: inline-block;" +
"}" +
"" +
"/*" +
" page directory" +
"*/" +
"" +
"#content #directory.section {" +
" background-color: #fff;" +
" width: 576px;" +
"}" +
"" +
"#content #directory.section ul ul ul {" +
" margin: 0 0 0 48px;" +
"}" +
"" +
"#content #directory.section ul ul li {" +
" background-image: url(\"i/sprite.png\");" +
" background-repeat: no-repeat;" +
" background-position: left -437px;" +
" padding-left: 18px;" +
" font-style: normal;" +
"}" +
"" +
"#content #directory h1 {" +
" padding: 0 0 65px 0;" +
" margin: 0 0 14px 0;" +
" font-weight: normal;" +
" font-size: 21px;" +
" text-align: center;" +
" text-transform: uppercase;" +
" letter-spacing: 2px;" +
" color: #222;" +
" background-image: url(\"i/arrow-x.png\");" +
" background-repeat: no-repeat;" +
" background-position: center bottom;" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
"}" +
"" +
"" +
"#content ul.index {" +
" padding: 0;" +
" background-color: transparent;" +
" border: none;" +
" -moz-box-shadow: none;" +
" font-style: normal;" +
" font-family: \"Inconsolata\", Andale Mono, Monaco, Monospace;" +
"}" +
"" +
"#content ul.index li {" +
" width: 100%;" +
" font-size: 15px;" +
" color: #333;" +
" padding: 0 0 7px 0;" +
"}" +
"" +
"" +
"/*" +
" intro page specific" +
"*/" +
"" +
"#content #intro {" +
" width: 576px;" +
" margin: 0 auto;" +
" padding: 21px 0;" +
"}" +
"" +
"#content #intro p," +
"#content #intro h1 {" +
" font-size: 19px;" +
" line-height: 28px;" +
" color: green;" +
" letter-spacing: 2px;" +
" padding: 0 0 28px 0;" +
"}" +
"" +
"#content #intro p:last-child," +
"#content #intro h1:last-child {" +
" padding: 0;" +
"}" +
"" +
"#content #intro p a {" +
" color: green;" +
" text-decoration: underline;" +
"}" +
"" +
"/*" +
" download page" +
"*/" +
"" +
"#content h4 a.download {" +
" -webkit-border-radius: 5px;" +
" -moz-border-radius: 5px;" +
" background-color: #F2F2F2;" +
" background-image: url(\"i/sprite.png\"), -moz-linear-gradient(center top , #FAFAFA 0%, #F2F2F2 100%);" +
" background-image: url(\"i/sprite.png\"), -webkit-gradient(linear, left top, left bottom, color-stop(0%, #fafafa), color-stop(100%, #f2f2f2));" +
" background-position: 7px -58px, center center;" +
" background-repeat: no-repeat, no-repeat;" +
" border: 1px solid #CCCCCC;" +
" color: #333333;" +
" font-size: 12px;" +
" margin: 0 0 0 5px;" +
" padding: 0 10px 0 25px;" +
" text-shadow: 1px 1px 0 #FFFFFF;" +
"}" +
"" +
"/*" +
" footer" +
"*/" +
"#footer {" +
" color: #4d4d4d;" +
" padding: 65px 20px 20px;" +
" margin: 20px 0 0 220px;" +
" text-align: center;" +
" display: block;" +
" font-size: 13px;" +
" background-image: url(\"i/arrow-x.png\");" +
" background-repeat: no-repeat;" +
" background-position: center top;" +
" background-color: #fff;" +
"}" +
"" +
"#footer .line {" +
" display: block;" +
"}" +
"" +
"#footer .line a {" +
" color: #4d4d4d;" +
" text-decoration: underline;" +
"}" +
"" +
"/*" +
" Pygments manni style" +
"*/" +
"" +
"code {background-color: #fafafa; color: #333;}" +
"" +
"code .comment {color: green; font-style: italic}" +
"code .comment.preproc {color: #099; font-style: normal}" +
"code .comment.special {font-weight: bold}" +
"" +
"code .keyword {color: #069; font-weight: bold}" +
"code .keyword.pseudo {font-weight: normal}" +
"code .keyword.type {color: #078}" +
"" +
"code .operator {color: #555}" +
"code .operator.word {color: #000; font-weight: bold}" +
"" +
"code .name.builtin {color: #366}" +
"code .name.function {color: #c0f}" +
"code .name.class {color: #0a8; font-weight: bold}" +
"code .name.namespace {color: #0cf; font-weight: bold}" +
"code .name.exception {color: #c00; font-weight: bold}" +
"code .name.variable {color: #033}" +
"code .name.constant {color: #360}" +
"code .name.label {color: #99f}" +
"code .name.entity {color: #999; font-weight: bold}" +
"code .name.attribute {color: #309}" +
"code .name.tag {color: #309; font-weight: bold}" +
"code .name.decorator {color: #99f}" +
"" +
"code .string {color: #c30}" +
"code .string.doc {font-style: italic}" +
"code .string.interpol {color: #a00}" +
"code .string.escape {color: #c30; font-weight: bold}" +
"code .string.regex {color: #3aa}" +
"code .string.symbol {color: #fc3}" +
"code .string.other {color: #c30}" +
"" +
"code .number {color: #f60}" +
"" +
"" +
"/*" +
" webkit scroll bars" +
"*/" +
"" +
"pre::-webkit-scrollbar {" +
" width: 6px;" +
" height: 6px;" +
"}" +
"" +
"pre::-webkit-scrollbar-button:start:decrement," +
"pre::-webkit-scrollbar-button:end:increment {" +
" display: block;" +
" height: 0;" +
" width: 0;" +
"}" +
"" +
"pre::-webkit-scrollbar-button:vertical:increment," +
"pre::-webkit-scrollbar-button:horizontal:increment {" +
" background-color: transparent;" +
" display: block;" +
" height: 0;" +
" width: 0;" +
"}" +
"" +
"pre::-webkit-scrollbar-track-piece {" +
" -webkit-border-radius: 3px;" +
"}" +
"" +
"pre::-webkit-scrollbar-thumb:vertical {" +
" background-color: #aaa;" +
" -webkit-border-radius: 3px;" +
"" +
"}" +
"" +
"pre::-webkit-scrollbar-thumb:horizontal {" +
" background-color: #aaa;" +
" -webkit-border-radius: 3px;" +
"}" +
"" +
"/*" +
" hbox" +
"*/" +
"" +
".hbox {" +
" display: -webkit-box;" +
" -webkit-box-orient: horizontal;" +
" -webkit-box-align: stretch;" +
"" +
" display: -moz-box;" +
" -moz-box-orient: horizontal;" +
" -moz-box-align: stretch;" +
"" +
" display: box;" +
" box-orient: horizontal;" +
" box-align: stretch;" +
"" +
" width: 100%;" +
"}" +
"" +
".hbox > * {" +
" -webkit-box-flex: 0;" +
" -moz-box-flex: 0;" +
" box-flex: 0;" +
" display: block;" +
"}" +
"" +
".vbox {" +
" display: -webkit-box;" +
" -webkit-box-orient: vertical;" +
" -webkit-box-align: stretch;" +
"" +
" display: -moz-box;" +
" -moz-box-orient: vertical;" +
" -moz-box-align: stretch;" +
"" +
" display: box;" +
" box-orient: vertical;" +
" box-align: stretch;" +
"}" +
"" +
".vbox > * {" +
" -webkit-box-flex: 0;" +
" -moz-box-flex: 0;" +
" box-flex: 0;" +
" display: block;" +
"}" +
"" +
".spacer {" +
" -webkit-box-flex: 1;" +
" -moz-box-flex: 1;" +
" box-flex: 1;" +
"}" +
"" +
".reverse {" +
" -webkit-box-direction: reverse;" +
" -moz-box-direction: reverse;" +
" box-direction: reverse;" +
"}" +
"" +
".boxFlex0 {" +
" -webkit-box-flex: 0;" +
" -moz-box-flex: 0;" +
" box-flex: 0;" +
"}" +
"" +
".boxFlex1, .boxFlex {" +
" -webkit-box-flex: 1;" +
" -moz-box-flex: 1;" +
" box-flex: 1;" +
"}" +
"" +
".boxFlex2 {" +
" -webkit-box-flex: 2;" +
" -moz-box-flex: 2;" +
" box-flex: 2;" +
"}" +
"" +
".boxGroup1 {" +
" -webkit-box-flex-group: 1;" +
" -moz-box-flex-group: 1;" +
" box-flex-group: 1;" +
"}" +
"" +
".boxGroup2 {" +
" -webkit-box-flex-group: 2;" +
" -moz-box-flex-group: 2;" +
" box-flex-group: 2;" +
"}" +
"" +
".start {" +
" -webkit-box-pack: start;" +
" -moz-box-pack: start;" +
" box-pack: start;" +
"}" +
"" +
".end {" +
" -webkit-box-pack: end;" +
" -moz-box-pack: end;" +
" box-pack: end;" +
"}" +
"" +
".center {" +
" -webkit-box-pack: center;" +
" -moz-box-pack: center;" +
" box-pack: center;" +
"}" +
"" +
"/*" +
" clearfix" +
"*/" +
"" +
".clearfix:after {" +
" content: \".\";" +
" display: block;" +
" clear: both;" +
" visibility: hidden;" +
" line-height: 0;" +
" height: 0;" +
"}" +
"" +
"html[xmlns] .clearfix {" +
" display: block;" +
"}" +
"" +
"* html .clearfix {" +
" height: 1%;" +
"}");
define("text/lib/ace/css/editor.css", [], ".ace_editor {" +
" position: absolute;" +
" overflow: hidden;" +
" font-family: Monaco, \"Menlo\", \"Courier New\", monospace;" +
" font-size: 12px;" +
"}" +
"" +
".ace_scroller {" +
" position: absolute;" +
" overflow-x: scroll;" +
" overflow-y: hidden;" +
"}" +
"" +
".ace_content {" +
" position: absolute;" +
" box-sizing: border-box;" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
"}" +
"" +
".ace_composition {" +
" position: absolute;" +
" background: #555;" +
" color: #DDD;" +
" z-index: 4;" +
"}" +
"" +
".ace_gutter {" +
" position: absolute;" +
" overflow-x: hidden;" +
" overflow-y: hidden;" +
" height: 100%;" +
"}" +
"" +
".ace_gutter-cell.ace_error {" +
" background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%F5or%F5%87%88%F5nr%F4ns%EBmq%F5z%7F%DDJT%DEKS%DFOW%F1Yc%F2ah%CE(7%CE)8%D18E%DD%40M%F2KZ%EBU%60%F4%60m%DCir%C8%16(%C8%19*%CE%255%F1%3FR%F1%3FS%E6%AB%B5%CA%5DI%CEn%5E%F7%A2%9A%C9G%3E%E0a%5B%F7%89%85%F5yy%F6%82%80%ED%82%80%FF%BF%BF%E3%C4%C4%FF%FF%FF%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%25%00%2C%00%00%00%00%10%00%10%00%00%06p%C0%92pH%2C%1A%8F%C8%D2H%93%E1d4%23%E4%88%D3%09mB%1DN%B48%F5%90%40%60%92G%5B%94%20%3E%22%D2%87%24%FA%20%24%C5%06A%00%20%B1%07%02B%A38%89X.v%17%82%11%13q%10%0Fi%24%0F%8B%10%7BD%12%0Ei%09%92%09%0EpD%18%15%24%0A%9Ci%05%0C%18F%18%0B%07%04%01%04%06%A0H%18%12%0D%14%0D%12%A1I%B3%B4%B5IA%00%3B\");" +
" background-repeat: no-repeat;" +
" background-position: 4px center;" +
"}" +
"" +
".ace_gutter-cell.ace_warning {" +
" background-image: url(\"data:image/gif,GIF89a%10%00%10%00%D5%00%00%FF%DBr%FF%DE%81%FF%E2%8D%FF%E2%8F%FF%E4%96%FF%E3%97%FF%E5%9D%FF%E6%9E%FF%EE%C1%FF%C8Z%FF%CDk%FF%D0s%FF%D4%81%FF%D5%82%FF%D5%83%FF%DC%97%FF%DE%9D%FF%E7%B8%FF%CCl%7BQ%13%80U%15%82W%16%81U%16%89%5B%18%87%5B%18%8C%5E%1A%94d%1D%C5%83-%C9%87%2F%C6%84.%C6%85.%CD%8B2%C9%871%CB%8A3%CD%8B5%DC%98%3F%DF%9BB%E0%9CC%E1%A5U%CB%871%CF%8B5%D1%8D6%DB%97%40%DF%9AB%DD%99B%E3%B0p%E7%CC%AE%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%00%2F%00%2C%00%00%00%00%10%00%10%00%00%06a%C0%97pH%2C%1A%8FH%A1%ABTr%25%87%2B%04%82%F4%7C%B9X%91%08%CB%99%1C!%26%13%84*iJ9(%15G%CA%84%14%01%1A%97%0C%03%80%3A%9A%3E%81%84%3E%11%08%B1%8B%20%02%12%0F%18%1A%0F%0A%03'F%1C%04%0B%10%16%18%10%0B%05%1CF%1D-%06%07%9A%9A-%1EG%1B%A0%A1%A0U%A4%A5%A6BA%00%3B\");" +
" background-repeat: no-repeat;" +
" background-position: 4px center;" +
"}" +
"" +
".ace_editor .ace_sb {" +
" position: absolute;" +
" overflow-x: hidden;" +
" overflow-y: scroll;" +
" right: 0;" +
"}" +
"" +
".ace_editor .ace_sb div {" +
" position: absolute;" +
" width: 1px;" +
" left: 0;" +
"}" +
"" +
".ace_editor .ace_print_margin_layer {" +
" z-index: 0;" +
" position: absolute;" +
" overflow: hidden;" +
" margin: 0;" +
" left: 0;" +
" height: 100%;" +
" width: 100%;" +
"}" +
"" +
".ace_editor .ace_print_margin {" +
" position: absolute;" +
" height: 100%;" +
"}" +
"" +
".ace_editor textarea {" +
" position: fixed;" +
" z-index: -1;" +
" width: 10px;" +
" height: 30px;" +
" opacity: 0;" +
" background: transparent;" +
" appearance: none;" +
" -moz-appearance: none;" +
" border: none;" +
" resize: none;" +
" outline: none;" +
" overflow: hidden;" +
"}" +
"" +
".ace_layer {" +
" z-index: 1;" +
" position: absolute;" +
" overflow: hidden;" +
" white-space: nowrap;" +
" height: 100%;" +
" width: 100%;" +
"}" +
"" +
".ace_text-layer {" +
" color: black;" +
"}" +
"" +
".ace_cjk {" +
" display: inline-block;" +
" text-align: center;" +
"}" +
"" +
".ace_cursor-layer {" +
" z-index: 4;" +
" cursor: text;" +
" /* setting pointer-events: none; here will break mouse wheel scrolling in Safari */" +
"}" +
"" +
".ace_cursor {" +
" z-index: 4;" +
" position: absolute;" +
"}" +
"" +
".ace_cursor.ace_hidden {" +
" opacity: 0.2;" +
"}" +
"" +
".ace_line {" +
" white-space: nowrap;" +
"}" +
"" +
".ace_marker-layer {" +
" cursor: text;" +
" pointer-events: none;" +
"}" +
"" +
".ace_marker-layer .ace_step {" +
" position: absolute;" +
" z-index: 3;" +
"}" +
"" +
".ace_marker-layer .ace_selection {" +
" position: absolute;" +
" z-index: 4;" +
"}" +
"" +
".ace_marker-layer .ace_bracket {" +
" position: absolute;" +
" z-index: 5;" +
"}" +
"" +
".ace_marker-layer .ace_active_line {" +
" position: absolute;" +
" z-index: 2;" +
"}" +
"" +
".ace_marker-layer .ace_selected_word {" +
" position: absolute;" +
" z-index: 6;" +
" box-sizing: border-box;" +
" -moz-box-sizing: border-box;" +
" -webkit-box-sizing: border-box;" +
"}" +
"" +
".ace_line .ace_fold {" +
" cursor: pointer;" +
"}" +
"" +
".ace_dragging .ace_marker-layer, .ace_dragging .ace_text-layer {" +
" cursor: move;" +
"}" +
"");
define("text/node_modules/uglify-js/docstyle.css", [], "html { font-family: \"Lucida Grande\",\"Trebuchet MS\",sans-serif; font-size: 12pt; }" +
"body { max-width: 60em; }" +
".title { text-align: center; }" +
".todo { color: red; }" +
".done { color: green; }" +
".tag { background-color:lightblue; font-weight:normal }" +
".target { }" +
".timestamp { color: grey }" +
".timestamp-kwd { color: CadetBlue }" +
"p.verse { margin-left: 3% }" +
"pre {" +
" border: 1pt solid #AEBDCC;" +
" background-color: #F3F5F7;" +
" padding: 5pt;" +
" font-family: monospace;" +
" font-size: 90%;" +
" overflow:auto;" +
"}" +
"pre.src {" +
" background-color: #eee; color: #112; border: 1px solid #000;" +
"}" +
"table { border-collapse: collapse; }" +
"td, th { vertical-align: top; }" +
"dt { font-weight: bold; }" +
"div.figure { padding: 0.5em; }" +
"div.figure p { text-align: center; }" +
".linenr { font-size:smaller }" +
".code-highlighted {background-color:#ffff00;}" +
".org-info-js_info-navigation { border-style:none; }" +
"#org-info-js_console-label { font-size:10px; font-weight:bold;" +
" white-space:nowrap; }" +
".org-info-js_search-highlight {background-color:#ffff00; color:#000000;" +
" font-weight:bold; }" +
"" +
"sup {" +
" vertical-align: baseline;" +
" position: relative;" +
" top: -0.5em;" +
" font-size: 80%;" +
"}" +
"" +
"sup a:link, sup a:visited {" +
" text-decoration: none;" +
" color: #c00;" +
"}" +
"" +
"sup a:before { content: \"[\"; color: #999; }" +
"sup a:after { content: \"]\"; color: #999; }" +
"" +
"h1.title { border-bottom: 4px solid #000; padding-bottom: 5px; margin-bottom: 2em; }" +
"" +
"#postamble {" +
" color: #777;" +
" font-size: 90%;" +
" padding-top: 1em; padding-bottom: 1em; border-top: 1px solid #999;" +
" margin-top: 2em;" +
" padding-left: 2em;" +
" padding-right: 2em;" +
" text-align: right;" +
"}" +
"" +
"#postamble p { margin: 0; }" +
"" +
"#footnotes { border-top: 1px solid #000; }" +
"" +
"h1 { font-size: 200% }" +
"h2 { font-size: 175% }" +
"h3 { font-size: 150% }" +
"h4 { font-size: 125% }" +
"" +
"h1, h2, h3, h4 { font-family: \"Bookman\",Georgia,\"Times New Roman\",serif; font-weight: normal; }" +
"" +
"@media print {" +
" html { font-size: 11pt; }" +
"}" +
"");
define("text/support/cockpit/lib/cockpit/ui/cli_view.css", [], "" +
"#cockpitInput { padding-left: 16px; }" +
"" +
".cptOutput { overflow: auto; position: absolute; z-index: 999; display: none; }" +
"" +
".cptCompletion { padding: 0; position: absolute; z-index: -1000; }" +
".cptCompletion.VALID { background: #FFF; }" +
".cptCompletion.INCOMPLETE { background: #DDD; }" +
".cptCompletion.INVALID { background: #DDD; }" +
".cptCompletion span { color: #FFF; }" +
".cptCompletion span.INCOMPLETE { color: #DDD; border-bottom: 2px dotted #F80; }" +
".cptCompletion span.INVALID { color: #DDD; border-bottom: 2px dotted #F00; }" +
"span.cptPrompt { color: #66F; font-weight: bold; }" +
"" +
"" +
".cptHints {" +
" color: #000;" +
" position: absolute;" +
" border: 1px solid rgba(230, 230, 230, 0.8);" +
" background: rgba(250, 250, 250, 0.8);" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 10px; border-top-right-radius: 10px;" +
" z-index: 1000;" +
" padding: 8px;" +
" display: none;" +
"}" +
"" +
".cptFocusPopup { display: block; }" +
".cptFocusPopup.cptNoPopup { display: none; }" +
"" +
".cptHints ul { margin: 0; padding: 0 15px; }" +
"" +
".cptGt { font-weight: bold; font-size: 120%; }" +
"");
define("text/support/cockpit/lib/cockpit/ui/request_view.css", [], "" +
".cptRowIn {" +
" display: box; display: -moz-box; display: -webkit-box;" +
" box-orient: horizontal; -moz-box-orient: horizontal; -webkit-box-orient: horizontal;" +
" box-align: center; -moz-box-align: center; -webkit-box-align: center;" +
" color: #333;" +
" background-color: #EEE;" +
" width: 100%;" +
" font-family: consolas, courier, monospace;" +
"}" +
".cptRowIn > * { padding-left: 2px; padding-right: 2px; }" +
".cptRowIn > img { cursor: pointer; }" +
".cptHover { display: none; }" +
".cptRowIn:hover > .cptHover { display: block; }" +
".cptRowIn:hover > .cptHover.cptHidden { display: none; }" +
".cptOutTyped {" +
" box-flex: 1; -moz-box-flex: 1; -webkit-box-flex: 1;" +
" font-weight: bold; color: #000; font-size: 120%;" +
"}" +
".cptRowOutput { padding-left: 10px; line-height: 1.2em; }" +
".cptRowOutput strong," +
".cptRowOutput b," +
".cptRowOutput th," +
".cptRowOutput h1," +
".cptRowOutput h2," +
".cptRowOutput h3 { color: #000; }" +
".cptRowOutput a { font-weight: bold; color: #666; text-decoration: none; }" +
".cptRowOutput a: hover { text-decoration: underline; cursor: pointer; }" +
".cptRowOutput input[type=password]," +
".cptRowOutput input[type=text]," +
".cptRowOutput textarea {" +
" color: #000; font-size: 120%;" +
" background: transparent; padding: 3px;" +
" border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;" +
"}" +
".cptRowOutput table," +
".cptRowOutput td," +
".cptRowOutput th { border: 0; padding: 0 2px; }" +
".cptRowOutput .right { text-align: right; }" +
"");
define("text/tool/Theme.tmpl.css", [], ".%cssClass% .ace_editor {" +
" border: 2px solid rgb(159, 159, 159);" +
"}" +
"" +
".%cssClass% .ace_editor.ace_focus {" +
" border: 2px solid #327fbd;" +
"}" +
"" +
".%cssClass% .ace_gutter {" +
" width: 50px;" +
" background: #e8e8e8;" +
" color: #333;" +
" overflow : hidden;" +
"}" +
"" +
".%cssClass% .ace_gutter-layer {" +
" width: 100%;" +
" text-align: right;" +
"}" +
"" +
".%cssClass% .ace_gutter-layer .ace_gutter-cell {" +
" padding-right: 6px;" +
"}" +
"" +
".%cssClass% .ace_print_margin {" +
" width: 1px;" +
" background: %printMargin%;" +
"}" +
"" +
".%cssClass% .ace_scroller {" +
" background-color: %background%;" +
"}" +
"" +
".%cssClass% .ace_text-layer {" +
" cursor: text;" +
" color: %foreground%;" +
"}" +
"" +
".%cssClass% .ace_cursor {" +
" border-left: 2px solid %cursor%;" +
"}" +
"" +
".%cssClass% .ace_cursor.ace_overwrite {" +
" border-left: 0px;" +
" border-bottom: 1px solid %overwrite%;" +
"}" +
" " +
".%cssClass% .ace_marker-layer .ace_selection {" +
" background: %selection%;" +
"}" +
"" +
".%cssClass% .ace_marker-layer .ace_step {" +
" background: %step%;" +
"}" +
"" +
".%cssClass% .ace_marker-layer .ace_bracket {" +
" margin: -1px 0 0 -1px;" +
" border: 1px solid %bracket%;" +
"}" +
"" +
".%cssClass% .ace_marker-layer .ace_active_line {" +
" background: %active_line%;" +
"}" +
"" +
" " +
".%cssClass% .ace_invisible {" +
" %invisible%" +
"}" +
"" +
".%cssClass% .ace_keyword {" +
" %keyword%" +
"}" +
"" +
".%cssClass% .ace_keyword.ace_operator {" +
" %keyword.operator%" +
"}" +
"" +
".%cssClass% .ace_constant {" +
" %constant%" +
"}" +
"" +
".%cssClass% .ace_constant.ace_language {" +
" %constant.language%" +
"}" +
"" +
".%cssClass% .ace_constant.ace_library {" +
" %constant.library%" +
"}" +
"" +
".%cssClass% .ace_constant.ace_numeric {" +
" %constant.numeric%" +
"}" +
"" +
".%cssClass% .ace_invalid {" +
" %invalid%" +
"}" +
"" +
".%cssClass% .ace_invalid.ace_illegal {" +
" %invalid.illegal%" +
"}" +
"" +
".%cssClass% .ace_invalid.ace_deprecated {" +
" %invalid.deprecated%" +
"}" +
"" +
".%cssClass% .ace_support {" +
" %support%" +
"}" +
"" +
".%cssClass% .ace_support.ace_function {" +
" %support.function%" +
"}" +
"" +
".%cssClass% .ace_function.ace_buildin {" +
" %function.buildin%" +
"}" +
"" +
".%cssClass% .ace_string {" +
" %string%" +
"}" +
"" +
".%cssClass% .ace_string.ace_regexp {" +
" %string.regexp%" +
"}" +
"" +
".%cssClass% .ace_comment {" +
" %comment%" +
"}" +
"" +
".%cssClass% .ace_comment.ace_doc {" +
" %comment.doc%" +
"}" +
"" +
".%cssClass% .ace_comment.ace_doc.ace_tag {" +
" %comment.doc.tag%" +
"}" +
"" +
".%cssClass% .ace_variable {" +
" %variable%" +
"}" +
"" +
".%cssClass% .ace_variable.ace_language {" +
" %variable.language%" +
"}" +
"" +
".%cssClass% .ace_xml_pe {" +
" %xml_pe%" +
"}" +
"" +
".%cssClass% .ace_collab.ace_user1 {" +
" %collab.user1% " +
"}");
define("text/styles.css", [], "html {" +
" height: 100%;" +
" width: 100%;" +
" overflow: hidden;" +
"}" +
"" +
"body {" +
" overflow: hidden;" +
" margin: 0;" +
" padding: 0;" +
" height: 100%;" +
" width: 100%;" +
" font-family: Arial, Helvetica, sans-serif, Tahoma, Verdana, sans-serif;" +
" font-size: 12px;" +
" background: rgb(14, 98, 165);" +
" color: white;" +
"}" +
"" +
"#logo {" +
" padding: 15px;" +
" margin-left: 65px;" +
"}" +
"" +
"#editor {" +
" position: absolute;" +
" top: 0px;" +
" left: 280px;" +
" bottom: 0px;" +
" right: 0px;" +
" background: white;" +
"}" +
"" +
"#controls {" +
" padding: 5px;" +
"}" +
"" +
"#controls td {" +
" text-align: right;" +
"}" +
"" +
"#controls td + td {" +
" text-align: left;" +
"}" +
"" +
"#cockpitInput {" +
" position: absolute;" +
" left: 280px;" +
" right: 0px;" +
" bottom: 0;" +
"" +
" border: none; outline: none;" +
" font-family: consolas, courier, monospace;" +
" font-size: 120%;" +
"}" +
"" +
"#cockpitOutput {" +
" padding: 10px;" +
" margin: 0 15px;" +
" border: 1px solid #AAA;" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 4px; border-top-right-radius: 4px;" +
" background: #DDD; color: #000;" +
"}");
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
require(["ace/ace"], function(ace) {
window.ace = ace;
}); | zzangtest123-google-drive-sdk-samples | php/static/ace/ace-uncompressed.js | JavaScript | asf20 | 582,900 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Kevin Dangoor (kdangoor@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/index', ['require', 'exports', 'module' , 'pilot/index', 'cockpit/cli', 'cockpit/ui/settings', 'cockpit/ui/cli_view', 'cockpit/commands/basic'], function(require, exports, module) {
exports.startup = function(data, reason) {
require('pilot/index');
require('cockpit/cli').startup(data, reason);
// window.testCli = require('cockpit/test/testCli');
require('cockpit/ui/settings').startup(data, reason);
require('cockpit/ui/cli_view').startup(data, reason);
require('cockpit/commands/basic').startup(data, reason);
};
/*
exports.shutdown(data, reason) {
};
*/
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/cli', ['require', 'exports', 'module' , 'pilot/console', 'pilot/lang', 'pilot/oop', 'pilot/event_emitter', 'pilot/types', 'pilot/canon'], function(require, exports, module) {
var console = require('pilot/console');
var lang = require('pilot/lang');
var oop = require('pilot/oop');
var EventEmitter = require('pilot/event_emitter').EventEmitter;
//var keyboard = require('keyboard/keyboard');
var types = require('pilot/types');
var Status = require('pilot/types').Status;
var Conversion = require('pilot/types').Conversion;
var canon = require('pilot/canon');
/**
* Normally type upgrade is done when the owning command is registered, but
* out commandParam isn't part of a command, so it misses out.
*/
exports.startup = function(data, reason) {
canon.upgradeType('command', commandParam);
};
/**
* The information required to tell the user there is a problem with their
* input.
* TODO: There a several places where {start,end} crop up. Perhaps we should
* have a Cursor object.
*/
function Hint(status, message, start, end, predictions) {
this.status = status;
this.message = message;
if (typeof start === 'number') {
this.start = start;
this.end = end;
this.predictions = predictions;
}
else {
var arg = start;
this.start = arg.start;
this.end = arg.end;
this.predictions = arg.predictions;
}
}
Hint.prototype = {
};
/**
* Loop over the array of hints finding the one we should display.
* @param hints array of hints
*/
Hint.sort = function(hints, cursor) {
// Calculate 'distance from cursor'
if (cursor !== undefined) {
hints.forEach(function(hint) {
if (hint.start === Argument.AT_CURSOR) {
hint.distance = 0;
}
else if (cursor < hint.start) {
hint.distance = hint.start - cursor;
}
else if (cursor > hint.end) {
hint.distance = cursor - hint.end;
}
else {
hint.distance = 0;
}
}, this);
}
// Sort
hints.sort(function(hint1, hint2) {
// Compare first based on distance from cursor
if (cursor !== undefined) {
var diff = hint1.distance - hint2.distance;
if (diff != 0) {
return diff;
}
}
// otherwise go with hint severity
return hint2.status - hint1.status;
});
// tidy-up
if (cursor !== undefined) {
hints.forEach(function(hint) {
delete hint.distance;
}, this);
}
return hints;
};
exports.Hint = Hint;
/**
* A Hint that arose as a result of a Conversion
*/
function ConversionHint(conversion, arg) {
this.status = conversion.status;
this.message = conversion.message;
if (arg) {
this.start = arg.start;
this.end = arg.end;
}
else {
this.start = 0;
this.end = 0;
}
this.predictions = conversion.predictions;
};
oop.inherits(ConversionHint, Hint);
/**
* We record where in the input string an argument comes so we can report errors
* against those string positions.
* We publish a 'change' event when-ever the text changes
* @param emitter Arguments use something else to pass on change events.
* Currently this will be the creating Requisition. This prevents dependency
* loops and prevents us from needing to merge listener lists.
* @param text The string (trimmed) that contains the argument
* @param start The position of the text in the original input string
* @param end See start
* @param prefix Knowledge of quotation marks and whitespace used prior to the
* text in the input string allows us to re-generate the original input from
* the arguments.
* @param suffix Any quotation marks and whitespace used after the text.
* Whitespace is normally placed in the prefix to the succeeding argument, but
* can be used here when this is the last argument.
* @constructor
*/
function Argument(emitter, text, start, end, prefix, suffix) {
this.emitter = emitter;
this.setText(text);
this.start = start;
this.end = end;
this.prefix = prefix;
this.suffix = suffix;
}
Argument.prototype = {
/**
* Return the result of merging these arguments.
* TODO: What happens when we're merging arguments for the single string
* case and some of the arguments are in quotation marks?
*/
merge: function(following) {
if (following.emitter != this.emitter) {
throw new Error('Can\'t merge Arguments from different EventEmitters');
}
return new Argument(
this.emitter,
this.text + this.suffix + following.prefix + following.text,
this.start, following.end,
this.prefix,
following.suffix);
},
/**
* See notes on events in Assignment. We might need to hook changes here
* into a CliRequisition so they appear of the command line.
*/
setText: function(text) {
if (text == null) {
throw new Error('Illegal text for Argument: ' + text);
}
var ev = { argument: this, oldText: this.text, text: text };
this.text = text;
this.emitter._dispatchEvent('argumentChange', ev);
},
/**
* Helper when we're putting arguments back together
*/
toString: function() {
// TODO: There is a bug here - we should re-escape escaped characters
// But can we do that reliably?
return this.prefix + this.text + this.suffix;
}
};
/**
* Merge an array of arguments into a single argument.
* All Arguments in the array are expected to have the same emitter
*/
Argument.merge = function(argArray, start, end) {
start = (start === undefined) ? 0 : start;
end = (end === undefined) ? argArray.length : end;
var joined;
for (var i = start; i < end; i++) {
var arg = argArray[i];
if (!joined) {
joined = arg;
}
else {
joined = joined.merge(arg);
}
}
return joined;
};
/**
* We sometimes need a way to say 'this error occurs where ever the cursor is'
*/
Argument.AT_CURSOR = -1;
/**
* A link between a parameter and the data for that parameter.
* The data for the parameter is available as in the preferred type and as
* an Argument for the CLI.
* <p>We also record validity information where applicable.
* <p>For values, null and undefined have distinct definitions. null means
* that a value has been provided, undefined means that it has not.
* Thus, null is a valid default value, and common because it identifies an
* parameter that is optional. undefined means there is no value from
* the command line.
* @constructor
*/
function Assignment(param, requisition) {
this.param = param;
this.requisition = requisition;
this.setValue(param.defaultValue);
};
Assignment.prototype = {
/**
* The parameter that we are assigning to
* @readonly
*/
param: undefined,
/**
* Report on the status of the last parse() conversion.
* @see types.Conversion
*/
conversion: undefined,
/**
* The current value in a type as specified by param.type
*/
value: undefined,
/**
* The string version of the current value
*/
arg: undefined,
/**
* The current value (i.e. not the string representation)
* Use setValue() to mutate
*/
value: undefined,
setValue: function(value) {
if (this.value === value) {
return;
}
if (value === undefined) {
this.value = this.param.defaultValue;
this.conversion = this.param.getDefault ?
this.param.getDefault() :
this.param.type.getDefault();
this.arg = undefined;
} else {
this.value = value;
this.conversion = undefined;
var text = (value == null) ? '' : this.param.type.stringify(value);
if (this.arg) {
this.arg.setText(text);
}
}
this.requisition._assignmentChanged(this);
},
/**
* The textual representation of the current value
* Use setValue() to mutate
*/
arg: undefined,
setArgument: function(arg) {
if (this.arg === arg) {
return;
}
this.arg = arg;
this.conversion = this.param.type.parse(arg.text);
this.conversion.arg = arg; // TODO: make this automatic?
this.value = this.conversion.value;
this.requisition._assignmentChanged(this);
},
/**
* Create a list of the hints associated with this parameter assignment.
* Generally there will be only one hint generated because we're currently
* only displaying one hint at a time, ordering by distance from cursor
* and severity. Since distance from cursor will be the same for all hints
* from this assignment all but the most severe will ever be used. It might
* make sense with more experience to alter this to function to be getHint()
*/
getHint: function() {
// Allow the parameter to provide documentation
if (this.param.getCustomHint && this.value && this.arg) {
var hint = this.param.getCustomHint(this.value, this.arg);
if (hint) {
return hint;
}
}
// If there is no argument, use the cursor position
var message = '<strong>' + this.param.name + '</strong>: ';
if (this.param.description) {
// TODO: This should be a short description - do we need to trim?
message += this.param.description.trim();
// Ensure the help text ends with '. '
if (message.charAt(message.length - 1) !== '.') {
message += '.';
}
if (message.charAt(message.length - 1) !== ' ') {
message += ' ';
}
}
var status = Status.VALID;
var start = this.arg ? this.arg.start : Argument.AT_CURSOR;
var end = this.arg ? this.arg.end : Argument.AT_CURSOR;
var predictions;
// Non-valid conversions will have useful information to pass on
if (this.conversion) {
status = this.conversion.status;
if (this.conversion.message) {
message += this.conversion.message;
}
predictions = this.conversion.predictions;
}
// Hint if the param is required, but not provided
var argProvided = this.arg && this.arg.text !== '';
var dataProvided = this.value !== undefined || argProvided;
if (this.param.defaultValue === undefined && !dataProvided) {
status = Status.INVALID;
message += '<strong>Required<\strong>';
}
return new Hint(status, message, start, end, predictions);
},
/**
* Basically <tt>setValue(conversion.predictions[0])</tt> done in a safe
* way.
*/
complete: function() {
if (this.conversion && this.conversion.predictions &&
this.conversion.predictions.length > 0) {
this.setValue(this.conversion.predictions[0]);
}
},
/**
* If the cursor is at 'position', do we have sufficient data to start
* displaying the next hint. This is both complex and important.
* For example, if the user has just typed:<ul>
* <li>'set tabstop ' then they clearly want to know about the valid
* values for the tabstop setting, so the hint is based on the next
* parameter.
* <li>'set tabstop' (without trailing space) - they will probably still
* want to know about the valid values for the tabstop setting because
* there is no confusion about the setting in question.
* <li>'set tabsto' they've not finished typing a setting name so the hint
* should be based on the current parameter.
* <li>'set tabstop' (when there is an additional tabstopstyle setting) we
* can't make assumptions about the setting - we're not finished.
* </ul>
* <p>Note that the input for 2 and 4 is identical, only the configuration
* has changed, so hint display is environmental.
*
* <p>This function works out if the cursor is before the end of this
* assignment (assuming that we've asked the same thing of the previous
* assignment) and then attempts to work out if we should use the hint from
* the next assignment even though technically the cursor is still inside
* this one due to the rules above.
*/
isPositionCaptured: function(position) {
if (!this.arg) {
return false;
}
// Note we don't check if position >= this.arg.start because that's
// implied by the fact that we're asking the assignments in turn, and
// we want to avoid thing falling between the cracks, but we do need
// to check that the argument does have a position
if (this.arg.start === -1) {
return false;
}
// We're clearly done if the position is past the end of the text
if (position > this.arg.end) {
return false;
}
// If we're AT the end, the position is captured if either the status
// is not valid or if there are other valid options including current
if (position === this.arg.end) {
return this.conversion.status !== Status.VALID ||
this.conversion.predictions.length !== 0;
}
// Otherwise we're clearly inside
return true;
},
/**
* Replace the current value with the lower value if such a concept
* exists.
*/
decrement: function() {
var replacement = this.param.type.decrement(this.value);
if (replacement != null) {
this.setValue(replacement);
}
},
/**
* Replace the current value with the higher value if such a concept
* exists.
*/
increment: function() {
var replacement = this.param.type.increment(this.value);
if (replacement != null) {
this.setValue(replacement);
}
},
/**
* Helper when we're rebuilding command lines.
*/
toString: function() {
return this.arg ? this.arg.toString() : '';
}
};
exports.Assignment = Assignment;
/**
* This is a special parameter to reflect the command itself.
*/
var commandParam = {
name: '__command',
type: 'command',
description: 'The command to execute',
/**
* Provide some documentation for a command.
*/
getCustomHint: function(command, arg) {
var docs = [];
docs.push('<strong><tt> > ');
docs.push(command.name);
if (command.params && command.params.length > 0) {
command.params.forEach(function(param) {
if (param.defaultValue === undefined) {
docs.push(' [' + param.name + ']');
}
else {
docs.push(' <em>[' + param.name + ']</em>');
}
}, this);
}
docs.push('</tt></strong><br/>');
docs.push(command.description ? command.description : '(No description)');
docs.push('<br/>');
if (command.params && command.params.length > 0) {
docs.push('<ul>');
command.params.forEach(function(param) {
docs.push('<li>');
docs.push('<strong><tt>' + param.name + '</tt></strong>: ');
docs.push(param.description ? param.description : '(No description)');
if (param.defaultValue === undefined) {
docs.push(' <em>[Required]</em>');
}
else if (param.defaultValue === null) {
docs.push(' <em>[Optional]</em>');
}
else {
docs.push(' <em>[Default: ' + param.defaultValue + ']</em>');
}
docs.push('</li>');
}, this);
docs.push('</ul>');
}
return new Hint(Status.VALID, docs.join(''), arg);
}
};
/**
* A Requisition collects the information needed to execute a command.
* There is no point in a requisition for parameter-less commands because there
* is no information to collect. A Requisition is a collection of assignments
* of values to parameters, each handled by an instance of Assignment.
* CliRequisition adds functions for parsing input from a command line to this
* class.
* <h2>Events<h2>
* We publish the following events:<ul>
* <li>argumentChange: The text of some argument has changed. It is likely that
* any UI component displaying this argument will need to be updated. (Note that
* this event is actually published by the Argument itself - see the docs for
* Argument for more details)
* The event object looks like: { argument: A, oldText: B, text: B }
* <li>commandChange: The command has changed. It is likely that a UI
* structure will need updating to match the parameters of the new command.
* The event object looks like { command: A }
* @constructor
*/
function Requisition(env) {
this.env = env;
this.commandAssignment = new Assignment(commandParam, this);
}
Requisition.prototype = {
/**
* The command that we are about to execute.
* @see setCommandConversion()
* @readonly
*/
commandAssignment: undefined,
/**
* The count of assignments. Excludes the commandAssignment
* @readonly
*/
assignmentCount: undefined,
/**
* The object that stores of Assignment objects that we are filling out.
* The Assignment objects are stored under their param.name for named
* lookup. Note: We make use of the property of Javascript objects that
* they are not just hashmaps, but linked-list hashmaps which iterate in
* insertion order.
* Excludes the commandAssignment.
*/
_assignments: undefined,
/**
* The store of hints generated by the assignments. We are trying to prevent
* the UI from needing to access this in broad form, but instead use
* methods that query part of this structure.
*/
_hints: undefined,
/**
* When the command changes, we need to keep a bunch of stuff in sync
*/
_assignmentChanged: function(assignment) {
// This is all about re-creating Assignments
if (assignment.param.name !== '__command') {
return;
}
this._assignments = {};
if (assignment.value) {
assignment.value.params.forEach(function(param) {
this._assignments[param.name] = new Assignment(param, this);
}, this);
}
this.assignmentCount = Object.keys(this._assignments).length;
this._dispatchEvent('commandChange', { command: assignment.value });
},
/**
* Assignments have an order, so we need to store them in an array.
* But we also need named access ...
*/
getAssignment: function(nameOrNumber) {
var name = (typeof nameOrNumber === 'string') ?
nameOrNumber :
Object.keys(this._assignments)[nameOrNumber];
return this._assignments[name];
},
/**
* Where parameter name == assignment names - they are the same.
*/
getParameterNames: function() {
return Object.keys(this._assignments);
},
/**
* A *shallow* clone of the assignments.
* This is useful for systems that wish to go over all the assignments
* finding values one way or another and wish to trim an array as they go.
*/
cloneAssignments: function() {
return Object.keys(this._assignments).map(function(name) {
return this._assignments[name];
}, this);
},
/**
* Collect the statuses from the Assignments.
* The hints returned are sorted by severity
*/
_updateHints: function() {
// TODO: work out when to clear this out for the plain Requisition case
// this._hints = [];
this.getAssignments(true).forEach(function(assignment) {
this._hints.push(assignment.getHint());
}, this);
Hint.sort(this._hints);
// We would like to put some initial help here, but for anyone but
// a complete novice a 'type help' message is very annoying, so we
// need to find a way to only display this message once, or for
// until the user click a 'close' button or similar
// TODO: Add special case for '' input
},
/**
* Returns the most severe status
*/
getWorstHint: function() {
return this._hints[0];
},
/**
* Extract the names and values of all the assignments, and return as
* an object.
*/
getArgsObject: function() {
var args = {};
this.getAssignments().forEach(function(assignment) {
args[assignment.param.name] = assignment.value;
}, this);
return args;
},
/**
* Access the arguments as an array.
* @param includeCommand By default only the parameter arguments are
* returned unless (includeCommand === true), in which case the list is
* prepended with commandAssignment.arg
*/
getAssignments: function(includeCommand) {
var args = [];
if (includeCommand === true) {
args.push(this.commandAssignment);
}
Object.keys(this._assignments).forEach(function(name) {
args.push(this.getAssignment(name));
}, this);
return args;
},
/**
* Reset all the assignments to their default values
*/
setDefaultValues: function() {
this.getAssignments().forEach(function(assignment) {
assignment.setValue(undefined);
}, this);
},
/**
* Helper to call canon.exec
*/
exec: function() {
canon.exec(this.commandAssignment.value,
this.env,
"cli",
this.getArgsObject(),
this.toCanonicalString());
},
/**
* Extract a canonical version of the input
*/
toCanonicalString: function() {
var line = [];
line.push(this.commandAssignment.value.name);
Object.keys(this._assignments).forEach(function(name) {
var assignment = this._assignments[name];
var type = assignment.param.type;
// TODO: This will cause problems if there is a non-default value
// after a default value. Also we need to decide when to use
// named parameters in place of positional params. Both can wait.
if (assignment.value !== assignment.param.defaultValue) {
line.push(' ');
line.push(type.stringify(assignment.value));
}
}, this);
return line.join('');
}
};
oop.implement(Requisition.prototype, EventEmitter);
exports.Requisition = Requisition;
/**
* An object used during command line parsing to hold the various intermediate
* data steps.
* <p>The 'output' of the update is held in 2 objects: input.hints which is an
* array of hints to display to the user. In the future this will become a
* single value.
* <p>The other output value is input.requisition which gives access to an
* args object for use in executing the final command.
*
* <p>The majority of the functions in this class are called in sequence by the
* constructor. Their task is to add to <tt>hints</tt> fill out the requisition.
* <p>The general sequence is:<ul>
* <li>_tokenize(): convert _typed into _parts
* <li>_split(): convert _parts into _command and _unparsedArgs
* <li>_assign(): convert _unparsedArgs into requisition
* </ul>
*
* @param typed {string} The instruction as typed by the user so far
* @param options {object} A list of optional named parameters. Can be any of:
* <b>flags</b>: Flags for us to check against the predicates specified with the
* commands. Defaulted to <tt>keyboard.buildFlags({ });</tt>
* if not specified.
* @constructor
*/
function CliRequisition(env, options) {
Requisition.call(this, env);
if (options && options.flags) {
/**
* TODO: We were using a default of keyboard.buildFlags({ });
* This allowed us to have commands that only existed in certain contexts
* - i.e. Javascript specific commands.
*/
this.flags = options.flags;
}
}
oop.inherits(CliRequisition, Requisition);
(function() {
/**
* Called by the UI when ever the user interacts with a command line input
* @param input A structure that details the state of the input field.
* It should look something like: { typed:a, cursor: { start:b, end:c } }
* Where a is the contents of the input field, and b and c are the start
* and end of the cursor/selection respectively.
*/
CliRequisition.prototype.update = function(input) {
this.input = input;
this._hints = [];
var args = this._tokenize(input.typed);
this._split(args);
if (this.commandAssignment.value) {
this._assign(args);
}
this._updateHints();
};
/**
* Return an array of Status scores so we can create a marked up
* version of the command line input.
*/
CliRequisition.prototype.getInputStatusMarkup = function() {
// 'scores' is an array which tells us what chars are errors
// Initialize with everything VALID
var scores = this.toString().split('').map(function(ch) {
return Status.VALID;
});
// For all chars in all hints, check and upgrade the score
this._hints.forEach(function(hint) {
for (var i = hint.start; i <= hint.end; i++) {
if (hint.status > scores[i]) {
scores[i] = hint.status;
}
}
}, this);
return scores;
};
/**
* Reconstitute the input from the args
*/
CliRequisition.prototype.toString = function() {
return this.getAssignments(true).map(function(assignment) {
return assignment.toString();
}, this).join('');
};
var superUpdateHints = CliRequisition.prototype._updateHints;
/**
* Marks up hints in a number of ways:
* - Makes INCOMPLETE hints that are not near the cursor INVALID since
* they can't be completed by typing
* - Finds the most severe hint, and annotates the array with it
* - Finds the hint to display, and also annotates the array with it
* TODO: I'm wondering if array annotation is evil and we should replace
* this with an object. Need to find out more.
*/
CliRequisition.prototype._updateHints = function() {
superUpdateHints.call(this);
// Not knowing about cursor positioning, the requisition and assignments
// can't know this, but anything they mark as INCOMPLETE is actually
// INVALID unless the cursor is actually inside that argument.
var c = this.input.cursor;
this._hints.forEach(function(hint) {
var startInHint = c.start >= hint.start && c.start <= hint.end;
var endInHint = c.end >= hint.start && c.end <= hint.end;
var inHint = startInHint || endInHint;
if (!inHint && hint.status === Status.INCOMPLETE) {
hint.status = Status.INVALID;
}
}, this);
Hint.sort(this._hints);
};
/**
* Accessor for the hints array.
* While we could just use the hints property, using getHints() is
* preferred for symmetry with Requisition where it needs a function due to
* lack of an atomic update system.
*/
CliRequisition.prototype.getHints = function() {
return this._hints;
};
/**
* Look through the arguments attached to our assignments for the assignment
* at the given position.
*/
CliRequisition.prototype.getAssignmentAt = function(position) {
var assignments = this.getAssignments(true);
for (var i = 0; i < assignments.length; i++) {
var assignment = assignments[i];
if (!assignment.arg) {
// There is no argument in this assignment, we've fallen off
// the end of the obvious answers - it must be this one.
return assignment;
}
if (assignment.isPositionCaptured(position)) {
return assignment;
}
}
return assignment;
};
/**
* Split up the input taking into account ' and "
*/
CliRequisition.prototype._tokenize = function(typed) {
// For blank input, place a dummy empty argument into the list
if (typed == null || typed.length === 0) {
return [ new Argument(this, '', 0, 0, '', '') ];
}
var OUTSIDE = 1; // The last character was whitespace
var IN_SIMPLE = 2; // The last character was part of a parameter
var IN_SINGLE_Q = 3; // We're inside a single quote: '
var IN_DOUBLE_Q = 4; // We're inside double quotes: "
var mode = OUTSIDE;
// First we un-escape. This list was taken from:
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Unicode
// We are generally converting to their real values except for \', \"
// and '\ ' which we are converting to unicode private characters so we
// can distinguish them from ', " and ' ', which have special meaning.
// They need swapping back post-split - see unescape2()
typed = typed
.replace(/\\\\/g, '\\')
.replace(/\\b/g, '\b')
.replace(/\\f/g, '\f')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\t/g, '\t')
.replace(/\\v/g, '\v')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\ /g, '\uF000')
.replace(/\\'/g, '\uF001')
.replace(/\\"/g, '\uF002');
function unescape2(str) {
return str
.replace(/\uF000/g, ' ')
.replace(/\uF001/g, '\'')
.replace(/\uF002/g, '"');
}
var i = 0;
var start = 0; // Where did this section start?
var prefix = '';
var args = [];
while (true) {
if (i >= typed.length) {
// There is nothing else to read - tidy up
if (mode !== OUTSIDE) {
var str = unescape2(typed.substring(start, i));
args.push(new Argument(this, str, start, i, prefix, ''));
}
else {
if (i !== start) {
// There's a bunch of whitespace at the end of the
// command add it to the last argument's suffix,
// creating an empty argument if needed.
var extra = typed.substring(start, i);
var lastArg = args[args.length - 1];
if (!lastArg) {
lastArg = new Argument(this, '', i, i, extra, '');
args.push(lastArg);
}
else {
lastArg.suffix += extra;
}
}
}
break;
}
var c = typed[i];
switch (mode) {
case OUTSIDE:
if (c === '\'') {
prefix = typed.substring(start, i + 1);
mode = IN_SINGLE_Q;
start = i + 1;
}
else if (c === '"') {
prefix = typed.substring(start, i + 1);
mode = IN_DOUBLE_Q;
start = i + 1;
}
else if (/ /.test(c)) {
// Still whitespace, do nothing
}
else {
prefix = typed.substring(start, i);
mode = IN_SIMPLE;
start = i;
}
break;
case IN_SIMPLE:
// There is an edge case of xx'xx which we are assuming to
// be a single parameter (and same with ")
if (c === ' ') {
var str = unescape2(typed.substring(start, i));
args.push(new Argument(this, str,
start, i, prefix, ''));
mode = OUTSIDE;
start = i;
prefix = '';
}
break;
case IN_SINGLE_Q:
if (c === '\'') {
var str = unescape2(typed.substring(start, i));
args.push(new Argument(this, str,
start - 1, i + 1, prefix, c));
mode = OUTSIDE;
start = i + 1;
prefix = '';
}
break;
case IN_DOUBLE_Q:
if (c === '"') {
var str = unescape2(typed.substring(start, i));
args.push(new Argument(this, str,
start - 1, i + 1, prefix, c));
mode = OUTSIDE;
start = i + 1;
prefix = '';
}
break;
}
i++;
}
return args;
};
/**
* Looks in the canon for a command extension that matches what has been
* typed at the command line.
*/
CliRequisition.prototype._split = function(args) {
var argsUsed = 1;
var arg;
while (argsUsed <= args.length) {
var arg = Argument.merge(args, 0, argsUsed);
this.commandAssignment.setArgument(arg);
if (!this.commandAssignment.value) {
// Not found. break with value == null
break;
}
/*
// Previously we needed a way to hide commands depending context.
// We have not resurrected that feature yet.
if (!keyboard.flagsMatch(command.predicates, this.flags)) {
// If the predicates say 'no match' then go LA LA LA
command = null;
break;
}
*/
if (this.commandAssignment.value.exec) {
// Valid command, break with command valid
for (var i = 0; i < argsUsed; i++) {
args.shift();
}
break;
}
argsUsed++;
}
};
/**
* Work out which arguments are applicable to which parameters.
* <p>This takes #_command.params and #_unparsedArgs and creates a map of
* param names to 'assignment' objects, which have the following properties:
* <ul>
* <li>param - The matching parameter.
* <li>index - Zero based index into where the match came from on the input
* <li>value - The matching input
* </ul>
*/
CliRequisition.prototype._assign = function(args) {
if (args.length === 0) {
this.setDefaultValues();
return;
}
// Create an error if the command does not take parameters, but we have
// been given them ...
if (this.assignmentCount === 0) {
// TODO: previously we were doing some extra work to avoid this if
// we determined that we had args that were all whitespace, but
// probably given our tighter tokenize() this won't be an issue?
this._hints.push(new Hint(Status.INVALID,
this.commandAssignment.value.name +
' does not take any parameters',
Argument.merge(args)));
return;
}
// Special case: if there is only 1 parameter, and that's of type
// text we put all the params into the first param
if (this.assignmentCount === 1) {
var assignment = this.getAssignment(0);
if (assignment.param.type.name === 'text') {
assignment.setArgument(Argument.merge(args));
return;
}
}
var assignments = this.cloneAssignments();
var names = this.getParameterNames();
// Extract all the named parameters
var used = [];
assignments.forEach(function(assignment) {
var namedArgText = '--' + assignment.name;
var i = 0;
while (true) {
var arg = args[i];
if (namedArgText !== arg.text) {
i++;
if (i >= args.length) {
break;
}
continue;
}
// boolean parameters don't have values, default to false
if (assignment.param.type.name === 'boolean') {
assignment.setValue(true);
}
else {
if (i + 1 < args.length) {
// Missing value portion of this named param
this._hints.push(new Hint(Status.INCOMPLETE,
'Missing value for: ' + namedArgText,
args[i]));
}
else {
args.splice(i + 1, 1);
assignment.setArgument(args[i + 1]);
}
}
lang.arrayRemove(names, assignment.name);
args.splice(i, 1);
// We don't need to i++ if we splice
}
}, this);
// What's left are positional parameters assign in order
names.forEach(function(name) {
var assignment = this.getAssignment(name);
if (args.length === 0) {
// No more values
assignment.setValue(undefined); // i.e. default
}
else {
var arg = args[0];
args.splice(0, 1);
assignment.setArgument(arg);
}
}, this);
if (args.length > 0) {
var remaining = Argument.merge(args);
this._hints.push(new Hint(Status.INVALID,
'Input \'' + remaining.text + '\' makes no sense.',
remaining));
}
};
})();
exports.CliRequisition = CliRequisition;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/ui/settings', ['require', 'exports', 'module' , 'pilot/types', 'pilot/types/basic'], function(require, exports, module) {
var types = require("pilot/types");
var SelectionType = require('pilot/types/basic').SelectionType;
var direction = new SelectionType({
name: 'direction',
data: [ 'above', 'below' ]
});
var hintDirectionSetting = {
name: "hintDirection",
description: "Are hints shown above or below the command line?",
type: "direction",
defaultValue: "above"
};
var outputDirectionSetting = {
name: "outputDirection",
description: "Is the output window shown above or below the command line?",
type: "direction",
defaultValue: "above"
};
var outputHeightSetting = {
name: "outputHeight",
description: "What height should the output panel be?",
type: "number",
defaultValue: 300
};
exports.startup = function(data, reason) {
types.registerType(direction);
data.env.settings.addSetting(hintDirectionSetting);
data.env.settings.addSetting(outputDirectionSetting);
data.env.settings.addSetting(outputHeightSetting);
};
exports.shutdown = function(data, reason) {
types.unregisterType(direction);
data.env.settings.removeSetting(hintDirectionSetting);
data.env.settings.removeSetting(outputDirectionSetting);
data.env.settings.removeSetting(outputHeightSetting);
};
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/ui/cli_view', ['require', 'exports', 'module' , 'text!cockpit/ui/cli_view.css', 'pilot/event', 'pilot/dom', 'pilot/keys', 'pilot/canon', 'pilot/types', 'cockpit/cli', 'cockpit/ui/request_view'], function(require, exports, module) {
var editorCss = require("text!cockpit/ui/cli_view.css");
var event = require("pilot/event");
var dom = require("pilot/dom");
dom.importCssString(editorCss);
var event = require("pilot/event");
var keys = require("pilot/keys");
var canon = require("pilot/canon");
var Status = require('pilot/types').Status;
var CliRequisition = require('cockpit/cli').CliRequisition;
var Hint = require('cockpit/cli').Hint;
var RequestView = require('cockpit/ui/request_view').RequestView;
var NO_HINT = new Hint(Status.VALID, '', 0, 0);
/**
* On startup we need to:
* 1. Add 3 sets of elements to the DOM for:
* - command line output
* - input hints
* - completion
* 2. Attach a set of events so the command line works
*/
exports.startup = function(data, reason) {
var cli = new CliRequisition(data.env);
var cliView = new CliView(cli, data.env);
data.env.cli = cli;
};
/**
* A class to handle the simplest UI implementation
*/
function CliView(cli, env) {
cli.cliView = this;
this.cli = cli;
this.doc = document;
this.win = dom.getParentWindow(this.doc);
this.env = env;
// TODO: we should have a better way to specify command lines???
this.element = this.doc.getElementById('cockpitInput');
if (!this.element) {
// console.log('No element with an id of cockpit. Bailing on cli');
return;
}
this.settings = env.settings;
this.hintDirection = this.settings.getSetting('hintDirection');
this.outputDirection = this.settings.getSetting('outputDirection');
this.outputHeight = this.settings.getSetting('outputHeight');
// If the requisition tells us something has changed, we use this to know
// if we should ignore it
this.isUpdating = false;
this.createElements();
this.update();
}
CliView.prototype = {
/**
* Create divs for completion, hints and output
*/
createElements: function() {
var input = this.element;
this.element.spellcheck = false;
this.output = this.doc.getElementById('cockpitOutput');
this.popupOutput = (this.output == null);
if (!this.output) {
this.output = this.doc.createElement('div');
this.output.id = 'cockpitOutput';
this.output.className = 'cptOutput';
input.parentNode.insertBefore(this.output, input.nextSibling);
var setMaxOutputHeight = function() {
this.output.style.maxHeight = this.outputHeight.get() + 'px';
}.bind(this);
this.outputHeight.addEventListener('change', setMaxOutputHeight);
setMaxOutputHeight();
}
this.completer = this.doc.createElement('div');
this.completer.className = 'cptCompletion VALID';
this.completer.style.color = dom.computedStyle(input, "color");
this.completer.style.fontSize = dom.computedStyle(input, "fontSize");
this.completer.style.fontFamily = dom.computedStyle(input, "fontFamily");
this.completer.style.fontWeight = dom.computedStyle(input, "fontWeight");
this.completer.style.fontStyle = dom.computedStyle(input, "fontStyle");
input.parentNode.insertBefore(this.completer, input.nextSibling);
// Transfer background styling to the completer.
this.completer.style.backgroundColor = input.style.backgroundColor;
input.style.backgroundColor = 'transparent';
this.hinter = this.doc.createElement('div');
this.hinter.className = 'cptHints';
input.parentNode.insertBefore(this.hinter, input.nextSibling);
var resizer = this.resizer.bind(this);
event.addListener(this.win, 'resize', resizer);
this.hintDirection.addEventListener('change', resizer);
this.outputDirection.addEventListener('change', resizer);
resizer();
canon.addEventListener('output', function(ev) {
new RequestView(ev.request, this);
}.bind(this));
event.addCommandKeyListener(input, this.onCommandKey.bind(this));
event.addListener(input, 'keyup', this.onKeyUp.bind(this));
// cursor position affects hint severity. TODO: shortcuts for speed
event.addListener(input, 'mouseup', function(ev) {
this.isUpdating = true;
this.update();
this.isUpdating = false;
}.bind(this));
this.cli.addEventListener('argumentChange', this.onArgChange.bind(this));
event.addListener(input, "focus", function() {
dom.addCssClass(this.output, "cptFocusPopup");
dom.addCssClass(this.hinter, "cptFocusPopup");
}.bind(this));
function hideOutput() {
dom.removeCssClass(this.output, "cptFocusPopup");
dom.removeCssClass(this.hinter, "cptFocusPopup");
};
event.addListener(input, "blur", hideOutput.bind(this));
hideOutput.call(this);
},
/**
* We need to see the output of the latest command entered
*/
scrollOutputToBottom: function() {
// Certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(this.output.scrollHeight, this.output.clientHeight);
this.output.scrollTop = scrollHeight - this.output.clientHeight;
},
/**
* To be called on window resize or any time we want to align the elements
* with the input box.
*/
resizer: function() {
var rect = this.element.getClientRects()[0];
this.completer.style.top = rect.top + 'px';
var height = rect.bottom - rect.top;
this.completer.style.height = height + 'px';
this.completer.style.lineHeight = height + 'px';
this.completer.style.left = rect.left + 'px';
var width = rect.right - rect.left;
this.completer.style.width = width + 'px';
if (this.hintDirection.get() === 'below') {
this.hinter.style.top = rect.bottom + 'px';
this.hinter.style.bottom = 'auto';
}
else {
this.hinter.style.top = 'auto';
this.hinter.style.bottom = (this.doc.documentElement.clientHeight - rect.top) + 'px';
}
this.hinter.style.left = (rect.left + 30) + 'px';
this.hinter.style.maxWidth = (width - 110) + 'px';
if (this.popupOutput) {
if (this.outputDirection.get() === 'below') {
this.output.style.top = rect.bottom + 'px';
this.output.style.bottom = 'auto';
}
else {
this.output.style.top = 'auto';
this.output.style.bottom = (this.doc.documentElement.clientHeight - rect.top) + 'px';
}
this.output.style.left = rect.left + 'px';
this.output.style.width = (width - 80) + 'px';
}
},
/**
* Ensure that TAB isn't handled by the browser
*/
onCommandKey: function(ev, hashId, keyCode) {
var stopEvent;
if (keyCode === keys.TAB ||
keyCode === keys.UP ||
keyCode === keys.DOWN) {
stopEvent = true;
} else if (hashId != 0 || keyCode != 0) {
stopEvent = canon.execKeyCommand(this.env, 'cli', hashId, keyCode);
}
stopEvent && event.stopEvent(ev);
},
/**
* The main keyboard processing loop
*/
onKeyUp: function(ev) {
var handled;
/*
var handled = keyboardManager.processKeyEvent(ev, this, {
isCommandLine: true, isKeyUp: true
});
*/
// RETURN does a special exec/highlight thing
if (ev.keyCode === keys.RETURN) {
var worst = this.cli.getWorstHint();
// Deny RETURN unless the command might work
if (worst.status === Status.VALID) {
this.cli.exec();
this.element.value = '';
}
else {
// If we've denied RETURN because the command was not VALID,
// select the part of the command line that is causing problems
// TODO: if there are 2 errors are we picking the right one?
dom.setSelectionStart(this.element, worst.start);
dom.setSelectionEnd(this.element, worst.end);
}
}
this.update();
// Special actions which delegate to the assignment
var current = this.cli.getAssignmentAt(dom.getSelectionStart(this.element));
if (current) {
// TAB does a special complete thing
if (ev.keyCode === keys.TAB) {
current.complete();
this.update();
}
// UP/DOWN look for some history
if (ev.keyCode === keys.UP) {
current.increment();
this.update();
}
if (ev.keyCode === keys.DOWN) {
current.decrement();
this.update();
}
}
return handled;
},
/**
* Actually parse the input and make sure we're all up to date
*/
update: function() {
this.isUpdating = true;
var input = {
typed: this.element.value,
cursor: {
start: dom.getSelectionStart(this.element),
end: dom.getSelectionEnd(this.element.selectionEnd)
}
};
this.cli.update(input);
var display = this.cli.getAssignmentAt(input.cursor.start).getHint();
// 1. Update the completer with prompt/error marker/TAB info
dom.removeCssClass(this.completer, Status.VALID.toString());
dom.removeCssClass(this.completer, Status.INCOMPLETE.toString());
dom.removeCssClass(this.completer, Status.INVALID.toString());
var completion = '<span class="cptPrompt">></span> ';
if (this.element.value.length > 0) {
var scores = this.cli.getInputStatusMarkup();
completion += this.markupStatusScore(scores);
}
// Display the "-> prediction" at the end of the completer
if (this.element.value.length > 0 &&
display.predictions && display.predictions.length > 0) {
var tab = display.predictions[0];
completion += ' ⇥ ' + (tab.name ? tab.name : tab);
}
this.completer.innerHTML = completion;
dom.addCssClass(this.completer, this.cli.getWorstHint().status.toString());
// 2. Update the hint element
var hint = '';
if (this.element.value.length !== 0) {
hint += display.message;
if (display.predictions && display.predictions.length > 0) {
hint += ': [ ';
display.predictions.forEach(function(prediction) {
hint += (prediction.name ? prediction.name : prediction);
hint += ' | ';
}, this);
hint = hint.replace(/\| $/, ']');
}
}
this.hinter.innerHTML = hint;
if (hint.length === 0) {
dom.addCssClass(this.hinter, 'cptNoPopup');
}
else {
dom.removeCssClass(this.hinter, 'cptNoPopup');
}
this.isUpdating = false;
},
/**
* Markup an array of Status values with spans
*/
markupStatusScore: function(scores) {
var completion = '';
// Create mark-up
var i = 0;
var lastStatus = -1;
while (true) {
if (lastStatus !== scores[i]) {
completion += '<span class=' + scores[i].toString() + '>';
lastStatus = scores[i];
}
completion += this.element.value[i];
i++;
if (i === this.element.value.length) {
completion += '</span>';
break;
}
if (lastStatus !== scores[i]) {
completion += '</span>';
}
}
return completion;
},
/**
* Update the input element to reflect the changed argument
*/
onArgChange: function(ev) {
if (this.isUpdating) {
return;
}
var prefix = this.element.value.substring(0, ev.argument.start);
var suffix = this.element.value.substring(ev.argument.end);
var insert = typeof ev.text === 'string' ? ev.text : ev.text.name;
this.element.value = prefix + insert + suffix;
// Fix the cursor.
var insertEnd = (prefix + insert).length;
this.element.selectionStart = insertEnd;
this.element.selectionEnd = insertEnd;
}
};
exports.CliView = CliView;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/ui/request_view', ['require', 'exports', 'module' , 'pilot/dom', 'pilot/event', 'text!cockpit/ui/request_view.html', 'pilot/domtemplate', 'text!cockpit/ui/request_view.css'], function(require, exports, module) {
var dom = require("pilot/dom");
var event = require("pilot/event");
var requestViewHtml = require("text!cockpit/ui/request_view.html");
var Templater = require("pilot/domtemplate").Templater;
var requestViewCss = require("text!cockpit/ui/request_view.css");
dom.importCssString(requestViewCss);
/**
* Pull the HTML into the DOM, but don't add it to the document
*/
var templates = document.createElement('div');
templates.innerHTML = requestViewHtml;
var row = templates.querySelector('.cptRow');
/**
* Work out the path for images.
* TODO: This should probably live in some utility area somewhere
*/
function imageUrl(path) {
var dataUrl;
try {
dataUrl = require('text!cockpit/ui/' + path);
} catch (e) { }
if (dataUrl) {
return dataUrl;
}
var filename = module.id.split('/').pop() + '.js';
var imagePath;
if (module.uri.substr(-filename.length) !== filename) {
console.error('Can\'t work out path from module.uri/module.id');
return path;
}
if (module.uri) {
var end = module.uri.length - filename.length - 1;
return module.uri.substr(0, end) + "/" + path;
}
return filename + path;
}
/**
* Adds a row to the CLI output display
*/
function RequestView(request, cliView) {
this.request = request;
this.cliView = cliView;
this.imageUrl = imageUrl;
// Elements attached to this by the templater. For info only
this.rowin = null;
this.rowout = null;
this.output = null;
this.hide = null;
this.show = null;
this.duration = null;
this.throb = null;
new Templater().processNode(row.cloneNode(true), this);
this.cliView.output.appendChild(this.rowin);
this.cliView.output.appendChild(this.rowout);
this.request.addEventListener('output', this.onRequestChange.bind(this));
};
RequestView.prototype = {
/**
* A single click on an invocation line in the console copies the command to
* the command line
*/
copyToInput: function() {
this.cliView.element.value = this.request.typed;
},
/**
* A double click on an invocation line in the console executes the command
*/
executeRequest: function(ev) {
this.cliView.cli.update({
typed: this.request.typed,
cursor: { start:0, end:0 }
});
this.cliView.cli.exec();
},
hideOutput: function(ev) {
this.output.style.display = 'none';
dom.addCssClass(this.hide, 'cmd_hidden');
dom.removeCssClass(this.show, 'cmd_hidden');
event.stopPropagation(ev);
},
showOutput: function(ev) {
this.output.style.display = 'block';
dom.removeCssClass(this.hide, 'cmd_hidden');
dom.addCssClass(this.show, 'cmd_hidden');
event.stopPropagation(ev);
},
remove: function(ev) {
this.cliView.output.removeChild(this.rowin);
this.cliView.output.removeChild(this.rowout);
event.stopPropagation(ev);
},
onRequestChange: function(ev) {
this.duration.innerHTML = this.request.duration ?
'completed in ' + (this.request.duration / 1000) + ' sec ' :
'';
this.output.innerHTML = '';
this.request.outputs.forEach(function(output) {
var node;
if (typeof output == 'string') {
node = document.createElement('p');
node.innerHTML = output;
} else {
node = output;
}
this.output.appendChild(node);
}, this);
this.cliView.scrollOutputToBottom();
dom.setCssClass(this.output, 'cmd_error', this.request.error);
this.throb.style.display = this.request.completed ? 'none' : 'block';
}
};
exports.RequestView = RequestView;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is DomTemplate.
*
* The Initial Developer of the Original Code is Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com) (original author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('pilot/domtemplate', ['require', 'exports', 'module' ], function(require, exports, module) {
// WARNING: do not 'use_strict' without reading the notes in envEval;
/**
* A templater that allows one to quickly template DOM nodes.
*/
function Templater() {
this.scope = [];
};
/**
* Recursive function to walk the tree processing the attributes as it goes.
* @param node the node to process. If you pass a string in instead of a DOM
* element, it is assumed to be an id for use with document.getElementById()
* @param data the data to use for node processing.
*/
Templater.prototype.processNode = function(node, data) {
if (typeof node === 'string') {
node = document.getElementById(node);
}
if (data === null || data === undefined) {
data = {};
}
this.scope.push(node.nodeName + (node.id ? '#' + node.id : ''));
try {
// Process attributes
if (node.attributes && node.attributes.length) {
// We need to handle 'foreach' and 'if' first because they might stop
// some types of processing from happening, and foreach must come first
// because it defines new data on which 'if' might depend.
if (node.hasAttribute('foreach')) {
this.processForEach(node, data);
return;
}
if (node.hasAttribute('if')) {
if (!this.processIf(node, data)) {
return;
}
}
// Only make the node available once we know it's not going away
data.__element = node;
// It's good to clean up the attributes when we've processed them,
// but if we do it straight away, we mess up the array index
var attrs = Array.prototype.slice.call(node.attributes);
for (var i = 0; i < attrs.length; i++) {
var value = attrs[i].value;
var name = attrs[i].name;
this.scope.push(name);
try {
if (name === 'save') {
// Save attributes are a setter using the node
value = this.stripBraces(value);
this.property(value, data, node);
node.removeAttribute('save');
} else if (name.substring(0, 2) === 'on') {
// Event registration relies on property doing a bind
value = this.stripBraces(value);
var func = this.property(value, data);
if (typeof func !== 'function') {
this.handleError('Expected ' + value +
' to resolve to a function, but got ' + typeof func);
}
node.removeAttribute(name);
var capture = node.hasAttribute('capture' + name.substring(2));
node.addEventListener(name.substring(2), func, capture);
if (capture) {
node.removeAttribute('capture' + name.substring(2));
}
} else {
// Replace references in all other attributes
var self = this;
var newValue = value.replace(/\$\{[^}]*\}/g, function(path) {
return self.envEval(path.slice(2, -1), data, value);
});
// Remove '_' prefix of attribute names so the DOM won't try
// to use them before we've processed the template
if (name.charAt(0) === '_') {
node.removeAttribute(name);
node.setAttribute(name.substring(1), newValue);
} else if (value !== newValue) {
attrs[i].value = newValue;
}
}
} finally {
this.scope.pop();
}
}
}
// Loop through our children calling processNode. First clone them, so the
// set of nodes that we visit will be unaffected by additions or removals.
var childNodes = Array.prototype.slice.call(node.childNodes);
for (var j = 0; j < childNodes.length; j++) {
this.processNode(childNodes[j], data);
}
if (node.nodeType === Node.TEXT_NODE) {
this.processTextNode(node, data);
}
} finally {
this.scope.pop();
}
};
/**
* Handle <x if="${...}">
* @param node An element with an 'if' attribute
* @param data The data to use with envEval
* @returns true if processing should continue, false otherwise
*/
Templater.prototype.processIf = function(node, data) {
this.scope.push('if');
try {
var originalValue = node.getAttribute('if');
var value = this.stripBraces(originalValue);
var recurse = true;
try {
var reply = this.envEval(value, data, originalValue);
recurse = !!reply;
} catch (ex) {
this.handleError('Error with \'' + value + '\'', ex);
recurse = false;
}
if (!recurse) {
node.parentNode.removeChild(node);
}
node.removeAttribute('if');
return recurse;
} finally {
this.scope.pop();
}
};
/**
* Handle <x foreach="param in ${array}"> and the special case of
* <loop foreach="param in ${array}">
* @param node An element with a 'foreach' attribute
* @param data The data to use with envEval
*/
Templater.prototype.processForEach = function(node, data) {
this.scope.push('foreach');
try {
var originalValue = node.getAttribute('foreach');
var value = originalValue;
var paramName = 'param';
if (value.charAt(0) === '$') {
// No custom loop variable name. Use the default: 'param'
value = this.stripBraces(value);
} else {
// Extract the loop variable name from 'NAME in ${ARRAY}'
var nameArr = value.split(' in ');
paramName = nameArr[0].trim();
value = this.stripBraces(nameArr[1].trim());
}
node.removeAttribute('foreach');
try {
var self = this;
// Process a single iteration of a loop
var processSingle = function(member, clone, ref) {
ref.parentNode.insertBefore(clone, ref);
data[paramName] = member;
self.processNode(clone, data);
delete data[paramName];
};
// processSingle is no good for <loop> nodes where we want to work on
// the childNodes rather than the node itself
var processAll = function(scope, member) {
self.scope.push(scope);
try {
if (node.nodeName === 'LOOP') {
for (var i = 0; i < node.childNodes.length; i++) {
var clone = node.childNodes[i].cloneNode(true);
processSingle(member, clone, node);
}
} else {
var clone = node.cloneNode(true);
clone.removeAttribute('foreach');
processSingle(member, clone, node);
}
} finally {
self.scope.pop();
}
};
var reply = this.envEval(value, data, originalValue);
if (Array.isArray(reply)) {
reply.forEach(function(data, i) {
processAll('' + i, data);
}, this);
} else {
for (var param in reply) {
if (reply.hasOwnProperty(param)) {
processAll(param, param);
}
}
}
node.parentNode.removeChild(node);
} catch (ex) {
this.handleError('Error with \'' + value + '\'', ex);
}
} finally {
this.scope.pop();
}
};
/**
* Take a text node and replace it with another text node with the ${...}
* sections parsed out. We replace the node by altering node.parentNode but
* we could probably use a DOM Text API to achieve the same thing.
* @param node The Text node to work on
* @param data The data to use in calls to envEval
*/
Templater.prototype.processTextNode = function(node, data) {
// Replace references in other attributes
var value = node.data;
// We can't use the string.replace() with function trick (see generic
// attribute processing in processNode()) because we need to support
// functions that return DOM nodes, so we can't have the conversion to a
// string.
// Instead we process the string as an array of parts. In order to split
// the string up, we first replace '${' with '\uF001$' and '}' with '\uF002'
// We can then split using \uF001 or \uF002 to get an array of strings
// where scripts are prefixed with $.
// \uF001 and \uF002 are just unicode chars reserved for private use.
value = value.replace(/\$\{([^}]*)\}/g, '\uF001$$$1\uF002');
var parts = value.split(/\uF001|\uF002/);
if (parts.length > 1) {
parts.forEach(function(part) {
if (part === null || part === undefined || part === '') {
return;
}
if (part.charAt(0) === '$') {
part = this.envEval(part.slice(1), data, node.data);
}
// It looks like this was done a few lines above but see envEval
if (part === null) {
part = "null";
}
if (part === undefined) {
part = "undefined";
}
// if (isDOMElement(part)) { ... }
if (typeof part.cloneNode !== 'function') {
part = node.ownerDocument.createTextNode(part.toString());
}
node.parentNode.insertBefore(part, node);
}, this);
node.parentNode.removeChild(node);
}
};
/**
* Warn of string does not begin '${' and end '}'
* @param str the string to check.
* @return The string stripped of ${ and }, or untouched if it does not match
*/
Templater.prototype.stripBraces = function(str) {
if (!str.match(/\$\{.*\}/g)) {
this.handleError('Expected ' + str + ' to match ${...}');
return str;
}
return str.slice(2, -1);
};
/**
* Combined getter and setter that works with a path through some data set.
* For example:
* <ul>
* <li>property('a.b', { a: { b: 99 }}); // returns 99
* <li>property('a', { a: { b: 99 }}); // returns { b: 99 }
* <li>property('a', { a: { b: 99 }}, 42); // returns 99 and alters the
* input data to be { a: { b: 42 }}
* </ul>
* @param path An array of strings indicating the path through the data, or
* a string to be cut into an array using <tt>split('.')</tt>
* @param data An object to look in for the <tt>path</tt> argument
* @param newValue (optional) If defined, this value will replace the
* original value for the data at the path specified.
* @return The value pointed to by <tt>path</tt> before any
* <tt>newValue</tt> is applied.
*/
Templater.prototype.property = function(path, data, newValue) {
this.scope.push(path);
try {
if (typeof path === 'string') {
path = path.split('.');
}
var value = data[path[0]];
if (path.length === 1) {
if (newValue !== undefined) {
data[path[0]] = newValue;
}
if (typeof value === 'function') {
return function() {
return value.apply(data, arguments);
};
}
return value;
}
if (!value) {
this.handleError('Can\'t find path=' + path);
return null;
}
return this.property(path.slice(1), value, newValue);
} finally {
this.scope.pop();
}
};
/**
* Like eval, but that creates a context of the variables in <tt>env</tt> in
* which the script is evaluated.
* WARNING: This script uses 'with' which is generally regarded to be evil.
* The alternative is to create a Function at runtime that takes X parameters
* according to the X keys in the env object, and then call that function using
* the values in the env object. This is likely to be slow, but workable.
* @param script The string to be evaluated.
* @param env The environment in which to eval the script.
* @param context Optional debugging string in case of failure
* @return The return value of the script, or the error message if the script
* execution failed.
*/
Templater.prototype.envEval = function(script, env, context) {
with (env) {
try {
this.scope.push(context);
return eval(script);
} catch (ex) {
this.handleError('Template error evaluating \'' + script + '\'', ex);
return script;
} finally {
this.scope.pop();
}
}
};
/**
* A generic way of reporting errors, for easy overloading in different
* environments.
* @param message the error message to report.
* @param ex optional associated exception.
*/
Templater.prototype.handleError = function(message, ex) {
this.logError(message);
this.logError('In: ' + this.scope.join(' > '));
if (ex) {
this.logError(ex);
}
};
/**
* A generic way of reporting errors, for easy overloading in different
* environments.
* @param message the error message to report.
*/
Templater.prototype.logError = function(message) {
window.console && window.console.log && console.log(message);
};
exports.Templater = Templater;
});
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Skywriter Team (skywriter@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('cockpit/commands/basic', ['require', 'exports', 'module' , 'pilot/canon'], function(require, exports, module) {
var canon = require('pilot/canon');
/**
* '!' command
*/
var bangCommandSpec = {
name: 'sh',
description: 'Execute a system command (requires server support)',
params: [
{
name: 'command',
type: 'text',
description: 'The string to send to the os shell.'
}
],
exec: function(env, args, request) {
var req = new XMLHttpRequest();
req.open('GET', '/exec?args=' + args.command, true);
req.onreadystatechange = function(ev) {
if (req.readyState == 4) {
if (req.status == 200) {
request.done('<pre>' + req.responseText + '</pre>');
}
}
};
req.send(null);
}
};
var canon = require('pilot/canon');
exports.startup = function(data, reason) {
canon.addCommand(bangCommandSpec);
};
exports.shutdown = function(data, reason) {
canon.removeCommand(bangCommandSpec);
};
});
define("text!cockpit/ui/cli_view.css", [], "" +
"#cockpitInput { padding-left: 16px; }" +
"" +
".cptOutput { overflow: auto; position: absolute; z-index: 999; display: none; }" +
"" +
".cptCompletion { padding: 0; position: absolute; z-index: -1000; }" +
".cptCompletion.VALID { background: #FFF; }" +
".cptCompletion.INCOMPLETE { background: #DDD; }" +
".cptCompletion.INVALID { background: #DDD; }" +
".cptCompletion span { color: #FFF; }" +
".cptCompletion span.INCOMPLETE { color: #DDD; border-bottom: 2px dotted #F80; }" +
".cptCompletion span.INVALID { color: #DDD; border-bottom: 2px dotted #F00; }" +
"span.cptPrompt { color: #66F; font-weight: bold; }" +
"" +
"" +
".cptHints {" +
" color: #000;" +
" position: absolute;" +
" border: 1px solid rgba(230, 230, 230, 0.8);" +
" background: rgba(250, 250, 250, 0.8);" +
" -moz-border-radius-topleft: 10px;" +
" -moz-border-radius-topright: 10px;" +
" border-top-left-radius: 10px; border-top-right-radius: 10px;" +
" z-index: 1000;" +
" padding: 8px;" +
" display: none;" +
"}" +
"" +
".cptFocusPopup { display: block; }" +
".cptFocusPopup.cptNoPopup { display: none; }" +
"" +
".cptHints ul { margin: 0; padding: 0 15px; }" +
"" +
".cptGt { font-weight: bold; font-size: 120%; }" +
"");
define("text!cockpit/ui/request_view.css", [], "" +
".cptRowIn {" +
" display: box; display: -moz-box; display: -webkit-box;" +
" box-orient: horizontal; -moz-box-orient: horizontal; -webkit-box-orient: horizontal;" +
" box-align: center; -moz-box-align: center; -webkit-box-align: center;" +
" color: #333;" +
" background-color: #EEE;" +
" width: 100%;" +
" font-family: consolas, courier, monospace;" +
"}" +
".cptRowIn > * { padding-left: 2px; padding-right: 2px; }" +
".cptRowIn > img { cursor: pointer; }" +
".cptHover { display: none; }" +
".cptRowIn:hover > .cptHover { display: block; }" +
".cptRowIn:hover > .cptHover.cptHidden { display: none; }" +
".cptOutTyped {" +
" box-flex: 1; -moz-box-flex: 1; -webkit-box-flex: 1;" +
" font-weight: bold; color: #000; font-size: 120%;" +
"}" +
".cptRowOutput { padding-left: 10px; line-height: 1.2em; }" +
".cptRowOutput strong," +
".cptRowOutput b," +
".cptRowOutput th," +
".cptRowOutput h1," +
".cptRowOutput h2," +
".cptRowOutput h3 { color: #000; }" +
".cptRowOutput a { font-weight: bold; color: #666; text-decoration: none; }" +
".cptRowOutput a: hover { text-decoration: underline; cursor: pointer; }" +
".cptRowOutput input[type=password]," +
".cptRowOutput input[type=text]," +
".cptRowOutput textarea {" +
" color: #000; font-size: 120%;" +
" background: transparent; padding: 3px;" +
" border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px;" +
"}" +
".cptRowOutput table," +
".cptRowOutput td," +
".cptRowOutput th { border: 0; padding: 0 2px; }" +
".cptRowOutput .right { text-align: right; }" +
"");
define("text!cockpit/ui/request_view.html", [], "" +
"<div class=cptRow>" +
" <!-- The div for the input (i.e. what was typed) -->" +
" <div class=\"cptRowIn\" save=\"${rowin}\"" +
" onclick=\"${copyToInput}\"" +
" ondblclick=\"${executeRequest}\">" +
"" +
" <!-- What the user actually typed -->" +
" <div class=\"cptGt\">> </div>" +
" <div class=\"cptOutTyped\">${request.typed}</div>" +
"" +
" <!-- The extra details that appear on hover -->" +
" <div class=cptHover save=\"${duration}\"></div>" +
" <img class=cptHover onclick=\"${hideOutput}\" save=\"${hide}\"" +
" alt=\"Hide command output\" _src=\"${imageUrl('images/minus.png')}\"/>" +
" <img class=\"cptHover cptHidden\" onclick=\"${showOutput}\" save=\"${show}\"" +
" alt=\"Show command output\" _src=\"${imageUrl('images/plus.png')}\"/>" +
" <img class=cptHover onclick=\"${remove}\"" +
" alt=\"Remove this command from the history\"" +
" _src=\"${imageUrl('images/closer.png')}\"/>" +
"" +
" </div>" +
"" +
" <!-- The div for the command output -->" +
" <div class=\"cptRowOut\" save=\"${rowout}\">" +
" <div class=\"cptRowOutput\" save=\"${output}\"></div>" +
" <img _src=\"${imageUrl('images/throbber.gif')}\" save=\"${throb}\"/>" +
" </div>" +
"</div>" +
"");
define("text!cockpit/ui/images/closer.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAj9JREFUeNp0ks+LUlEUx7/vV1o8Z8wUx3IEHcQmiBiQlomjRNCiZpEuEqF/oEUwq/6EhvoHggmRcJUQBM1CRJAW0aLIaGQimZJxJsWxyV/P9/R1zzWlFl04vPvOPZ9z7rnnK5imidmKRCIq+zxgdoPZ1T/ut8xeM3tcKpW6s1hhBkaj0Qj7bDebTX+324WmadxvsVigqipcLleN/d4rFoulORiLxTZY8ItOp8MBCpYkiYPj8Xjus9vtlORWoVB4KcTjcQc732dLpSRXvCZaAws6Q4WDdqsO52kNH+oCRFGEz+f7ydwBKRgMPmTXi49GI1x2D/DsznesB06ws2eDbI7w9HYN6bVjvGss4KAjwDAMq81mM2SW5Wa/3weBbz42UL9uYnVpiO2Nr9ANHSGXib2Wgm9tCYIggGKJEVkvlwgi5/FQRmTLxO6hgJVzI1x0T/fJrBtHJxPeL6tI/fsZLA6ot8lkQi8HRVbw94gkWYI5MaHrOjcCGSNRxZosy9y5cErDzn0Dqx7gcwO8WtBp4PndI35GMYqiUMUvBL5yOBz8yRfFNpbPmqgcCFh/IuHa1nR/YXGM8+oUpFhihEQiwcdRLpfVRqOBtWXWq34Gra6AXq8Hp2piZcmKT4cKnE4nwuHwdByVSmWQz+d32WCTlHG/qaHHREN9kgi0sYQfv0R4PB4EAgESQDKXy72fSy6VSnHJVatVf71eR7vd5n66mtfrRSgU4pLLZrOlf7RKK51Ok8g3/yPyR5lMZi7y3wIMAME4EigHWgKnAAAAAElFTkSuQmCC");
define("text!cockpit/ui/images/dot_clear.gif", [], "data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAEBMgA7");
define("text!cockpit/ui/images/minus.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAAXNSR0IArs4c6QAAAAZiS0dEANIA0gDS7KbF4AAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9kFGw4xMrIJw5EAAAHcSURBVCjPhZIxSxtxGMZ/976XhJA/RA5EAyJcFksnp64hjUPBoXRyCYLQTyD0UxScu0nFwalCQSgFCVk7dXAwUAiBDA2RO4W7yN1x9+9gcyhU+pteHt4H3pfncay1LOl0OgY4BN4Ar/7KP4BvwNFwOIyWu87S2O12O8DxfD73oygiSRIAarUaxhhWV1fHwMFgMBiWxl6v9y6Koi+3t7ckSUKtVkNVAcjzvNRWVlYwxry9vLz86uzs7HjAZDKZGGstjUaDfxHHMSLC5ubmHdB2VfVwNpuZ5clxHPMcRVFwc3PTXFtbO3RFZHexWJCmabnweAaoVqvlv4vFAhHZdVX1ZZqmOI5DURR8fz/lxbp9Yrz+7bD72SfPcwBU1XdF5N5aWy2KgqIoeBzPEnWVLMseYnAcRERdVR27rrsdxzGqyutP6898+GBsNBqo6i9XVS88z9sOggAR4X94noeqXoiIHPm+H9XrdYIgIAxDwjAkTVPCMESzBy3LMprNJr7v34nIkV5dXd2fn59fG2P2siwjSRIqlQrWWlSVJFcqlQqtVot2u40xZu/s7OxnWbl+v98BjkejkT+dTgmCoDxtY2ODra2tMXBweno6fNJVgP39fQN8eKbkH09OTsqS/wHFRdHPfTSfjwAAAABJRU5ErkJggg==");
define("text!cockpit/ui/images/pinaction.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGFVM9rE0EU/jZuqdAiCFprDrJ4kCJJWatoRdQ2/RFiawzbH7ZFkGQzSdZuNuvuJrWliOTi0SreRe2hB/+AHnrwZC9KhVpFKN6rKGKhFy3xzW5MtqXqwM5+8943731vdt8ADXLSNPWABOQNx1KiEWlsfEJq/IgAjqIJQTQlVdvsTiQGQYNz+Xvn2HoPgVtWw3v7d7J3rZrStpoHhP1A4Eea2Sqw7xdxClkSAog836Epx3QI3+PY8uyPOU55eMG1Dys9xFkifEA1Lc5/TbhTzSXTQINIOJT1cVI+nNeLlNcdB2luZsbIEL1PkKa7zO6rYqGcTvYOkL2d9H5Os94+wiHCCxmtP0a4jZ71jNU/4mHhpObEhj0cGDX0+GAVtxqp+DXCFF8QTSeiVHHZLg3xmK79VvJKgnCQOMpkYYBzWkhP10xu+LqHBX0m1xOv4ndWUeF5jxNn3tTd70XaAq8wDh0MGgyaDUhQEEUEYZiwUECGPBoxNLJyPyOrBhuTezJ1JGq7dGJEsUF7Ntw9t1Gk3Tz+KCJxlEO1CJL8Qf4qr8lP5Xn5y1yw2Fb3lK2bmrry4DvF5Zm5Gh7X08jjc01efJXUdpNXR5aseXq8muwaP+xXlzHmgjWPxHOw+/EtX5XMlymMFMXjVfPqS4R1WjE3359sfzs94i7PLrXWc62JizdWm5dn/WpI++6qvJPmVflPXvXx/GfNxGPiKTEmdornIYmXxS7xkthLqwviYG3HCJ2VhinSbZH6JNVgYJq89S9dP1t4vUZ/DPVRlBnM0lSJ93/CKmQ0nbkOb/qP28f8F+T3iuefKAIvbODImbptU3HvEKFlpW5zrgIXv9F98LZua6N+OPwEWDyrFq1SNZ8gvAEcdod6HugpmNOWls05Uocsn5O66cpiUsxQ20NSUtcl12VLFrOZVWLpdtiZ0x1uHKE5QvfEp0plk/qv8RGw/bBS+fmsUtl+ThrWgZf6b8C8/UXAeIuJAAAACXBIWXMAAAsTAAALEwEAmpwYAAAClklEQVQ4EX1TXUhUQRQ+Z3Zmd+9uN1q2P3UpZaEwcikKekkqLKggKHJ96MHe9DmLkCDa9U198Id8kErICmIlRAN96UdE6QdBW/tBA5Uic7E0zN297L17p5mb1zYjD3eYc+d83zlnON8g5xzWNUSEdUBkHTJasRWySPP7fw3hfwkk2GoNsc0vOaJRHo1GV/GiMctkTIJRFlpZli8opK+htmf83gXeG63oteOtra0u25e7TYJIJELb26vYCACTgUe1lXV86BTn745l+MsyHqs53S/Aq4VEUa9Y6ko14eYY4u3AyM3HYwdKU35DZyblGR2+qq6W0X2Nnh07xynnVYpHORx/E1/GvvqaAZUayjMjdM2f/Lgr5E+fV93zR4u3zKCLughsZqKwAzAxaz6dPY6JgjLUF+eSP5OpjmAw2E8DvldHSvJMKPg08aRor1tc4BuALu6mOwGWdQC3mKIqRsC8mKd8wYfD78/earzSYzdMDW9QgKb0Is8CBY1mQXOiaXAHEpMDE5XTJqIq4EiyxUqKlpfkF0pyV1OTAoFAhmTmyCCoDsZNZvIkUjELQpipo0sQqYZAswZHwsEEE10M0pq2SSZY9HqNcDicJcNTpBvQJz40UbSOTh1B8bDpuY0w9Hb3kkn9lPAlBLfhfD39XTtX/blFJqiqrjbkTi63Hbofj2uL4GMsmzFgbDJ/vmMgv/lB4syJ0oXO7d3j++vio6GFsYmD6cHJreWc3/jRVVHhsOYvM8iZ36mtjPDBk/xDZE8CoHlbrlAssbTxDdDJvdb536L7I6S7Vy++6Gi4Xi9BsUthJRaLOYSPz4XALKI4j4iObd/e5UtDKUjZzYyYRyGAJv01Zj8kC5cbs5WY83hQnv0DzCXl+r8APElkq0RU6oMAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/pinin.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGFVM9rE0EU/jZuqdAiCFprDrJ4kCJJWatoRdQ2/RFiawzbH7ZFkGQzSdZuNuvuJrWliOTi0SreRe2hB/+AHnrwZC9KhVpFKN6rKGKhFy3xzW5MtqXqwM5+8943731vdt8ADXLSNPWABOQNx1KiEWlsfEJq/IgAjqIJQTQlVdvsTiQGQYNz+Xvn2HoPgVtWw3v7d7J3rZrStpoHhP1A4Eea2Sqw7xdxClkSAog836Epx3QI3+PY8uyPOU55eMG1Dys9xFkifEA1Lc5/TbhTzSXTQINIOJT1cVI+nNeLlNcdB2luZsbIEL1PkKa7zO6rYqGcTvYOkL2d9H5Os94+wiHCCxmtP0a4jZ71jNU/4mHhpObEhj0cGDX0+GAVtxqp+DXCFF8QTSeiVHHZLg3xmK79VvJKgnCQOMpkYYBzWkhP10xu+LqHBX0m1xOv4ndWUeF5jxNn3tTd70XaAq8wDh0MGgyaDUhQEEUEYZiwUECGPBoxNLJyPyOrBhuTezJ1JGq7dGJEsUF7Ntw9t1Gk3Tz+KCJxlEO1CJL8Qf4qr8lP5Xn5y1yw2Fb3lK2bmrry4DvF5Zm5Gh7X08jjc01efJXUdpNXR5aseXq8muwaP+xXlzHmgjWPxHOw+/EtX5XMlymMFMXjVfPqS4R1WjE3359sfzs94i7PLrXWc62JizdWm5dn/WpI++6qvJPmVflPXvXx/GfNxGPiKTEmdornIYmXxS7xkthLqwviYG3HCJ2VhinSbZH6JNVgYJq89S9dP1t4vUZ/DPVRlBnM0lSJ93/CKmQ0nbkOb/qP28f8F+T3iuefKAIvbODImbptU3HvEKFlpW5zrgIXv9F98LZua6N+OPwEWDyrFq1SNZ8gvAEcdod6HugpmNOWls05Uocsn5O66cpiUsxQ20NSUtcl12VLFrOZVWLpdtiZ0x1uHKE5QvfEp0plk/qv8RGw/bBS+fmsUtl+ThrWgZf6b8C8/UXAeIuJAAAACXBIWXMAAAsTAAALEwEAmpwYAAABZ0lEQVQ4Ea2TPUsDQRCGZ89Eo4FACkULEQs1CH4Uamfjn7GxEYJFIFXgChFsbPwzNnZioREkaiHBQtEiEEiMRm/dZ8OEGAxR4sBxx877Pju7M2estTJIxLrNuVwuMxQEx0ZkzcFHyRtjXt02559RtB2GYanTYzoryOfz+6l4Nbszf2niwffKmpGRo9sVW22mDgqFwp5C2gDMm+P32a3JB1N+n5JifUGeP9JeNxGryPLYjcwMP8rJ07Q9fZltQzyAstOJ2vVu5sKc1ZZkRBrOcKeb+HexPidvkpCN5JUcllZtpZFc5DgBWc5M2eysZuMuofMBSA4NWjx4PUCsXefMlI0QY3ewRg4NWi4ZTQsgrjYXema+e4VqtEMK6KXvu+4B9Bklt90vVKMeD2BI6DOt4rZ/Gk7WyKFBi4fNPIAJY0joM61SCCZ9tI1o0OIB8D+DBIkYaJRbCBH9mZgNt+bb++ufSSF/eX8BYcDeAzuQJVUAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/pinout.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAC7mlDQ1BJQ0MgUHJvZmlsZQAAeAGFVM9rE0EU/jZuqdAiCFprDrJ4kCJJWatoRdQ2/RFiawzbH7ZFkGQzSdZuNuvuJrWliOTi0SreRe2hB/+AHnrwZC9KhVpFKN6rKGKhFy3xzW5MtqXqwM5+8943731vdt8ADXLSNPWABOQNx1KiEWlsfEJq/IgAjqIJQTQlVdvsTiQGQYNz+Xvn2HoPgVtWw3v7d7J3rZrStpoHhP1A4Eea2Sqw7xdxClkSAog836Epx3QI3+PY8uyPOU55eMG1Dys9xFkifEA1Lc5/TbhTzSXTQINIOJT1cVI+nNeLlNcdB2luZsbIEL1PkKa7zO6rYqGcTvYOkL2d9H5Os94+wiHCCxmtP0a4jZ71jNU/4mHhpObEhj0cGDX0+GAVtxqp+DXCFF8QTSeiVHHZLg3xmK79VvJKgnCQOMpkYYBzWkhP10xu+LqHBX0m1xOv4ndWUeF5jxNn3tTd70XaAq8wDh0MGgyaDUhQEEUEYZiwUECGPBoxNLJyPyOrBhuTezJ1JGq7dGJEsUF7Ntw9t1Gk3Tz+KCJxlEO1CJL8Qf4qr8lP5Xn5y1yw2Fb3lK2bmrry4DvF5Zm5Gh7X08jjc01efJXUdpNXR5aseXq8muwaP+xXlzHmgjWPxHOw+/EtX5XMlymMFMXjVfPqS4R1WjE3359sfzs94i7PLrXWc62JizdWm5dn/WpI++6qvJPmVflPXvXx/GfNxGPiKTEmdornIYmXxS7xkthLqwviYG3HCJ2VhinSbZH6JNVgYJq89S9dP1t4vUZ/DPVRlBnM0lSJ93/CKmQ0nbkOb/qP28f8F+T3iuefKAIvbODImbptU3HvEKFlpW5zrgIXv9F98LZua6N+OPwEWDyrFq1SNZ8gvAEcdod6HugpmNOWls05Uocsn5O66cpiUsxQ20NSUtcl12VLFrOZVWLpdtiZ0x1uHKE5QvfEp0plk/qv8RGw/bBS+fmsUtl+ThrWgZf6b8C8/UXAeIuJAAAACXBIWXMAAAsTAAALEwEAmpwYAAACyUlEQVQ4EW1TXUgUURQ+Z3ZmnVV3QV2xJbVSEIowQbAfLQx8McLoYX2qjB58MRSkP3vZppceYhGxgrZaIughlYpE7CHFWiiKyj9II0qxWmwlNh1Xtp2f27mz7GDlZX7uuXO+73zfuXeQMQYIgAyALppgyBtse32stsw86txkHhATn+FbfPfzxnPB+vR3RMJYuTwW6bbB4a6WS5O3Yu2VlXIesDiAamiQNKVlVXfx5I0GJ7DY7p0/+erU4dgeMJIA31WNxZmAgibOreXDqF55sY4SFUURqbi+nkjgwTyAbHhLX8yOLsSM2QRA3JRAAgd4RGPbVhkKEp8qeJ7PFyW3fw++YHtC7CkaD0amqyqihSwlMQQ0wa07IjPVI/vbexreIUrVaQV2D4RMQ/o7m12Mdfx4H3PfB9FNzTR1U2cO0Bi45aV6xNvFBNaoIAfbSiwLlqi9/hR/R3Nrhua+Oqi9TEKiB02C7YXz+Pba4MTDrpbLiMAxNgmXb+HpwVkZdoIrkn9isW7nRw/TZYaagZArAWyhfqsSDL/c9aTx7JUjGZCtYExRqCzAwGblwr6aFQ84nTo6qZ7XCeCVQNckE/KSWolvoQnxeoFFgIh8G/nA+kBAxxuQO5m9eFrwLIGJHgcyM63VFMhRSgNVyJr7og8y1vbTQpH8DIEVgxuYuexw0QECIalq5FYgEmpkgoFYltU/lnrqDz5osirSFpF7lrHAFKSWHYfEs+mY/82UnAStyMlW8sUPsVIciTZgz3jV1ebg0CEOpgPF22s1z1YQYKSXPJ1hbAhR8T26WdLhkuVfAzPR+YO1Ox5n58SmCcF6e3uzAoHA77RkevJdWH/3+f2O9TGf3w3fWQ2Hw5F/13mcsWAT+vv6DK4kFApJ/d3d1k+kJtbCrmxXHS3n8ER6b3CQbAqaEHVra6sGxcXW4SovLx+empxapS//FfwD9kpMJjMMBBAAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/pins.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAQCAYAAABQrvyxAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGYklEQVRIDbVWe0yURxCf/R735o6DO0FBe0RFsaL4iLXGIKa2SY3P6JGa2GpjlJjUV9NosbU++tYUbEnaQIrVaKJBG7WiNFQFUWO1UUEsVg2CAgoeHHLewcH32O58cBdQsX9Y5+7LfrszOzO/2ZnZj1BKgTBiIwVGVvKd49OVVYunDlXn6wdBKh+ogXrv+DOz1melIb+3LM5fNv2XPYE5EHY+L3PJljN5zavHpJjsQNsA/JJEgyC2+WTjy3b0GfoJW8O4aoHtDwiHQrj5lw1LLyyb1bp5zAjJTus9klrVpdD6TqH2ngVO+0dsRJnp06cLIYU4fx7NnRI3bu7UIYOeJ/McnuY88q3k62gc0S4Dgf5qhICQtIXS2lqD7BhSduPk3YfyzXaANhBBJDxYdUqCywB2qS4RdyUuSkTF/VJxcbH5j8N7/75RuFrN3Zh8OS8zqf5m4UpPeenOyP42dbtBeuvVnCdkK1e4PfPouX03mo9se+c33M8wqDk5Ofqed8REUTicQhbySUxp9u3KlMSHTtrFU6Kyn03lz15PPpW25vsZeYSIKyiVURcqeZJOH9lTNZLfnxRjU/uwrjbEUBWsapcSO2Hq4k0VfZg9EzxdDNCEjDxgNqRDme9umz/btwlsHRIEePHgAf73RdnHZ6LTuIUBN7OBQ+c1Fdnp6cZ1BQUdeRuWZi97o3ktDQQkVeFFzqJARd1A5a0Vr7ta6Kp6TZjtZ+NTIOoKF6qDrL7e0QQIUCiqMMKk8Z1Q/SCSKvzocf2B6NEN0SQn/kTO6fKJ0zqjZUlQBSpJ0GjR77w0aoc1Pr6S5/kVJrNpakV5hR+LWKN4t7sLX+p0rx2vqSta64olIulUKUgCSXLWE1R4KPPSj+5vhm2hdDOG+CkQBmhhyyKq6SaFYWTn5bB3QJRNz54AuXKn8TJjhu0Wbv+wNEKQjVhnmKopjo4FxXmetCRnC4F7BhCiCUepqAepRh0TM/gjjzOOSK2NgWZPc05qampRWJHb7dbOffep2ednzLzgczlbrQA6gHYF9BYDh9GY+FjddMweHMscmMuep07gXlMQoqw9ALoYu5MJsak9QmJA2IvAgVmoCRciooyPujJtNCv1uHt3TmK9gegFKrG9kh6oXwZiIEAtBIjORGKNTWR/WeW8XVkbjuJepLAyloM8LmTN//njKZPbraATZaLjCHEww9Ei4FFiPg6Ja5gT6gxYgLgnRDHRQwJXbz2GOw0d4A3K4GXlUtMahJjYVxiYbrwOmxIS10bFnIBOSi6Tl9Jgs0zbOEX18wyEwgLPMrxD1Y4aCK8kmTpgYcpAF27Mzs42Hjx4kA8BICUlJfKArR7LcEvTB1xEC9AoEw9OPagWkVU/D1oesmK6U911zEczMVe01oZjiMggg6ux2Qk379qh4rYKet4GjrhhwEteBgBrH8BssoXEtbHzPpSBRRSpqlNpgAiUoxzHKxLRszoVuggIisxaDQWZqkQvQjAoax3NbDbLLGuUEABNGedXqSyLRupXgDT5JfAGZNLio9B0X8Uiwk4w77MDc1D4yejjWtykPS3DX01UDCY/GPQcVDe0QYT0CIxGFvUorfvBxZsRfVrUuWruMBAb/lXCUofoFNZfzGJtowXOX0vwUSFK4BgyMKm6P6s9wQUZld+jrYyMDC0iIQDaJdG4IyZQfL3RfbFcCBIlRgc+u3CjaTApuZ9KsANgG8PNzHlWWD3tCxd6kafNNiFp5HAalAkkJ0SCV2H3CgOD9Nc/FqrXuyb0Eocvfhq171p5eyuJ1omKJEP5rQGe/FOOnXtq335z8YmvYo9cHb2t8spIb3lVSseZW46FlGY/Sk9P50P2w20UlWJUkUHIushfc5PXGAzCo0PlD2pnpCYfCXga3lu+fPlevEhWrVrFyrN/Orfv87FOW9tlqb2Kc9pV8DzioMk3UNUbXM+8B/ATBr8C8CKdvGXWGD/9sqm3dkxtzA4McMjHMB8D2ftheYXo+qzt3pXvz8/PP/vk+v8537V+yYW87Zu+RZ1ZbrexoKAA/SBpaWn4+aL5w5zGk+/jW59JiMkESW5urpiVlWXENRb1H/Yf2I9txIxz5IdkX3TsraukpsbQjz6090yb4XsAvQoRE0YvJdamtIIbOnRoUVlZ2ftsLVQzIdEXHntsaZdimssVfCpFui109+BnWPsXaWLI/zactygAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/plus.png", [], "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAAXNSR0IArs4c6QAAAAZiS0dEANIA0gDS7KbF4AAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9kFGw4yFTwuJTkAAAH7SURBVCjPdZKxa1NRFMZ/956XZMgFyyMlCZRA4hBx6lBcQ00GoYi4tEstFPwLAs7iLDi7FWuHThaUggihBDI5OWRoQAmBQFISQgvvpbwX3rsOaR4K+o2H8zvfOZxPWWtZqVarGaAJPAEe3ZW/A1+Bd+1221v1qhW4vb1dA44mk0nZ8zyCIAAgk8lgjGF9fb0PHF5cXLQTsF6vP/c879P19TVBEJDJZBARAKIoSmpra2sYY561Wq3PqtFouMBgMBgYay3ZbJZ/yfd9tNaUSqUboOKISPPq6sqsVvZ9H4AvL34B8PTj/QSO45jpdHovn883Ha31znw+JwzDpCEMQx4UloM8zyOdTif3zudztNY7jog8DMMQpRRxHPPt5TCBAEZvxlyOFTsfykRRBICIlB2t9a21Nh3HMXEc8+d7VhJHWCwWyzcohdZaHBHpO46z6fs+IsLj94XECaD4unCHL8FsNouI/HRE5Nx13c3ZbIbWOnG5HKtl+53TSq7rIiLnand31wUGnU7HjEYjlFLJZN/3yRnL1FMYY8jlcmxtbd0AFel2u7dnZ2eXxpi9xWJBEASkUimstYgIQSSkUimKxSKVSgVjzN7p6emPJHL7+/s14KjX65WHwyGz2SxZbWNjg2q12gcOT05O2n9lFeDg4MAAr/4T8rfHx8dJyH8DvvbYGzKvWukAAAAASUVORK5CYII=");
define("text!cockpit/ui/images/throbber.gif", [], "data:image/gif;base64,R0lGODlh3AATAPQAAP///wAAAL6+vqamppycnLi4uLKyssjIyNjY2MTExNTU1Nzc3ODg4OTk5LCwsLy8vOjo6Ozs7MrKyvLy8vT09M7Ozvb29sbGxtDQ0O7u7tbW1sLCwqqqqvj4+KCgoJaWliH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAA3AATAAAF/yAgjmRpnmiqrmzrvnAsz3Rt33iu73zv/8CgcEgECAaEpHLJbDqf0Kh0Sq1ar9isdjoQtAQFg8PwKIMHnLF63N2438f0mv1I2O8buXjvaOPtaHx7fn96goR4hmuId4qDdX95c4+RG4GCBoyAjpmQhZN0YGYFXitdZBIVGAoKoq4CG6Qaswi1CBtkcG6ytrYJubq8vbfAcMK9v7q7D8O1ycrHvsW6zcTKsczNz8HZw9vG3cjTsMIYqQgDLAQGCQoLDA0QCwUHqfYSFw/xEPz88/X38Onr14+Bp4ADCco7eC8hQYMAEe57yNCew4IVBU7EGNDiRn8Z831cGLHhSIgdE/9chIeBgDoB7gjaWUWTlYAFE3LqzDCTlc9WOHfm7PkTqNCh54rePDqB6M+lR536hCpUqs2gVZM+xbrTqtGoWqdy1emValeXKwgcWABB5y1acFNZmEvXwoJ2cGfJrTv3bl69Ffj2xZt3L1+/fw3XRVw4sGDGcR0fJhxZsF3KtBTThZxZ8mLMgC3fRatCLYMIFCzwLEprg84OsDus/tvqdezZf13Hvr2B9Szdu2X3pg18N+68xXn7rh1c+PLksI/Dhe6cuO3ow3NfV92bdArTqC2Ebc3A8vjf5QWf15Bg7Nz17c2fj69+fnq+8N2Lty+fuP78/eV2X13neIcCeBRwxorbZrAxAJoCDHbgoG8RTshahQ9iSKEEzUmYIYfNWViUhheCGJyIP5E4oom7WWjgCeBBAJNv1DVV01MZdJhhjdkplWNzO/5oXI846njjVEIqR2OS2B1pE5PVscajkxhMycqLJgxQCwT40PjfAV4GqNSXYdZXJn5gSkmmmmJu1aZYb14V51do+pTOCmA00AqVB4hG5IJ9PvYnhIFOxmdqhpaI6GeHCtpooisuutmg+Eg62KOMKuqoTaXgicQWoIYq6qiklmoqFV0UoeqqrLbq6quwxirrrLTWauutJ4QAACH5BAkKAAAALAAAAADcABMAAAX/ICCOZGmeaKqubOu+cCzPdG3feK7vfO//wKBwSAQIBoSkcslsOp/QqHRKrVqv2Kx2OhC0BAXHx/EoCzboAcdhcLDdgwJ6nua03YZ8PMFPoBMca215eg98G36IgYNvDgOGh4lqjHd7fXOTjYV9nItvhJaIfYF4jXuIf4CCbHmOBZySdoOtj5eja59wBmYFXitdHhwSFRgKxhobBgUPAmdoyxoI0tPJaM5+u9PaCQZzZ9gP2tPcdM7L4tLVznPn6OQb18nh6NV0fu3i5OvP8/nd1qjwaasHcIPAcf/gBSyAAMMwBANYEAhWYQGDBhAyLihwYJiEjx8fYMxIcsGDAxVA/yYIOZIkBAaGPIK8INJlRpgrPeasaRPmx5QgJfB0abLjz50tSeIM+pFmUo0nQQIV+vRlTJUSnNq0KlXCSq09ozIFexEBAYkeNiwgOaEtn2LFpGEQsKCtXbcSjOmVlqDuhAx3+eg1Jo3u37sZBA9GoMAw4MB5FyMwfLht4sh7G/utPGHlYAV8Nz9OnOBz4c2VFWem/Pivar0aKCP2LFn2XwhnVxBwsPbuBAQbEGiIFg1BggoWkidva5z4cL7IlStfkED48OIYoiufYIH68+cKPkqfnsB58ePjmZd3Dj199/XE20tv6/27XO3S6z9nPCz9BP3FISDefL/Bt192/uWmAv8BFzAQAQUWWFaaBgqA11hbHWTIXWIVXifNhRlq6FqF1sm1QQYhdiAhbNEYc2KKK1pXnAIvhrjhBh0KxxiINlqQAY4UXjdcjSJyeAx2G2BYJJD7NZQkjCPKuCORKnbAIXsuKhlhBxEomAIBBzgIYXIfHfmhAAyMR2ZkHk62gJoWlNlhi33ZJZ2cQiKTJoG05Wjcm3xith9dcOK5X51tLRenoHTuud2iMnaolp3KGXrdBo7eKYF5p/mXgJcogClmcgzAR5gCKymXYqlCgmacdhp2UCqL96mq4nuDBTmgBasaCFp4sHaQHHUsGvNRiiGyep1exyIra2mS7dprrtA5++z/Z8ZKYGuGsy6GqgTIDvupRGE+6CO0x3xI5Y2mOTkBjD4ySeGU79o44mcaSEClhglgsKyJ9S5ZTGY0Bnzrj+3SiKK9Rh5zjAALCywZBk/ayCWO3hYM5Y8Dn6qxxRFsgAGoJwwgDQRtYXAAragyQOmaLKNZKGaEuUlpyiub+ad/KtPqpntypvvnzR30DBtjMhNodK6Eqrl0zU0/GjTUgG43wdN6Ra2pAhGtAAZGE5Ta8TH6wknd2IytNKaiZ+Or79oR/tcvthIcAPe7DGAs9Edwk6r3qWoTaNzY2fb9HuHh2S343Hs1VIHhYtOt+Hh551rh24vP5YvXSGzh+eeghy76GuikU9FFEainrvrqrLfu+uuwxy777LTXfkIIACH5BAkKAAAALAAAAADcABMAAAX/ICCOZGmeaKqubOu+cCzPdG3feK7vfO//wKBwSAQIBoSkcslsOp/QqHRKrVqv2Kx2OhC0BAWHB2l4CDZo9IDjcBja7UEhTV+3DXi3PJFA8xMcbHiDBgMPG31pgHBvg4Z9iYiBjYx7kWocb26OD398mI2EhoiegJlud4UFiZ5sm6Kdn2mBr5t7pJ9rlG0cHg5gXitdaxwFGArIGgoaGwYCZ3QFDwjU1AoIzdCQzdPV1c0bZ9vS3tUJBmjQaGXl1OB0feze1+faiBvk8wjnimn55e/o4OtWjp+4NPIKogsXjaA3g/fiGZBQAcEAFgQGOChgYEEDCCBBLihwQILJkxIe/3wMKfJBSQkJYJpUyRIkgwcVUJq8QLPmTYoyY6ZcyfJmTp08iYZc8MBkhZgxk9aEcPOlzp5FmwI9KdWn1qASurJkClRoWKwhq6IUqpJBAwQEMBYroAHkhLt3+RyzhgCDgAV48Wbgg+waAnoLMgTOm6DwQ8CLBzdGdvjw38V5JTg2lzhyTMeUEwBWHPgzZc4TSOM1bZia6LuqJxCmnOxv7NSsl1mGHHiw5tOuIWeAEHcFATwJME/ApgFBc3MVLEgPvE+Ddb4JokufPmFBAuvPXWu3MIF89wTOmxvOvp179evQtwf2nr6aApPyzVd3jn089e/8xdfeXe/xdZ9/d1ngHf98lbHH3V0LMrgPgsWpcFwBEFBgHmyNXWeYAgLc1UF5sG2wTHjIhNjBiIKZCN81GGyQwYq9uajeMiBOQGOLJ1KjTI40kmfBYNfc2NcGIpI4pI0vyrhjiT1WFqOOLEIZnjVOVpmajYfBiCSNLGbA5YdOkjdihSkQwIEEEWg4nQUmvYhYe+bFKaFodN5lp3rKvJYfnBKAJ+gGDMi3mmbwWYfng7IheuWihu5p32XcSWdSj+stkF95dp64jJ+RBipocHkCCp6PCiRQ6INookCAAwy0yd2CtNET3Yo7RvihBjFZAOaKDHT43DL4BQnsZMo8xx6uI1oQrHXXhHZrB28G62n/YSYxi+uzP2IrgbbHbiaer7hCiOxDFWhrbmGnLVuus5NFexhFuHLX6gkEECorlLpZo0CWJG4pLjIACykmBsp0eSSVeC15TDJeUhlkowlL+SWLNJpW2WEF87urXzNWSZ6JOEb7b8g1brZMjCg3ezBtWKKc4MvyEtwybPeaMAA1ECRoAQYHYLpbeYYCLfQ+mtL5c9CnfQpYpUtHOSejEgT9ogZ/GSqd0f2m+LR5WzOtHqlQX1pYwpC+WbXKqSYtpJ5Mt4a01lGzS3akF60AxkcTaLgAyRBPWCoDgHfJqwRuBuzdw/1ml3iCwTIeLUWJN0v4McMe7uasCTxseNWPSxc5RbvIgD7geZLbGrqCG3jepUmbbze63Y6fvjiOylbwOITPfIHEFsAHL/zwxBdvPBVdFKH88sw37/zz0Ecv/fTUV2/99SeEAAAh+QQJCgAAACwAAAAA3AATAAAF/yAgjmRpnmiqrmzrvnAsz3Rt33iu73zv/8CgcEgECAaEpHLJbDqf0Kh0Sq1ar9isdjoQtAQFh2cw8BQEm3T6yHEYHHD4oKCuD9qGvNsxT6QTgAkcHHmFeX11fm17hXwPG35qgnhxbwMPkXaLhgZ9gWp3bpyegX4DcG+inY+Qn6eclpiZkHh6epetgLSUcBxlD2csXXdvBQrHGgoaGhsGaIkFDwjTCArTzX+QadHU3c1ofpHc3dcGG89/4+TYktvS1NYI7OHu3fEJ5tpqBu/k+HX7+nXDB06SuoHm0KXhR65cQT8P3FRAMIAFgVMPwDCAwLHjggIHJIgceeFBg44eC/+ITCCBZYKSJ1FCWPBgpE2YMmc+qNCypwScMmnaXAkUJYOaFVyKLOqx5tCXJnMelcBzJNSYKIX2ZPkzqsyjPLku9Zr1QciVErYxaICAgEUOBRJIgzChbt0MLOPFwyBggV27eCUcmxZvg9+/dfPGo5bg8N/Ag61ZM4w4seDF1fpWhizZmoa+GSortgcaMWd/fkP/HY0MgWbTipVV++wY8GhvqSG4XUEgoYTKE+Qh0OCvggULiBckWEZ4Ggbjx5HXVc58IPQJ0idQJ66XanTpFraTe348+XLizRNcz658eHMN3rNPT+C+G/nodqk3t6a+fN3j+u0Xn3nVTQPfdRPspkL/b+dEIN8EeMm2GAYbTNABdrbJ1hyFFv5lQYTodSZABhc+loCEyhxTYYkZopdMMiNeiBxyIFajV4wYHpfBBspUl8yKHu6ooV5APsZjQxyyeNeJ3N1IYod38cgdPBUid6GCKfRWgAYU4IccSyHew8B3doGJHmMLkGkZcynKk2Z50Ym0zJzLbDCmfBbI6eIyCdyJmJmoqZmnBAXy9+Z/yOlZDZpwYihnj7IZpuYEevrYJ5mJEuqiof4l+NYDEXQpXQcMnNjZNDx1oGqJ4S2nF3EsqWrhqqVWl6JIslpAK5MaIqDeqjJq56qN1aTaQaPbHTPYr8Be6Gsyyh6Da7OkmmqP/7GyztdrNVQBm5+pgw3X7aoYKhfZosb6hyUKBHCgQKij1rghkOAJuZg1SeYIIY+nIpDvf/sqm4yNG5CY64f87qdAwSXKGqFkhPH1ZHb2EgYtw3bpKGVkPz5pJAav+gukjB1UHE/HLNJobWcSX8jiuicMMBFd2OmKwQFs2tjXpDfnPE1j30V3c7iRHlrzBD2HONzODyZtsQJMI4r0AUNaE3XNHQw95c9GC001MpIxDacFQ+ulTNTZlU3O1eWVHa6vb/pnQUUrgHHSBKIuwG+bCPyEqbAg25gMVV1iOB/IGh5YOKLKIQ6xBAcUHmzjIcIqgajZ+Ro42DcvXl7j0U4WOUd+2IGu7DWjI1pt4DYq8BPm0entuGSQY/4tBi9Ss0HqfwngBQtHbCH88MQXb/zxyFfRRRHMN+/889BHL/301Fdv/fXYZ39CCAAh+QQJCgAAACwAAAAA3AATAAAF/yAgjmRpnmiqrmzrvnAsz3Rt33iu73zv/8CgcEgECAaEpHLJbDqf0Kh0Sq1ar9isdjoQtAQFh2fAKXsKm7R6Q+Y43vABep0mGwwOPH7w2CT+gHZ3d3lyagl+CQNvg4yGh36LcHoGfHR/ZYOElQ9/a4ocmoRygIiRk5p8pYmZjXePaYBujHoOqp5qZHBlHAUFXitddg8PBg8KGsgayxvGkAkFDwgICtPTzX2mftHW3QnOpojG3dbYkNjk1waxsdDS1N7ga9zw1t/aifTk35fu6Qj3numL14fOuHTNECHqU4DDgQEsCCwidiHBAwYQMmpcUOCAhI8gJVzUuLGThAQnP/9abEAyI4MCIVOKZNnyJUqUJxNcGNlywYOQgHZirGkSJ8gHNEky+AkS58qWEJYC/bMzacmbQHkqNdlUJ1KoSz2i9COhmQYCEXtVrCBgwYS3cCf8qTcNQ9u4cFFOq2bPLV65Cf7dxZthbjW+CgbjnWtNgWPFcAsHdoxgWWK/iyV045sAc2S96SDn1exYw17REwpLQEYt2eW/qtPZRQAB7QoC61RW+GsBwYZ/CXb/XRCYLsAKFizEtUAc+G7lcZsjroscOvTmsoUvx15PwccJ0N8yL17N9PG/E7jv9S4hOV7pdIPDdZ+ePDzv2qMXn2b5+wTbKuAWnF3oZbABZY0lVmD/ApQd9thybxno2GGuCVDggaUpoyBsB1bGGgIYbJCBcuFJiOAyGohIInQSmmdeiBnMF2GHfNUlIoc1rncjYRjW6NgGf3VQGILWwNjBfxEZcAFbC7gHXQcfUYOYdwzQNxo5yUhQZXhvRYlMeVSuSOJHKJa5AQMQThBlZWZ6Bp4Fa1qzTAJbijcBlJrtxeaZ4lnnpZwpukWieGQmYx5ATXIplwTL8DdNZ07CtWYybNIJF4Ap4NZHe0920AEDk035kafieQrqXofK5ympn5JHKYjPrfoWcR8WWQGp4Ul32KPVgXdnqxM6OKqspjIYrGPDrlrsZtRIcOuR86nHFwbPvmes/6PH4frrqbvySh+mKGhaAARPzjjdhCramdoGGOhp44i+zogBkSDuWC5KlE4r4pHJkarXrj++Raq5iLmWLlxHBteavjG+6amJrUkJJI4Ro5sBv9AaOK+jAau77sbH7nspCwNIYIACffL7J4JtWQnen421nNzMcB6AqpRa9klonmBSiR4GNi+cJZpvwgX0ejj71W9yR+eIgaVvQgf0l/A8nWjUFhwtZYWC4hVnkZ3p/PJqNQ5NnwUQrQCGBBBMQIGTtL7abK+5JjAv1fi9bS0GLlJHgdjEgYzzARTwC1fgEWdJuKKBZzj331Y23qB3i9v5aY/rSUC4w7PaLeWXmr9NszMFoN79eeiM232o33EJAIzaSGwh++y012777bhT0UURvPfu++/ABy/88MQXb/zxyCd/QggAIfkECQoAAAAsAAAAANwAEwAABf8gII5kaZ5oqq5s675wLM90bd94ru987//AoHBIBAgGhKRyyWw6n9CodEqtWq/YrHY6ELQEBY5nwCk7xIWNer0hO95wziC9Ttg5b4ND/+Y87IBqZAaEe29zGwmJigmDfHoGiImTjXiQhJEPdYyWhXwDmpuVmHwOoHZqjI6kZ3+MqhyemJKAdo6Ge3OKbEd4ZRwFBV4rc4MPrgYPChrMzAgbyZSJBcoI1tfQoYsJydfe2amT3d7W0OGp1OTl0YtqyQrq0Lt11PDk3KGoG+nxBpvTD9QhwCctm0BzbOyMIwdOUwEDEgawIOCB2oMLgB4wgMCx44IHBySIHClBY0ePfyT/JCB5weRJCAwejFw58kGDlzBTqqTZcuPLmCIBiWx58+VHmiRLFj0JVCVLl0xl7qSZwCbOo0lFWv0pdefQrVFDJtr5gMBEYBgxqBWwYILbtxPsqMPAFu7blfa81bUbN4HAvXAzyLWnoDBguHIRFF6m4LBbwQngMYPXuC3fldbyPrMcGLM3w5wRS1iWWUNlvnElKDZtz/EEwaqvYahQoexEfyILi4RrYYKFZwJ3810QWZ2ECrx9Ew+O3K6F5Yq9zXbb+y30a7olJJ+wnLC16W97Py+uwdtx1NcLWzs/3G9e07stVPc9kHJ0BcLtQp+c3ewKAgYkUAFpCaAmmHqKLSYA/18WHEiZPRhsQF1nlLFWmIR8ZbDBYs0YZuCGpGXWmG92aWiPMwhEOOEEHXRwIALlwXjhio+BeE15IzpnInaLbZBBhhti9x2GbnVQo2Y9ZuCfCgBeMCB+DJDIolt4iVhOaNSJdCOBUfIlkmkyMpPAAvKJ59aXzTQzJo0WoJnmQF36Jp6W1qC4gWW9GZladCiyJd+KnsHImgRRVjfnaDEKuiZvbcYWo5htzefbl5LFWNeSKQAo1QXasdhiiwwUl2B21H3aQaghXnPcp1NagCqYslXAqnV+zYWcpNwVp9l5eepJnHqL4SdBi56CGlmw2Zn6aaiZjZqfb8Y2m+Cz1O0n3f+tnvrGbF6kToApCgAWoNWPeh754JA0vmajiAr4iOuOW7abQXVGNriBWoRdOK8FxNqLwX3oluubhv8yluRbegqGb536ykesuoXhyJqPQJIGbLvQhkcwjKs1zBvBwSZIsbcsDCCBAAf4ya+UEhyQoIiEJtfoZ7oxUOafE2BwgMWMqUydfC1LVtiArk0QtGkWEopzlqM9aJrKHfw5c6wKjFkmXDrbhwFockodtMGFLWpXy9JdiXN1ZDNszV4WSLQCGBKoQYHUyonqrHa4ErewAgMmcAAF7f2baIoVzC2p3gUvJtLcvIWqloy6/R04mIpLwDhciI8qLOB5yud44pHPLbA83hFDWPjNbuk9KnySN57Av+TMBvgEAgzzNhJb5K777rz37vvvVHRRxPDEF2/88cgnr/zyzDfv/PPQnxACACH5BAkKAAAALAAAAADcABMAAAX/ICCOZGmeaKqubOu+cCzPdG3feK7vfO//wKBwSAQIBoSkcslsOp/QqHRKrVqv2Kx2OhC0BIUCwcMpO84OT2HDbm8GHLQjnn6wE3g83SA3DB55G3llfHxnfnZ4gglvew6Gf4ySgmYGlpCJknochWiId3kJcZZyDn93i6KPl4eniopwq6SIoZKxhpenbhtHZRxhXisDopwPgHkGDxrLGgjLG8mC0gkFDwjX2AgJ0bXJ2djbgNJsAtbfCNB2oOnn6MmKbeXt226K1fMGi6j359D69ua+QZskjd+3cOvY9XNgp4ABCQNYEDBl7EIeCQkeMIDAseOCBwckiBSZ4ILGjh4B/40kaXIjSggMHmBcifHky5gYE6zM2OAlzGM6Z5rs+fIjTZ0tfcYMSlLCUJ8fL47kCVXmTjwPiKJkUCDnyqc3CxzQmYeAxAEGLGJYiwCDgAUT4sqdgOebArdw507IUNfuW71xdZ7DC5iuhGsKErf9CxhPYgUaEhPWyzfBMgUIJDPW6zhb5M1y+R5GjFkBaLmCM0dOfHqvztXYJnMejaFCBQlmVxAYsEGkYnQV4lqYMNyCtnYSggNekAC58uJxmTufW5w55mwKkg+nLp105uTC53a/nhg88fMTmDfDVl65Xum/IZt/3/zaag3a5W63nll1dvfiWbaaZLmpQIABCVQA2f9lAhTG112PQWYadXE9+FtmEwKWwQYQJrZagxomsOCAGVImInsSbpCBhhwug6KKcXXQQYUcYuDMggrASFmNzjjzzIrh7cUhhhHqONeGpSEW2QYxHsmjhxpgUGAKB16g4IIbMNCkXMlhaJ8GWVJo2I3NyKclYF1GxgyYDEAnXHJrMpNAm/rFBSczPiYAlwXF8ZnmesvoOdyMbx7m4o0S5LWdn4bex2Z4xYmEzaEb5EUcnxbA+WWglqIn6aHPTInCgVbdlZyMqMrIQHMRSiaBBakS1903p04w434n0loBoQFOt1yu2YAnY68RXiNsqh2s2qqxuyKb7Imtmgcrqsp6h8D/fMSpapldx55nwayK/SfqCQd2hcFdAgDp5GMvqhvakF4mZuS710WGIYy30khekRkMu92GNu6bo7r/ttjqwLaua5+HOdrKq5Cl3dcwi+xKiLBwwwom4b0E6xvuYyqOa8IAEghwQAV45VvovpkxBl2mo0W7AKbCZXoAhgMmWnOkEqx2JX5nUufbgJHpXCfMOGu2QAd8eitpW1eaNrNeMGN27mNz0swziYnpSbXN19gYtstzfXrdYjNHtAIYGFVwwAEvR1dfxdjKxVzAP0twAAW/ir2w3nzTd3W4yQWO3t0DfleB4XYnEHCEhffdKgaA29p0eo4fHLng9qoG+OVyXz0gMeWGY7qq3xhiRIEAwayNxBawxy777LTXbjsVXRSh++689+7778AHL/zwxBdv/PEnhAAAIfkECQoAAAAsAAAAANwAEwAABf8gII5kaZ5oqq5s675wLM90bd94ru987//AoHBIBAgGhKRyyWw6n9CodEqtWq/YrHY6ELQEhYLD4BlwHGg0ubBpuzdm9Dk9eCTu+MTZkDb4PXYbeIIcHHxqf4F3gnqGY2kOdQmCjHCGfpCSjHhmh2N+knmEkJmKg3uHfgaaeY2qn6t2i4t7sKAPbwIJD2VhXisDCQZgDrKDBQ8aGgjKyhvDlJMJyAjV1gjCunkP1NfVwpRtk93e2ZVt5NfCk27jD97f0LPP7/Dr4pTp1veLgvrx7AL+Q/BM25uBegoYkDCABYFhEobhkUBRwoMGEDJqXPDgQMUEFC9c1LjxQUUJICX/iMRIEgIDkycrjmzJMSXFlDNJvkwJsmdOjQwKfDz5M+PLoSGLQqgZU6XSoB/voHxawGbFlS2XGktAwKEADB0xiEWAodqGBRPSqp1wx5qCamDRrp2Qoa3bagLkzrULF4GCvHPTglRAmKxZvWsHayBcliDitHUlvGWM97FgCdYWVw4c2e/kw4HZJlCwmDBhwHPrjraGYTHqtaoxVKggoesKAgd2SX5rbUMFCxOAC8cGDwHFwBYWJCgu4XfwtcqZV0grPHj0u2SnqwU+IXph3rK5b1fOu7Bx5+K7L6/2/Xhg8uyXnQ8dvfRiDe7TwyfNuzlybKYpgIFtKhAgwEKkKcOf/wChZbBBgMucRh1so5XH3wbI1WXafRJy9iCErmX4IWHNaIAhZ6uxBxeGHXQA24P3yYfBBhmgSBozESpwongWOBhggn/N1aKG8a1YY2oVAklgCgQUUwGJ8iXAgItrWUARbwpqIOWEal0ZoYJbzmWlZCWSlsAC6VkwZonNbMAAl5cpg+NiZwpnJ0Xylegmlc+tWY1mjnGnZnB4QukMA9UJRxGOf5r4ppqDjjmnfKilh2ejGiyJAgF1XNmYbC2GmhZ5AcJVgajcXecNqM9Rx8B6bingnlotviqdkB3YCg+rtOaapFsUhSrsq6axJ6sEwoZK7I/HWpCsr57FBxJ1w8LqV/81zbkoXK3LfVeNpic0KRQG4NHoIW/XEmZuaiN6tti62/moWbk18uhjqerWS6GFpe2YVotskVssWfBOAHACrZHoWcGQwQhlvmsdXBZ/F9YLMF2jzUuYBP4a7CLCnoEHrgkDSCDAARUILAGaVVqAwQHR8pZXomm9/ONhgjrbgc2lyYxmpIRK9uSNjrXs8gEbTrYyl2ryTJmsLCdKkWzFQl1lWlOXGmifal6p9VnbQfpyY2SZyXKVV7JmZkMrgIFSyrIeUJ2r7YKnXdivUg1kAgdQ8B7IzJjGsd9zKSdwyBL03WpwDGxwuOASEP5vriO2F3nLjQdIrpaRDxqcBdgIHGA74pKrZXiR2ZWuZt49m+o3pKMC3p4Av7SNxBa456777rz37jsVXRQh/PDEF2/88cgnr/zyzDfv/PMnhAAAIfkECQoAAAAsAAAAANwAEwAABf8gII5kaZ5oqq5s675wLM90bd94ru987//AoHBIBAgGhKRyyWw6n9CodEqtWq/YrHY6ELQEhYLDUPAMHGi0weEpbN7wI8cxTzsGj4R+n+DUxwaBeBt7hH1/gYIPhox+Y3Z3iwmGk36BkIN8egOIl3h8hBuOkAaZhQlna4BrpnyWa4mleZOFjrGKcXoFA2ReKwMJBgISDw6abwUPGggazc0bBqG0G8kI1tcIwZp51djW2nC03d7BjG8J49jl4cgP3t/RetLp1+vT6O7v5fKhAvnk0UKFogeP3zmCCIoZkDCABQFhChQYuKBHgkUJkxpA2MhxQYEDFhNcvPBAI8eNCx7/gMQYckPJkxsZPLhIM8FLmDJrYiRp8mTKkCwT8IQJwSPQkENhpgQpEunNkzlpWkwKdSbGihKocowqVSvKWQkIOBSgQOYFDBgQpI0oYMGEt3AzTLKm4BqGtnDjirxW95vbvG/nWlub8G9euRsiqqWLF/AEkRoiprX2wLDeDQgkW9PQGLDgyNc665WguK8C0XAnRY6oGPUEuRLsgk5g+a3cCxUqSBC7gsCBBXcVq6swwULx4hayvctGPK8FCwsSLE9A3Hje6NOrHzeOnW695sffRi/9HfDz7sIVSNB+XXrmugo0rHcM3X388o6jr44ceb51uNjF1xcC8zk3wXiS8aYC/wESaLABBs7ch0ECjr2WAGvLsLZBeHqVFl9kGxooV0T81TVhBo6NiOEyJ4p4IYnNRBQiYCN6x4wCG3ZAY2If8jXjYRcyk2FmG/5nXAY8wqhWAii+1YGOSGLoY4VRfqiAgikwmIeS1gjAgHkWYLQZf9m49V9gDWYWY5nmTYCRM2TS5pxxb8IZGV5nhplmhJyZadxzbrpnZ2d/6rnZgHIid5xIMDaDgJfbLdrgMkKW+Rygz1kEZz1mehabkBpgiQIByVikwGTqVfDkk2/Vxxqiqur4X3fksHccre8xlxerDLiHjQIVUAgXr77yFeyuOvYqXGbMrbrqBMqaFpFFzhL7qv9i1FX7ZLR0LUNdcc4e6Cus263KbV+inkAAHhJg0BeITR6WmHcaxhvXg/AJiKO9R77ILF1FwmVdAu6WBu+ZFua72mkZWMfqBElKu0G8rFZ5n4ATp5jkmvsOq+Nj7u63ZMMPv4bveyYy6fDH+C6brgnACHBABQUrkGirz2FwAHnM4Mmhzq9yijOrOi/MKabH6VwBiYwZdukEQAvILKTWXVq0ZvH5/CfUM7M29Zetthp1eht0eqkFYw8IKXKA6mzXfTeH7fZg9zW0AhgY0TwthUa6Ch9dBeIsbsFrYkRBfgTfiG0FhwMWnbsoq3cABUYOnu/ejU/A6uNeT8u4wMb1WnBCyJJTLjjnr8o3OeJrUcpc5oCiPqAEkz8tXuLkPeDL3Uhs4fvvwAcv/PDEU9FFEcgnr/zyzDfv/PPQRy/99NRXf0IIACH5BAkKAAAALAAAAADcABMAAAX/ICCOZGmeaKqubOu+cCzPdG3feK7vfO//wKBwSAQIBoSkcslsOp/QqHRKrVqv2Kx2OhC0BIWCw/AoDziOtCHt8BQ28PjmzK57Hom8fo42+P8DeAkbeYQcfX9+gYOFg4d1bIGEjQmPbICClI9/YwaLjHAJdJeKmZOViGtpn3qOqZineoeJgG8CeWUbBV4rAwkGAhIVGL97hGACGsrKCAgbBoTRhLvN1c3PepnU1s2/oZO6AtzdBoPf4eMI3tIJyOnF0YwFD+nY8e3z7+Xfefnj9uz8cVsXCh89axgk7BrAggAwBQsYIChwQILFixIeNIDAseOCBwcSXMy2sSPHjxJE/6a0eEGjSY4MQGK86PIlypUJEmYsaTKmyJ8JW/Ls6HMkzaEn8YwMWtPkx4pGd76E4DMPRqFTY860OGhogwYagBFoKEABA46DEGBAoEBB0AUT4sqdIFKBNbcC4M6dkEEk22oYFOTdG9fvWrtsBxM23MytYL17666t9phwXwlum2lIDHmuSA2IGyuOLOHv38qLMbdFjHruZbWgRXeOe1nC2BUEDiyAMMHZuwoTLAQX3nvDOAUW5Vogru434d4JnAsnPmFB9NBshQXfa9104+Rxl8e13rZxN+CEydtVsFkd+vDjE7C/q52wOvb4s7+faz025frbxefWbSoQIAEDEUCwgf9j7bUlwHN9ZVaegxDK1xYzFMJH24L5saXABhlYxiEzHoKoIV8LYqAMaw9aZqFmJUK4YHuNfRjiXhmk+NcyJgaIolvM8BhiBx3IleN8lH1IWAcRgkZgCgYiaBGJojGgHHFTgtagAFYSZhF7/qnTpY+faVlNAnqJN0EHWa6ozAZjBtgmmBokwMB01LW5jAZwbqfmlNips4B4eOqJgDJ2+imXRZpthuigeC6XZTWIxilXmRo8iYKBCwiWmWkJVEAkfB0w8KI1IvlIpKnOkVpqdB5+h96o8d3lFnijrgprjbfGRSt0lH0nAZG5vsprWxYRW6Suq4UWqrLEsspWg8Io6yv/q6EhK0Fw0GLbjKYn5CZYBYht1laPrnEY67kyrhYbuyceiR28Pso7bYwiXjihjWsWuWF5p/H765HmNoiur3RJsGKNG/jq748XMrwmjhwCfO6QD9v7LQsDxPTAMKsFpthyJCdkmgYiw0VdXF/Om9dyv7YMWGXTLYpZg5wNR11C78oW3p8HSGgul4qyrJppgllJHJZHn0Y0yUwDXCXUNquFZNLKyYXBAVZvxtAKYIQEsmPgDacr0tltO1y/DMwYpkgUpJfTasLGzd3cdCN3gN3UWRcY3epIEPevfq+3njBxq/kqBoGBduvea8f393zICS63ivRBTqgFpgaWZEIUULdcK+frIfAAL2AjscXqrLfu+uuwx05FF0XUbvvtuOeu++689+7778AHL/wJIQAAOwAAAAAAAAAAAA==");
| zzangtest123-google-drive-sdk-samples | php/static/ace/cockpit-uncompressed.js | JavaScript | asf20 | 113,605 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Curl based implementation of apiIO.
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*/
require_once 'apiCacheParser.php';
class apiCurlIO implements apiIO {
const CONNECTION_ESTABLISHED = "HTTP/1.0 200 Connection established\r\n\r\n";
const FORM_URLENCODED = 'application/x-www-form-urlencoded';
private static $ENTITY_HTTP_METHODS = array("POST" => null, "PUT" => null);
private static $HOP_BY_HOP = array(
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
'te', 'trailers', 'transfer-encoding', 'upgrade');
private static $DEFAULT_CURL_PARAMS = array (
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => 0,
CURLOPT_FAILONERROR => false,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HEADER => true,
);
/**
* Perform an authenticated / signed apiHttpRequest.
* This function takes the apiHttpRequest, calls apiAuth->sign on it
* (which can modify the request in what ever way fits the auth mechanism)
* and then calls apiCurlIO::makeRequest on the signed request
*
* @param apiHttpRequest $request
* @return apiHttpRequest The resulting HTTP response including the
* responseHttpCode, responseHeaders and responseBody.
*/
public function authenticatedRequest(apiHttpRequest $request) {
$request = apiClient::$auth->sign($request);
return $this->makeRequest($request);
}
/**
* Execute a apiHttpRequest
*
* @param apiHttpRequest $request the http request to be executed
* @return apiHttpRequest http request with the response http code, response
* headers and response body filled in
* @throws apiIOException on curl or IO error
*/
public function makeRequest(apiHttpRequest $request) {
// First, check to see if we have a valid cached version.
$cached = $this->getCachedRequest($request);
if ($cached !== false) {
if (apiCacheParser::mustRevalidate($cached)) {
$addHeaders = array();
if ($cached->getResponseHeader('etag')) {
// [13.3.4] If an entity tag has been provided by the origin server,
// we must use that entity tag in any cache-conditional request.
$addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
} elseif ($cached->getResponseHeader('date')) {
$addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
}
$request->setRequestHeaders($addHeaders);
} else {
// No need to revalidate the request, return it directly
return $cached;
}
}
if (array_key_exists($request->getRequestMethod(),
self::$ENTITY_HTTP_METHODS)) {
$request = $this->processEntityRequest($request);
}
$ch = curl_init();
curl_setopt_array($ch, self::$DEFAULT_CURL_PARAMS);
curl_setopt($ch, CURLOPT_URL, $request->getUrl());
if ($request->getPostBody()) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPostBody());
}
$requestHeaders = $request->getRequestHeaders();
if ($requestHeaders && is_array($requestHeaders)) {
$parsed = array();
foreach ($requestHeaders as $k => $v) {
$parsed[] = "$k: $v";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $parsed);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
curl_setopt($ch, CURLOPT_USERAGENT, $request->getUserAgent());
$respData = curl_exec($ch);
// Retry if certificates are missing.
if (curl_errno($ch) == CURLE_SSL_CACERT) {
error_log('SSL certificate problem, verify that the CA cert is OK.'
. ' Retrying with the CA cert bundle from google-api-php-client.');
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
$respData = curl_exec($ch);
}
$respHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$respHttpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErrorNum = curl_errno($ch);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlErrorNum != CURLE_OK) {
throw new apiIOException("HTTP Error: ($respHttpCode) $curlError");
}
// Parse out the raw response into usable bits
list($responseHeaders, $responseBody) =
$this->parseHttpResponseBody($respData, $respHeaderSize);
if ($respHttpCode == 304 && $cached) {
// If the server responded NOT_MODIFIED, return the cached request.
if (isset($responseHeaders['connection'])) {
$hopByHop = array_merge(
self::$HOP_BY_HOP,
explode(',', $responseHeaders['connection'])
);
$endToEnd = array();
foreach($hopByHop as $key) {
if (isset($responseHeaders[$key])) {
$endToEnd[$key] = $responseHeaders[$key];
}
}
$cached->setResponseHeaders($endToEnd);
}
return $cached;
}
// Fill in the apiHttpRequest with the response values
$request->setResponseHttpCode($respHttpCode);
$request->setResponseHeaders($responseHeaders);
$request->setResponseBody($responseBody);
// Store the request in cache (the function checks to see if the request
// can actually be cached)
$this->setCachedRequest($request);
// And finally return it
return $request;
}
/**
* @visible for testing.
* Cache the response to an HTTP request if it is cacheable.
* @param apiHttpRequest $request
* @return bool Returns true if the insertion was successful.
* Otherwise, return false.
*/
public function setCachedRequest(apiHttpRequest $request) {
// Determine if the request is cacheable.
if (apiCacheParser::isResponseCacheable($request)) {
apiClient::$cache->set($request->getCacheKey(), $request);
return true;
}
return false;
}
/**
* @visible for testing.
* @param apiHttpRequest $request
* @return apiHttpRequest|bool Returns the cached object or
* false if the operation was unsuccessful.
*/
public function getCachedRequest(apiHttpRequest $request) {
if (false == apiCacheParser::isRequestCacheable($request)) {
false;
}
return apiClient::$cache->get($request->getCacheKey());
}
/**
* @param $respData
* @param $headerSize
* @return array
*/
public function parseHttpResponseBody($respData, $headerSize) {
if (stripos($respData, self::CONNECTION_ESTABLISHED) !== false) {
$respData = str_ireplace(self::CONNECTION_ESTABLISHED, '', $respData);
}
$responseBody = substr($respData, $headerSize);
$responseHeaderLines = explode("\r\n", substr($respData, 0, $headerSize));
$responseHeaders = array();
foreach ($responseHeaderLines as $headerLine) {
if ($headerLine && strpos($headerLine, ':') !== false) {
list($header, $value) = explode(': ', $headerLine, 2);
$header = strtolower($header);
if (isset($responseHeaders[$header])) {
$responseHeaders[$header] .= "\n" . $value;
} else {
$responseHeaders[$header] = $value;
}
}
}
return array($responseHeaders, $responseBody);
}
/**
* @visible for testing
* Process an http request that contains an enclosed entity.
* @param apiHttpRequest $request
* @return apiHttpRequest Processed request with the enclosed entity.
*/
public function processEntityRequest(apiHttpRequest $request) {
$postBody = $request->getPostBody();
$contentType = $request->getRequestHeader("content-type");
// Set the default content-type as application/x-www-form-urlencoded.
if (false == $contentType) {
$contentType = self::FORM_URLENCODED;
$request->setRequestHeaders(array('content-type' => $contentType));
}
// Force the payload to match the content-type asserted in the header.
if ($contentType == self::FORM_URLENCODED && is_array($postBody)) {
$postBody = http_build_query($postBody, '', '&');
$request->setPostBody($postBody);
}
// Make sure the content-length header is set.
if (!$postBody || is_string($postBody)) {
$postsLength = strlen($postBody);
$request->setRequestHeaders(array('content-length' => $postsLength));
}
return $request;
}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/io/apiCurlIO.php | PHP | asf20 | 8,846 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class implements the experimental JSON-RPC transport for executing apiServiceRequest'
*
* @author Chris Chabot <chabotc@google.com>
*/
class apiRPC {
static public function execute($requests) {
$jsonRpcRequest = array();
foreach ($requests as $request) {
$parameters = array();
foreach ($request->getParameters() as $parameterName => $parameterVal) {
$parameters[$parameterName] = $parameterVal['value'];
}
$jsonRpcRequest[] = array(
'id' => $request->getBatchKey(),
'method' => $request->getRpcName(),
'params' => $parameters,
'apiVersion' => 'v1'
);
}
$httpRequest = new apiHttpRequest($request->getRpcPath());
$httpRequest->setRequestHeaders(array('Content-Type' => 'application/json'));
$httpRequest->setRequestMethod('POST');
$httpRequest->setPostBody(json_encode($jsonRpcRequest));
$httpRequest = apiClient::$io->authenticatedRequest($httpRequest);
if (($decodedResponse = json_decode($httpRequest->getResponseBody(), true)) != false) {
$ret = array();
foreach ($decodedResponse as $response) {
$ret[$response['id']] = self::checkNextLink($response['result']);
}
return $ret;
} else {
throw new apiServiceException("Invalid json returned by the json-rpc end-point");
}
}
static private function checkNextLink($response) {
if (isset($response['links']) && isset($response['links']['next'][0]['href'])) {
parse_str($response['links']['next'][0]['href'], $params);
if (isset($params['c'])) {
$response['continuationToken'] = $params['c'];
}
}
return $response;
}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/io/apiRPC.php | PHP | asf20 | 2,282 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* HTTP Request to be executed by apiIO classes. Upon execution, the
* responseHttpCode, responseHeaders and responseBody will be filled in.
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*
*/
class apiHttpRequest {
const USER_AGENT_SUFFIX = "google-api-php-client/0.4.8";
protected $url;
protected $requestMethod;
protected $requestHeaders;
protected $postBody;
protected $userAgent;
protected $responseHttpCode;
protected $responseHeaders;
protected $responseBody;
public $accessKey;
public function __construct($url, $method = 'GET', $headers = array(), $postBody = null) {
$this->url = $url;
$this->setRequestMethod($method);
$this->setRequestHeaders($headers);
$this->setPostBody($postBody);
global $apiConfig;
if (empty($apiConfig['application_name'])) {
$this->userAgent = self::USER_AGENT_SUFFIX;
} else {
$this->userAgent = $apiConfig['application_name'] . " " . self::USER_AGENT_SUFFIX;
}
}
/**
* Misc function that returns the base url component of the $url
* used by the OAuth signing class to calculate the base string
* @return string The base url component of the $url.
* @see http://oauth.net/core/1.0a/#anchor13
*/
public function getBaseUrl() {
if ($pos = strpos($this->url, '?')) {
return substr($this->url, 0, $pos);
}
return $this->url;
}
/**
* Misc function that returns an array of the query parameters of the current
* url used by the OAuth signing class to calculate the signature
* @return array Query parameters in the query string.
*/
public function getQueryParams() {
if ($pos = strpos($this->url, '?')) {
$queryStr = substr($this->url, $pos + 1);
$params = array();
parse_str($queryStr, $params);
return $params;
}
return array();
}
/**
* @return string HTTP Response Code.
*/
public function getResponseHttpCode() {
return (int) $this->responseHttpCode;
}
/**
* @param int $responseHttpCode HTTP Response Code.
*/
public function setResponseHttpCode($responseHttpCode) {
$this->responseHttpCode = $responseHttpCode;
}
/**
* @return $responseHeaders (array) HTTP Response Headers.
*/
public function getResponseHeaders() {
return $this->responseHeaders;
}
/**
* @return string HTTP Response Body
*/
public function getResponseBody() {
return $this->responseBody;
}
/**
* @param array $headers The HTTP response headers
* to be normalized.
*/
public function setResponseHeaders($headers) {
$headers = apiUtils::normalize($headers);
if ($this->responseHeaders) {
$headers = array_merge($this->responseHeaders, $headers);
}
$this->responseHeaders = $headers;
}
/**
* @param string $key
* @return array|boolean Returns the requested HTTP header or
* false if unavailable.
*/
public function getResponseHeader($key) {
return isset($this->responseHeaders[$key])
? $this->responseHeaders[$key]
: false;
}
/**
* @param string $responseBody The HTTP response body.
*/
public function setResponseBody($responseBody) {
$this->responseBody = $responseBody;
}
/**
* @return string $url The request URL.
*/
public function getUrl() {
return $this->url;
}
/**
* @return string $method HTTP Request Method.
*/
public function getRequestMethod() {
return $this->requestMethod;
}
/**
* @return array $headers HTTP Request Headers.
*/
public function getRequestHeaders() {
return $this->requestHeaders;
}
/**
* @param string $key
* @return array|boolean Returns the requested HTTP header or
* false if unavailable.
*/
public function getRequestHeader($key) {
return isset($this->requestHeaders[$key])
? $this->requestHeaders[$key]
: false;
}
/**
* @return string $postBody HTTP Request Body.
*/
public function getPostBody() {
return $this->postBody;
}
/**
* @param string $url the url to set
*/
public function setUrl($url) {
$this->url = $url;
}
/**
* @param string $method Set he HTTP Method and normalize
* it to upper-case, as required by HTTP.
*
*/
public function setRequestMethod($method) {
$this->requestMethod = strtoupper($method);
}
/**
* @param array $headers The HTTP request headers
* to be set and normalized.
*/
public function setRequestHeaders($headers) {
$headers = apiUtils::normalize($headers);
if ($this->requestHeaders) {
$headers = array_merge($this->requestHeaders, $headers);
}
$this->requestHeaders = $headers;
}
/**
* @param string $postBody the postBody to set
*/
public function setPostBody($postBody) {
$this->postBody = $postBody;
}
/**
* Set the User-Agent Header.
* @param string $userAgent The User-Agent.
*/
public function setUserAgent($userAgent) {
$this->userAgent = $userAgent;
}
/**
* @return string The User-Agent.
*/
public function getUserAgent() {
return $this->userAgent;
}
/**
* Returns a cache key depending on if this was an OAuth signed request
* in which case it will use the non-signed url and access key to make this
* cache key unique per authenticated user, else use the plain request url
* @return The md5 hash of the request cache key.
*/
public function getCacheKey() {
$key = $this->getUrl();
if (isset($this->accessKey)) {
$key .= $this->accessKey;
}
if (isset($this->requestHeaders['authorization'])) {
$key .= $this->requestHeaders['authorization'];
}
return md5($key);
}
public function getParsedCacheControl() {
$parsed = array();
$rawCacheControl = $this->getResponseHeader('cache-control');
if ($rawCacheControl) {
$rawCacheControl = str_replace(", ", "&", $rawCacheControl);
parse_str($rawCacheControl, $parsed);
}
return $parsed;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/io/apiHttpRequest.php | PHP | asf20 | 6,641 |
<?php
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Implement the caching directives specified in rfc2616. This
* implementation is guided by the guidance offered in rfc2616-sec13.
* @author Chirag Shah <chirags@google.com>
*/
class apiCacheParser {
public static $CACHEABLE_HTTP_METHODS = array('GET', 'HEAD');
public static $CACHEABLE_STATUS_CODES = array('200', '203', '300', '301');
private function __construct() {}
/**
* Check if an HTTP request can be cached by a private local cache.
*
* @static
* @param apiHttpRequest $resp
* @return bool True if the request is cacheable.
* False if the request is uncacheable.
*/
public static function isRequestCacheable (apiHttpRequest $resp) {
$method = $resp->getRequestMethod();
if (! in_array($method, self::$CACHEABLE_HTTP_METHODS)) {
return false;
}
// Don't cache authorized requests/responses.
// [rfc2616-14.8] When a shared cache receives a request containing an
// Authorization field, it MUST NOT return the corresponding response
// as a reply to any other request...
if ($resp->getRequestHeader("authorization")) {
return false;
}
return true;
}
/**
* Check if an HTTP response can be cached by a private local cache.
*
* @static
* @param apiHttpRequest $resp
* @return bool True if the response is cacheable.
* False if the response is un-cacheable.
*/
public static function isResponseCacheable (apiHttpRequest $resp) {
// First, check if the HTTP request was cacheable before inspecting the
// HTTP response.
if (false == self::isRequestCacheable($resp)) {
return false;
}
$code = $resp->getResponseHttpCode();
if (! in_array($code, self::$CACHEABLE_STATUS_CODES)) {
return false;
}
// The resource is uncacheable if the resource is already expired and
// the resource doesn't have an ETag for revalidation.
$etag = $resp->getResponseHeader("etag");
if (self::isExpired($resp) && $etag == false) {
return false;
}
// [rfc2616-14.9.2] If [no-store is] sent in a response, a cache MUST NOT
// store any part of either this response or the request that elicited it.
$cacheControl = $resp->getParsedCacheControl();
if (isset($cacheControl['no-store'])) {
return false;
}
// Pragma: no-cache is an http request directive, but is occasionally
// used as a response header incorrectly.
$pragma = $resp->getResponseHeader('pragma');
if ($pragma == 'no-cache' || strpos($pragma, 'no-cache') !== false) {
return false;
}
// [rfc2616-14.44] Vary: * is extremely difficult to cache. "It implies that
// a cache cannot determine from the request headers of a subsequent request
// whether this response is the appropriate representation."
// Given this, we deem responses with the Vary header as uncacheable.
$vary = $resp->getResponseHeader('vary');
if ($vary) {
return false;
}
return true;
}
/**
* @static
* @param apiHttpRequest $resp
* @return bool True if the HTTP response is considered to be expired.
* False if it is considered to be fresh.
*/
public static function isExpired(apiHttpRequest $resp) {
// HTTP/1.1 clients and caches MUST treat other invalid date formats,
// especially including the value “0”, as in the past.
$parsedExpires = false;
$responseHeaders = $resp->getResponseHeaders();
if (isset($responseHeaders['expires'])) {
$rawExpires = $responseHeaders['expires'];
// Check for a malformed expires header first.
if (empty($rawExpires) || (is_numeric($rawExpires) && $rawExpires <= 0)) {
return true;
}
// See if we can parse the expires header.
$parsedExpires = strtotime($rawExpires);
if (false == $parsedExpires || $parsedExpires <= 0) {
return true;
}
}
// Calculate the freshness of an http response.
$freshnessLifetime = false;
$cacheControl = $resp->getParsedCacheControl();
if (isset($cacheControl['max-age'])) {
$freshnessLifetime = $cacheControl['max-age'];
}
$rawDate = $resp->getResponseHeader('date');
$parsedDate = strtotime($rawDate);
if (empty($rawDate) || false == $parsedDate) {
$parsedDate = time();
}
if (false == $freshnessLifetime && isset($responseHeaders['expires'])) {
$freshnessLifetime = $parsedExpires - $parsedDate;
}
if (false == $freshnessLifetime) {
return true;
}
// Calculate the age of an http response.
$age = max(0, time() - $parsedDate);
if (isset($responseHeaders['age'])) {
$age = max($age, strtotime($responseHeaders['age']));
}
return $freshnessLifetime <= $age;
}
/**
* Determine if a cache entry should be revalidated with by the origin.
*
* @param apiHttpRequest $response
* @return bool True if the entry is expired, else return false.
*/
public static function mustRevalidate(apiHttpRequest $response) {
// [13.3] When a cache has a stale entry that it would like to use as a
// response to a client's request, it first has to check with the origin
// server to see if its cached entry is still usable.
return self::isExpired($response);
}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/io/apiCacheParser.php | PHP | asf20 | 5,865 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "external/URITemplateParser.php";
require_once "service/apiUtils.php";
/**
* This class implements the RESTful transport of apiServiceRequest()'s
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*/
class apiREST {
/**
* Executes a apiServiceRequest using a RESTful call by transforming it into
* an apiHttpRequest, and executed via apiIO::authenticatedRequest().
*
* @param apiServiceRequest $req
* @return array decoded result
* @throws apiServiceException on server side error (ie: not authenticated, invalid or
* malformed post body, invalid url)
*/
static public function execute(apiServiceRequest $req) {
$result = null;
$postBody = $req->getPostBody();
$url = self::createRequestUri(
$req->getRestBasePath(), $req->getRestPath(), $req->getParameters());
$httpRequest = new apiHttpRequest($url, $req->getHttpMethod(), null, $postBody);
if ($postBody) {
$contentTypeHeader = array();
if (isset($req->contentType) && $req->contentType) {
$contentTypeHeader['content-type'] = $req->contentType;
} else {
$contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
$contentTypeHeader['content-length'] = apiUtils::getStrLen($postBody);
}
$httpRequest->setRequestHeaders($contentTypeHeader);
}
$httpRequest = apiClient::$io->authenticatedRequest($httpRequest);
$decodedResponse = self::decodeHttpResponse($httpRequest);
//FIXME currently everything is wrapped in a data envelope, but hopefully this might change some day
$ret = isset($decodedResponse['data']) ? $decodedResponse['data'] : $decodedResponse;
return $ret;
}
/**
* Decode an HTTP Response.
* @static
* @throws apiServiceException
* @param apiHttpRequest $response The http response to be decoded.
* @return mixed|null
*/
public static function decodeHttpResponse($response) {
$code = $response->getResponseHttpCode();
$body = $response->getResponseBody();
$decoded = null;
if ($code != '200' && $code != '201' && $code != '204') {
$decoded = json_decode($body, true);
$err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl();
if ($decoded != null && isset($decoded['error']['message']) && isset($decoded['error']['code'])) {
// if we're getting a json encoded error definition, use that instead of the raw response
// body for improved readability
$err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}";
} else {
$err .= ": ($code) $body";
}
throw new apiServiceException($err, $code);
}
// Only attempt to decode the response, if the response code wasn't (204) 'no content'
if ($code != '204') {
$decoded = json_decode($body, true);
if ($decoded == null) {
throw new apiServiceException("Invalid json in service response: $body");
}
}
return $decoded;
}
/**
* Parse/expand request parameters and create a fully qualified
* request uri.
* @static
* @param string $basePath
* @param string $restPath
* @param array $params
* @return string $requestUrl
*/
static function createRequestUri($basePath, $restPath, $params) {
$requestUrl = $basePath . $restPath;
$uriTemplateVars = array();
$queryVars = array();
foreach ($params as $paramName => $paramSpec) {
// Discovery v1.0 puts the canonical location under the 'location' field.
if (! isset($paramSpec['location'])) {
$paramSpec['location'] = $paramSpec['restParameterType'];
}
if ($paramSpec['type'] == 'boolean') {
$paramSpec['value'] = ($paramSpec['value']) ? 'true' : 'false';
}
if ($paramSpec['location'] == 'path') {
$uriTemplateVars[$paramName] = $paramSpec['value'];
} else {
if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
foreach ($paramSpec['value'] as $value) {
$queryVars[] = $paramName . '=' . rawurlencode($value);
}
} else {
$queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
}
}
}
if (count($uriTemplateVars)) {
$uriTemplateParser = new URI_Template_Parser($requestUrl);
$requestUrl = $uriTemplateParser->expand($uriTemplateVars);
}
//FIXME work around for the the uri template lib which url encodes
// the @'s & confuses our servers.
$requestUrl = str_replace('%40', '@', $requestUrl);
if (count($queryVars)) {
$requestUrl .= '?' . implode($queryVars, '&');
}
return $requestUrl;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/io/apiREST.php | PHP | asf20 | 5,324 |
<?php
/**
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once 'io/apiHttpRequest.php';
require_once 'io/apiCurlIO.php';
require_once 'io/apiREST.php';
require_once 'io/apiRPC.php';
/**
* Abstract IO class
*
* @author Chris Chabot <chabotc@google.com>
*/
interface apiIO {
/**
* An utility function that first calls $this->auth->sign($request) and then executes makeRequest()
* on that signed request. Used for when a request should be authenticated
* @param apiHttpRequest $request
* @return apiHttpRequest $request
*/
public function authenticatedRequest(apiHttpRequest $request);
/**
* Executes a apIHttpRequest and returns the resulting populated httpRequest
* @param apiHttpRequest $request
* @return apiHttpRequest $request
*/
public function makeRequest(apiHttpRequest $request);
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/io/apiIO.php | PHP | asf20 | 1,383 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once 'service/apiServiceResource.php';
require_once 'service/apiServiceRequest.php';
require_once 'service/apiBatch.php';
/**
* This class parses the service end points of the api discovery document and constructs
* serviceResource variables for all of them.
*
* For instance when calling with the service document for Plus, it will create apiServiceResource's
* for $this->activities, $this->comments, $this->people, etc.
*
* @author Chris Chabot <chabotc@google.com>
*
*/
class apiService {
public $version = null;
public $restBasePath;
public $rpcPath;
public $resource = null;
public function __construct($serviceName, $discoveryDocument) {
global $apiConfig;
if (!isset($discoveryDocument['version']) || !isset($discoveryDocument['restBasePath']) || !isset($discoveryDocument['rpcPath'])) {
throw new apiServiceException("Invalid discovery document");
}
$this->version = $discoveryDocument['version'];
$this->restBasePath = $apiConfig['basePath'] . $discoveryDocument['restBasePath'];
$this->rpcPath = $apiConfig['basePath'] . $discoveryDocument['rpcPath'];
foreach ($discoveryDocument['resources'] as $resourceName => $resourceTypes) {
$this->$resourceName = new apiServiceResource($this, $serviceName, $resourceName, $resourceTypes);
}
}
/**
* @return string $restBasePath
*/
public function getRestBasePath() {
return $this->restBasePath;
}
/**
* @return string $rpcPath
*/
public function getRpcPath() {
return $this->rpcPath;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/service/apiService.php | PHP | asf20 | 2,151 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal representation of a Google API request, used by the apiServiceResource class to
* construct API function calls and passing them to the IO layer who knows how to execute
* the request
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*
*/
class apiServiceRequest {
public $restBasePath;
public $restPath;
public $rpcPath;
public $rpcName;
public $httpMethod;
public $parameters;
public $postBody;
public $batchKey;
public $contentType;
/**
* @param string $restBasePath
* @param string $rpcPath
* @param string $restPath
* @param string $rpcName
* @param string $httpMethod
* @param array $parameters
* @param string $postBody
*/
public function __construct($restBasePath, $rpcPath, $restPath, $rpcName, $httpMethod, $parameters, $postBody = null) {
if (substr($restBasePath, 0, 4) == 'http') {
$this->restBasePath = $restBasePath;
} else {
global $apiConfig;
$this->restBasePath = $apiConfig['basePath'] . $restBasePath;
}
$this->restPath = $restPath;
$this->rpcPath = $rpcPath;
$this->rpcName = $rpcName;
$this->httpMethod = $httpMethod;
$this->parameters = $parameters;
$this->postBody = $postBody;
}
/**
* @return string $postBody
*/
public function getPostBody() {
return $this->postBody;
}
/**
* @param string $postBody The post body.
*/
public function setPostBody($postBody) {
$this->postBody = $postBody;
}
/**
* @return string restBasePath
*/
public function getRestBasePath() {
return $this->restBasePath;
}
/**
* @return string restPath
*/
public function getRestPath() {
return $this->restPath;
}
/**
* @return string $rpcPath
*/
public function getRpcPath() {
return $this->rpcPath;
}
/**
* @return string $rpcName
*/
public function getRpcName() {
return $this->rpcName;
}
/**
* @return string $httpMethod
*/
public function getHttpMethod() {
return $this->httpMethod;
}
/**
* @return array $parameters
*/
public function getParameters() {
return $this->parameters;
}
/**
* @return string $batchKey
*/
public function getBatchKey() {
return $this->batchKey;
}
/**
* @param $batchKey the $batchKey to set
*/
public function setBatchKey($batchKey) {
$this->batchKey = $batchKey;
}
public function setContentType($type) {
$this->contentType = $type;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/service/apiServiceRequest.php | PHP | asf20 | 3,111 |
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Collection of static utility methods used for convenience across
* the client library.
*
* @author Chirag Shah <chirags@google.com>
*/
class apiUtils {
public static function urlSafeB64Encode($data) {
$b64 = base64_encode($data);
$b64 = str_replace(array('+', '/', '\r', '\n', '='),
array('-', '_'),
$b64);
return $b64;
}
public static function urlSafeB64Decode($b64) {
$b64 = str_replace(array('-', '_'),
array('+', '/'),
$b64);
return base64_decode($b64);
}
/**
* Misc function used to count the number of bytes in a post body, in the world of multi-byte chars
* and the unpredictability of strlen/mb_strlen/sizeof, this is the only way to do that in a sane
* manner at the moment.
*
* This algorithm was originally developed for the
* Solar Framework by Paul M. Jones
*
* @link http://solarphp.com/
* @link http://svn.solarphp.com/core/trunk/Solar/Json.php
* @link http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Json/Decoder.php
* @param string $str
* @return int The number of bytes in a string.
*/
static public function getStrLen($str) {
$strlenVar = strlen($str);
$d = $ret = 0;
for ($count = 0; $count < $strlenVar; ++ $count) {
$ordinalValue = ord($str{$ret});
switch (true) {
case (($ordinalValue >= 0x20) && ($ordinalValue <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ret ++;
break;
case (($ordinalValue & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$ret += 2;
break;
case (($ordinalValue & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$ret += 3;
break;
case (($ordinalValue & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$ret += 4;
break;
case (($ordinalValue & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$ret += 5;
break;
case (($ordinalValue & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$ret += 6;
break;
default:
$ret ++;
}
}
return $ret;
}
/**
* Normalize all keys in an array to lower-case.
* @param array $arr
* @return array Normalized array.
*/
public static function normalize($arr) {
if (!is_array($arr)) {
return array();
}
$normalized = array();
foreach ($arr as $key => $val) {
$normalized[strtolower($key)] = $val;
}
return $normalized;
}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/service/apiUtils.php | PHP | asf20 | 3,700 |
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class defines attributes, valid values, and usage which is generated from
* a given json schema. http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
*
* @author Chirag Shah <chirags@google.com>
*
*/
class apiModel {
public function __construct( /* polymorphic */ ) {
if (func_num_args() == 1 && is_array(func_get_arg(0))) {
// Initialize the model with the array's contents.
$array = func_get_arg(0);
$this->mapTypes($array);
}
}
/**
* Initialize this object's properties from an array.
*
* @param array Used to seed this object's properties.
* @return void
*/
private function mapTypes($array) {
foreach ($array as $key => $val) {
$this->$key = $val;
$keyTypeName = "__$key" . 'Type';
$keyDataType = "__$key" . 'DataType';
if ($this->useObjects() && property_exists($this, $keyTypeName)) {
if ($this->isAssociativeArray($val)) {
if (isset($this->$keyDataType) && 'map' == $this->$keyDataType) {
foreach($val as $arrayKey => $arrayItem) {
$val[$arrayKey] = $this->createObjectFromName($keyTypeName, $arrayItem);
}
$this->$key = $val;
} else {
$this->$key = $this->createObjectFromName($keyTypeName, $val);
}
} else if (is_array($val)) {
$arrayObject = array();
foreach ($val as $arrayIndex => $arrayItem) {
$arrayObject[$arrayIndex] = $this->createObjectFromName($keyTypeName, $arrayItem);
}
$this->$key = $arrayObject;
}
}
}
}
/**
* Returns true only if the array is associative.
* @param array $array
* @return bool True if the array is associative.
*/
private function isAssociativeArray($array) {
if (!is_array($array)) {
return false;
}
$keys = array_keys($array);
foreach($keys as $key) {
if (is_string($key)) {
return true;
}
}
return false;
}
/**
* Given a variable name, discover its type.
*
* @param $name
* @param $item
* @return object The object from the item.
*/
private function createObjectFromName($name, $item) {
$type = $this->$name;
return new $type($item);
}
protected function useObjects() {
global $apiConfig;
return (isset($apiConfig['use_objects']) && $apiConfig['use_objects']);
}
/**
* Verify if $obj is an array.
* @throws apiException Thrown if $obj isn't an array.
* @param array $obj Items that should be validated.
* @param string $type Array items should be of this type.
* @param string $method Method expecting an array as an argument.
*/
protected function assertIsArray($obj, $type, $method) {
if ($obj && !is_array($obj)) {
throw new apiException("Incorrect parameter type passed to $method(), expected an"
. " array containing items of type $type.");
}
}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/service/apiModel.php | PHP | asf20 | 3,551 |
<?php
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Chirag Shah <chirags@google.com>
*
*/
class apiMediaFileUpload {
const UPLOAD_MEDIA_TYPE = 'media';
const UPLOAD_MULTIPART_TYPE = 'multipart';
const UPLOAD_RESUMABLE_TYPE = 'resumable';
/** @var string $mimeType */
public $mimeType;
/** @var string $data */
public $data;
/** @var bool $resumable */
public $resumable;
/** @var int $chunkSize */
public $chunkSize;
/** @var int $size */
public $size;
/** @var string $resumeUri */
public $resumeUri;
/** @var int $progress */
public $progress;
/**
* @param $mimeType string
* @param $data string The bytes you want to upload.
* @param $resumable bool
* @param bool $chunkSize File will be uploaded in chunks of this many bytes.
* only used if resumable=True
*/
public function __construct($mimeType, $data, $resumable=false, $chunkSize=false) {
$this->mimeType = $mimeType;
$this->data = $data;
$this->size = strlen($this->data);
$this->resumable = $resumable;
if(!$chunkSize) {
$this->chunkSize = 256 * 1024;
}
$this->progress = 0;
}
/**
* @static
* @param $meta
* @param $params
* @return array|bool
*/
public static function process($meta, &$params) {
$payload = array();
$meta = is_string($meta) ? json_decode($meta, true) : $meta;
$uploadType = self::getUploadType($meta, $payload, $params);
if (!$uploadType) {
// Process as a normal API request.
return false;
}
// Process as a media upload request.
$params['uploadType'] = array(
'type' => 'string',
'location' => 'query',
'value' => $uploadType,
);
if (isset($params['file'])) {
// This is a standard file upload with curl.
$file = $params['file']['value'];
unset($params['file']);
return self::processFileUpload($file);
}
$mimeType = isset($params['mimeType'])
? $params['mimeType']['value']
: false;
unset($params['mimeType']);
$data = isset($params['data'])
? $params['data']['value']
: false;
unset($params['data']);
if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
$payload['content-type'] = $mimeType;
} elseif (self::UPLOAD_MEDIA_TYPE == $uploadType) {
// This is a simple media upload.
$payload['content-type'] = $mimeType;
$payload['postBody'] = $data;
}
elseif (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
// This is a multipart/related upload.
$boundary = isset($params['boundary']['value']) ? $params['boundary']['value'] : mt_rand();
$boundary = str_replace('"', '', $boundary);
$payload['content-type'] = 'multipart/related; boundary=' . $boundary;
$related = "--$boundary\r\n";
$related .= "Content-Type: application/json; charset=UTF-8\r\n";
$related .= "\r\n" . json_encode($meta) . "\r\n";
$related .= "--$boundary\r\n";
$related .= "Content-Type: $mimeType\r\n";
$related .= "Content-Transfer-Encoding: base64\r\n";
$related .= "\r\n" . base64_encode($data) . "\r\n";
$related .= "--$boundary--";
$payload['postBody'] = $related;
}
return $payload;
}
/**
* Process standard file uploads.
* @param $file
* @internal param $fileName
* @return array Inclues the processed file name.
* @visible For testing.
*/
public static function processFileUpload($file) {
if (!$file) return array();
if (substr($file, 0, 1) != '@') {
$file = '@' . $file;
}
// This is a standard file upload with curl.
return array('postBody' => array('file' => $file));
}
/**
* Valid upload types:
* - resumable (UPLOAD_RESUMABLE_TYPE)
* - media (UPLOAD_MEDIA_TYPE)
* - multipart (UPLOAD_MULTIPART_TYPE)
* - none (false)
* @param $meta
* @param $payload
* @param $params
* @return bool|string
*/
public static function getUploadType($meta, &$payload, &$params) {
if (isset($params['mediaUpload'])
&& get_class($params['mediaUpload']['value']) == 'apiMediaFileUpload') {
$upload = $params['mediaUpload']['value'];
unset($params['mediaUpload']);
$payload['content-type'] = $upload->mimeType;
if (isset($upload->resumable) && $upload->resumable) {
return self::UPLOAD_RESUMABLE_TYPE;
}
}
// Allow the developer to override the upload type.
if (isset($params['uploadType'])) {
return $params['uploadType']['value'];
}
$data = isset($params['data']['value'])
? $params['data']['value'] : false;
if (false == $data && false == isset($params['file'])) {
// No upload data available.
return false;
}
if (isset($params['file'])) {
return self::UPLOAD_MEDIA_TYPE;
}
if (false == $meta) {
return self::UPLOAD_MEDIA_TYPE;
}
return self::UPLOAD_MULTIPART_TYPE;
}
public function nextChunk(apiServiceRequest $req) {
if (false == $this->resumeUri) {
$this->resumeUri = $this->getResumeUri($req);
}
$data = substr($this->data, $this->progress, $this->chunkSize);
$lastBytePos = $this->progress + strlen($data) - 1;
$headers = array(
'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
'content-type' => $req->contentType,
'content-length' => $this->chunkSize,
'expect' => '',
);
$httpRequest = new apiHttpRequest($this->resumeUri, 'PUT', $headers, $data);
$response = apiClient::$io->authenticatedRequest($httpRequest);
$code = $response->getResponseHttpCode();
if (308 == $code) {
$range = explode('-', $response->getResponseHeader('range'));
$this->progress = $range[1] + 1;
return false;
} else {
return apiREST::decodeHttpResponse($response);
}
}
private function getResumeUri(apiServiceRequest $req) {
$result = null;
$postBody = $req->getPostBody();
$url = apiREST::createRequestUri(
$req->getRestBasePath(),
$req->getRestPath(),
$req->getParameters()
);
$httpRequest = new apiHttpRequest(
$url, $req->getHttpMethod(), null, $postBody);
if ($postBody) {
$httpRequest->setRequestHeaders(array(
'content-type' => 'application/json; charset=UTF-8',
'content-length' => apiUtils::getStrLen($postBody),
'x-upload-content-type' => $this->mimeType,
'expect' => '',
));
}
$response = apiClient::$io->authenticatedRequest($httpRequest);
$location = $response->getResponseHeader('location');
$code = $response->getResponseHttpCode();
if (200 == $code && true == $location) {
return $location;
}
throw new apiException("Failed to start the resumable upload");
}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/service/apiMediaFileUpload.php | PHP | asf20 | 7,367 |
<?php
/**
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Implements the actual methods/resources of the discovered Google API using magic function
* calling overloading (__call()), which on call will see if the method name (plus.activities.list)
* is available in this service, and if so construct an apiServiceRequest representing it.
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*
*/
class apiServiceResource {
// Valid query parameters that work, but don't appear in discovery.
private $stackParameters = array(
'alt' => array('type' => 'string', 'location' => 'query'),
'boundary' => array('type' => 'string', 'location' => 'query'),
'fields' => array('type' => 'string', 'location' => 'query'),
'trace' => array('type' => 'string', 'location' => 'query'),
'userIp' => array('type' => 'string', 'location' => 'query'),
'userip' => array('type' => 'string', 'location' => 'query'),
'file' => array('type' => 'complex', 'location' => 'body'),
'data' => array('type' => 'string', 'location' => 'body'),
'mimeType' => array('type' => 'string', 'location' => 'header'),
'uploadType' => array('type' => 'string', 'location' => 'query'),
'mediaUpload' => array('type' => 'complex', 'location' => 'query'),
);
/** @var apiService $service */
private $service;
/** @var string $serviceName */
private $serviceName;
/** @var string $resourceName */
private $resourceName;
/** @var array $methods */
private $methods;
public function __construct($service, $serviceName, $resourceName, $resource) {
$this->service = $service;
$this->serviceName = $serviceName;
$this->resourceName = $resourceName;
$this->methods = isset($resource['methods']) ? $resource['methods'] : array($resourceName => $resource);
}
/**
* @param $name
* @param $arguments
* @return apiServiceRequest|array
* @throws apiException
*/
public function __call($name, $arguments) {
if (count($arguments) != 1 && count($arguments) != 2) {
throw new apiException("client method calls expect 1 or 2 parameter (\$client->plus->activities->list(array('userId' => 'me'))");
}
if (! is_array($arguments[0])) {
throw new apiException("client method parameter should be an array (\$client->plus->activities->list(array('userId' => 'me'))");
}
$batchKey = false;
if (isset($arguments[1])) {
if (! is_string($arguments[1])) {
throw new apiException("The batch key parameter should be a string (\$client->plus->activities->list( array('userId' => 'me'), 'batchKey'))");
}
$batchKey = $arguments[1];
}
if (! isset($this->methods[$name])) {
throw new apiException("Unknown function: {$this->serviceName}->{$this->resourceName}->{$name}()");
}
$method = $this->methods[$name];
$parameters = $arguments[0];
// postBody is a special case since it's not defined in the discovery document as parameter, but we abuse the param entry for storing it
$postBody = null;
if (isset($parameters['postBody'])) {
if (is_object($parameters['postBody'])) {
$this->stripNull($parameters['postBody']);
}
// Some APIs require the postBody to be set under the data key.
if (is_array($parameters['postBody']) && 'latitude' == $this->serviceName) {
if (!isset($parameters['postBody']['data'])) {
$rawBody = $parameters['postBody'];
unset($parameters['postBody']);
$parameters['postBody']['data'] = $rawBody;
}
}
$postBody = is_array($parameters['postBody']) || is_object($parameters['postBody'])
? json_encode($parameters['postBody'])
: $parameters['postBody'];
unset($parameters['postBody']);
if (isset($parameters['optParams'])) {
$optParams = $parameters['optParams'];
unset($parameters['optParams']);
$parameters = array_merge($parameters, $optParams);
}
}
if (!isset($method['parameters'])) {
$method['parameters'] = array();
}
$method['parameters'] = array_merge($method['parameters'], $this->stackParameters);
foreach ($parameters as $key => $val) {
if ($key != 'postBody' && ! isset($method['parameters'][$key])) {
throw new apiException("($name) unknown parameter: '$key'");
}
}
if (isset($method['parameters'])) {
foreach ($method['parameters'] as $paramName => $paramSpec) {
if (isset($paramSpec['required']) && $paramSpec['required'] && ! isset($parameters[$paramName])) {
throw new apiException("($name) missing required param: '$paramName'");
}
if (isset($parameters[$paramName])) {
$value = $parameters[$paramName];
$parameters[$paramName] = $paramSpec;
$parameters[$paramName]['value'] = $value;
unset($parameters[$paramName]['required']);
} else {
unset($parameters[$paramName]);
}
}
}
// Discovery v1.0 puts the canonical method id under the 'id' field.
if (! isset($method['id'])) {
$method['id'] = $method['rpcMethod'];
}
// Discovery v1.0 puts the canonical path under the 'path' field.
if (! isset($method['path'])) {
$method['path'] = $method['restPath'];
}
$restBasePath = $this->service->restBasePath;
// Process Media Request
$contentType = false;
if (isset($method['mediaUpload'])) {
$media = apiMediaFileUpload::process($postBody, $parameters);
if ($media) {
$contentType = isset($media['content-type']) ? $media['content-type']: null;
$postBody = isset($media['postBody']) ? $media['postBody'] : null;
$restBasePath = $method['mediaUpload']['protocols']['simple']['path'];
$method['path'] = '';
}
}
$request = new apiServiceRequest(
$restBasePath,
$this->service->rpcPath,
$method['path'],
$method['id'],
$method['httpMethod'],
$parameters, $postBody
);
$request->setContentType($contentType);
// Terminate immediatly if this is a resumable request.
if (isset($parameters['uploadType']['value'])
&& 'resumable' == $parameters['uploadType']['value']) {
return $request;
}
if ($batchKey) {
$request->setBatchKey($batchKey);
return $request;
} else {
return apiREST::execute($request);
}
}
protected function useObjects() {
global $apiConfig;
return (isset($apiConfig['use_objects']) && $apiConfig['use_objects']);
}
protected function stripNull(&$o) {
$o = (array) $o;
foreach ($o as $k => $v) {
if ($v === null || strstr($k, "\0*\0__")) {
unset($o[$k]);
}
elseif (is_object($v) || is_array($v)) {
$this->stripNull($o[$k]);
}
}
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/service/apiServiceResource.php | PHP | asf20 | 7,450 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Wrapper for the (experimental!) JSON-RPC protocol, for production use regular REST calls instead
*
* @author Chris Chabot <chabotc@google.com>
*/
class apiBatch {
/**
* Execute one or multiple Google API requests, takes one or multiple requests as param
* Example usage:
* $ret = apiBatch::execute(
* $apiClient->activities->list(array('@public', '@me'), 'listActivitiesKey'),
* $apiClient->people->get(array('userId' => '@me'), 'getPeopleKey')
* );
* print_r($ret['getPeopleKey']);
*/
static public function execute( /* polymorphic */) {
$requests = func_get_args();
return apiRPC::execute($requests);
}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/service/apiBatch.php | PHP | asf20 | 1,272 |
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "apiPemVerifier.php";
/**
* Verifies signatures.
*
* @author Brian Eaton <beaton@google.com>
*/
abstract class apiVerifier {
/**
* Checks a signature, returns true if the signature is correct,
* false otherwise.
*/
abstract public function verify($data, $signature);
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiVerifier.php | PHP | asf20 | 902 |
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Signs data.
*
* Only used for testing.
*
* @author Brian Eaton <beaton@google.com>
*/
class apiP12Signer extends apiSigner {
// OpenSSL private key resource
private $privateKey;
// Creates a new signer from a .p12 file.
function __construct($p12file, $password) {
if (!function_exists('openssl_x509_read')) {
throw new Exception(
'The Google PHP API library needs the openssl PHP extension');
}
// This throws on error
$p12 = file_get_contents($p12file);
$certs = array();
if (!openssl_pkcs12_read($p12, $certs, $password)) {
throw new apiAuthException("Unable to parse $p12file. " .
"Is this a .p12 file? Is the password correct? OpenSSL error: " .
openssl_error_string());
}
// TODO(beaton): is this part of the contract for the openssl_pkcs12_read
// method? What happens if there are multiple private keys? Do we care?
if (!array_key_exists("pkey", $certs) || !$certs["pkey"]) {
throw new apiAuthException("No private key found in p12 file $p12file");
}
$this->privateKey = openssl_pkey_get_private($certs["pkey"]);
if (!$this->privateKey) {
throw new apiAuthException("Unable to load private key in $p12file");
}
}
function __destruct() {
if ($this->privateKey) {
openssl_pkey_free($this->privateKey);
}
}
function sign($data) {
if (!openssl_sign($data, $signature, $this->privateKey, "sha256")) {
throw new apiAuthException("Unable to sign data");
}
return $signature;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiP12Signer.php | PHP | asf20 | 2,161 |
<?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "apiVerifier.php";
require_once "apiLoginTicket.php";
require_once "service/apiUtils.php";
/**
* Authentication class that deals with the OAuth 2 web-server authentication flow
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*
*/
class apiOAuth2 extends apiAuth {
public $clientId;
public $clientSecret;
public $developerKey;
public $accessToken;
public $redirectUri;
public $state;
public $accessType = 'offline';
public $approvalPrompt = 'force';
const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token';
const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
const OAUTH2_FEDERATED_SIGNON_CERTS_URL = 'https://www.googleapis.com/oauth2/v1/certs';
const CLOCK_SKEW_SECS = 300; // five minutes in seconds
const AUTH_TOKEN_LIFETIME_SECS = 300; // five minutes in seconds
const MAX_TOKEN_LIFETIME_SECS = 86400; // one day in seconds
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller (which is done by calling authenticate()).
*/
public function __construct() {
global $apiConfig;
if (! empty($apiConfig['developer_key'])) {
$this->developerKey = $apiConfig['developer_key'];
}
if (! empty($apiConfig['oauth2_client_id'])) {
$this->clientId = $apiConfig['oauth2_client_id'];
}
if (! empty($apiConfig['oauth2_client_secret'])) {
$this->clientSecret = $apiConfig['oauth2_client_secret'];
}
if (! empty($apiConfig['oauth2_redirect_uri'])) {
$this->redirectUri = $apiConfig['oauth2_redirect_uri'];
}
if (! empty($apiConfig['oauth2_access_type'])) {
$this->accessType = $apiConfig['oauth2_access_type'];
}
if (! empty($apiConfig['oauth2_approval_prompt'])) {
$this->approvalPrompt = $apiConfig['oauth2_approval_prompt'];
}
}
/**
* @param $service
* @return string
* @throws apiAuthException
*/
public function authenticate($service) {
if (isset($_GET['code'])) {
// We got here from the redirect from a successful authorization grant, fetch the access token
$request = apiClient::$io->makeRequest(new apiHttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
'code' => $_GET['code'],
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUri,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
)));
if ($request->getResponseHttpCode() == 200) {
$this->setAccessToken($request->getResponseBody());
$this->accessToken['created'] = time();
return $this->getAccessToken();
} else {
$response = $request->getResponseBody();
$decodedResponse = json_decode($response, true);
if ($decodedResponse != $response && $decodedResponse != null && $decodedResponse['error']) {
$response = $decodedResponse['error'];
}
throw new apiAuthException("Error fetching OAuth2 access token, message: '$response'", $request->getResponseHttpCode());
}
}
$authUrl = $this->createAuthUrl($service['scope']);
header('Location: ' . $authUrl);
}
/**
* Create a URL to obtain user authorization.
* The authorization endpoint allows the user to first
* authenticate, and then grant/deny the access request.
* @param string $scope The scope is expressed as a list of space-delimited strings.
* @return string
*/
public function createAuthUrl($scope) {
$params = array(
'response_type=code',
'redirect_uri=' . urlencode($this->redirectUri),
'client_id=' . urlencode($this->clientId),
'scope=' . urlencode($scope),
'access_type=' . urlencode($this->accessType),
'approval_prompt=' . urlencode($this->approvalPrompt)
);
if (isset($this->state)) {
$params[] = 'state=' . urlencode($this->state);
}
$params = implode('&', $params);
return self::OAUTH2_AUTH_URL . "?$params";
}
/**
* @param $accessToken
* @throws apiAuthException Thrown when $accessToken is invalid.
*/
public function setAccessToken($accessToken) {
$accessToken = json_decode($accessToken, true);
if ($accessToken == null) {
throw new apiAuthException('Could not json decode the access token');
}
if (! isset($accessToken['access_token'])) {
throw new apiAuthException("Invalid token format");
}
$this->accessToken = $accessToken;
}
public function getAccessToken() {
return json_encode($this->accessToken);
}
public function setDeveloperKey($developerKey) {
$this->developerKey = $developerKey;
}
public function setState($state) {
$this->state = $state;
}
public function setAccessType($accessType) {
$this->accessType = $accessType;
}
public function setApprovalPrompt($approvalPrompt) {
$this->approvalPrompt = $approvalPrompt;
}
/**
* Include an accessToken in a given apiHttpRequest.
* @param apiHttpRequest $request
* @return apiHttpRequest
* @throws apiAuthException
*/
public function sign(apiHttpRequest $request) {
// add the developer key to the request before signing it
if ($this->developerKey) {
$requestUrl = $request->getUrl();
$requestUrl .= (strpos($request->getUrl(), '?') === false) ? '?' : '&';
$requestUrl .= 'key=' . urlencode($this->developerKey);
$request->setUrl($requestUrl);
}
// Cannot sign the request without an OAuth access token.
if (null == $this->accessToken) {
return $request;
}
// If the token is set to expire in the next 30 seconds (or has already
// expired), refresh it and set the new token.
$expired = ($this->accessToken['created'] + ($this->accessToken['expires_in'] - 30)) < time();
if ($expired) {
if (! array_key_exists('refresh_token', $this->accessToken)) {
throw new apiAuthException("The OAuth 2.0 access token has expired, "
. "and a refresh token is not available. Refresh tokens are not "
. "returned for responses that were auto-approved.");
}
$this->refreshToken($this->accessToken['refresh_token']);
}
// Add the OAuth2 header to the request
$request->setRequestHeaders(
array('Authorization' => 'Bearer ' . $this->accessToken['access_token'])
);
return $request;
}
/**
* Fetches a fresh access token with the given refresh token.
* @param string $refreshToken
* @return void
*/
public function refreshToken($refreshToken) {
$params = array(
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'refresh_token' => $refreshToken,
'grant_type' => 'refresh_token'
);
$request = apiClient::$io->makeRequest(
new apiHttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), $params));
$code = $request->getResponseHttpCode();
$body = $request->getResponseBody();
if ($code == 200) {
$token = json_decode($body, true);
if ($token == null) {
throw new apiAuthException("Could not json decode the access token");
}
if (! isset($token['access_token']) || ! isset($token['expires_in'])) {
throw new apiAuthException("Invalid token format");
}
$this->accessToken['access_token'] = $token['access_token'];
$this->accessToken['expires_in'] = $token['expires_in'];
$this->accessToken['created'] = time();
} else {
throw new apiAuthException("Error refreshing the OAuth2 token, message: '$body'", $code);
}
}
/**
* Revoke an OAuth2 access token or refresh token. This method will revoke the current access
* token, if a token isn't provided.
* @throws apiAuthException
* @param string|null $token The token (access token or a refresh token) that should be revoked.
* @return boolean Returns True if the revocation was successful, otherwise False.
*/
public function revokeToken($token = null) {
if (!$token) {
$token = $this->accessToken['access_token'];
}
$request = new apiHttpRequest(self::OAUTH2_REVOKE_URI, 'POST', array(), "token=$token");
$response = apiClient::$io->makeRequest($request);
$code = $response->getResponseHttpCode();
if ($code == 200) {
$this->accessToken = null;
return true;
}
return false;
}
// Gets federated sign-on certificates to use for verifying identity tokens.
// Returns certs as array structure, where keys are key ids, and values
// are PEM encoded certificates.
private function getFederatedSignOnCerts() {
// This relies on makeRequest caching certificate responses.
$request = apiClient::$io->makeRequest(new apiHttpRequest(
self::OAUTH2_FEDERATED_SIGNON_CERTS_URL));
if ($request->getResponseHttpCode() == 200) {
$certs = json_decode($request->getResponseBody(), true);
if ($certs) {
return $certs;
}
}
throw new apiAuthException(
"Failed to retrieve verification certificates: '" .
$request->getResponseBody() . "'.",
$request->getResponseHttpCode());
}
/**
* Verifies an id token and returns the authenticated apiLoginTicket.
* Throws an exception if the id token is not valid.
* The audience parameter can be used to control which id tokens are
* accepted. By default, the id token must have been issued to this OAuth2 client.
*
* @param $id_token
* @param $audience
* @return apiLoginTicket
*/
public function verifyIdToken($id_token = null, $audience = null) {
if (!$id_token) {
$id_token = $this->accessToken['id_token'];
}
$certs = $this->getFederatedSignonCerts();
if (!$audience) {
$audience = $this->clientId;
}
return $this->verifySignedJwtWithCerts($id_token, $certs, $audience);
}
// Verifies the id token, returns the verified token contents.
// Visible for testing.
function verifySignedJwtWithCerts($jwt, $certs, $required_audience) {
$segments = explode(".", $jwt);
if (count($segments) != 3) {
throw new apiAuthException("Wrong number of segments in token: $jwt");
}
$signed = $segments[0] . "." . $segments[1];
$signature = apiUtils::urlSafeB64Decode($segments[2]);
// Parse envelope.
$envelope = json_decode(apiUtils::urlSafeB64Decode($segments[0]), true);
if (!$envelope) {
throw new apiAuthException("Can't parse token envelope: " . $segments[0]);
}
// Parse token
$json_body = apiUtils::urlSafeB64Decode($segments[1]);
$payload = json_decode($json_body, true);
if (!$payload) {
throw new apiAuthException("Can't parse token payload: " . $segments[1]);
}
// Check signature
$verified = false;
foreach ($certs as $keyName => $pem) {
$public_key = new apiPemVerifier($pem);
if ($public_key->verify($signed, $signature)) {
$verified = true;
break;
}
}
if (!$verified) {
throw new apiAuthException("Invalid token signature: $jwt");
}
// Check issued-at timestamp
$iat = 0;
if (array_key_exists("iat", $payload)) {
$iat = $payload["iat"];
}
if (!$iat) {
throw new apiAuthException("No issue time in token: $json_body");
}
$earliest = $iat - self::CLOCK_SKEW_SECS;
// Check expiration timestamp
$now = time();
$exp = 0;
if (array_key_exists("exp", $payload)) {
$exp = $payload["exp"];
}
if (!$exp) {
throw new apiAuthException("No expiration time in token: $json_body");
}
if ($exp >= $now + self::MAX_TOKEN_LIFETIME_SECS) {
throw new apiAuthException(
"Expiration time too far in future: $json_body");
}
$latest = $exp + self::CLOCK_SKEW_SECS;
if ($now < $earliest) {
throw new apiAuthException(
"Token used too early, $now < $earliest: $json_body");
}
if ($now > $latest) {
throw new apiAuthException(
"Token used too late, $now > $latest: $json_body");
}
// TODO(beaton): check issuer field?
// Check audience
$aud = $payload["aud"];
if ($aud != $required_audience) {
throw new apiAuthException("Wrong recipient, $aud != $required_audience: $json_body");
}
// All good.
return new apiLoginTicket($envelope, $payload);
}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiOAuth2.php | PHP | asf20 | 13,131 |
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Class to hold information about an authenticated login.
*
* @author Brian Eaton <beaton@google.com>
*/
class apiLoginTicket {
const USER_ATTR = "id";
// Information from id token envelope.
private $envelope;
// Information from id token payload.
private $payload;
/**
* Creates a user based on the supplied token.
*
* envelope: header from a verified authentication token.
* payload: information from a verified authentication token.
*/
public function __construct($envelope, $payload) {
$this->envelope = $envelope;
$this->payload = $payload;
}
/**
* Returns the numeric identifier for the user.
*/
public function getUserId() {
if (array_key_exists(self::USER_ATTR, $this->payload)) {
return $this->payload[self::USER_ATTR];
}
throw new apiAuthException("No user_id in token");
}
/**
* Returns attributes from the login ticket. This can contain
* various information about the user session.
*/
public function getAttributes() {
return array("envelope" => $this->envelope, "payload" => $this->payload);
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiLoginTicket.php | PHP | asf20 | 1,714 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Do-nothing authentication implementation, use this if you want to make un-authenticated calls
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*/
class apiAuthNone extends apiAuth {
public $key = null;
public function __construct() {
global $apiConfig;
if (!empty($apiConfig['developer_key'])) {
$this->setDeveloperKey($apiConfig['developer_key']);
}
}
public function setDeveloperKey($key) {$this->key = $key;}
public function authenticate($service) {/*noop*/}
public function setAccessToken($accessToken) {/* noop*/}
public function getAccessToken() {return null;}
public function createAuthUrl($scope) {return null;}
public function refreshToken($refreshToken) {/* noop*/}
public function revokeToken() {/* noop*/}
public function sign(apiHttpRequest $request) {
if ($this->key) {
$request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&')
. 'key='.urlencode($this->key));
}
return $request;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiAuthNone.php | PHP | asf20 | 1,659 |
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "apiP12Signer.php";
/**
* Signs data.
*
* @author Brian Eaton <beaton@google.com>
*/
abstract class apiSigner {
/**
* Signs data, returns the signature as binary data.
*/
abstract public function sign($data);
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiSigner.php | PHP | asf20 | 841 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "apiAuthNone.php";
require_once "apiOAuth.php";
require_once "apiOAuth2.php";
/**
* Abstract class for the Authentication in the API client
* @author Chris Chabot <chabotc@google.com>
*
*/
abstract class apiAuth {
abstract public function authenticate($service);
abstract public function sign(apiHttpRequest $request);
abstract public function createAuthUrl($scope);
abstract public function getAccessToken();
abstract public function setAccessToken($accessToken);
abstract public function setDeveloperKey($developerKey);
abstract public function refreshToken($refreshToken);
abstract public function revokeToken();
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiAuth.php | PHP | asf20 | 1,255 |
<?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once "external/OAuth.php";
/**
* Authentication class that deals with 3-Legged OAuth 1.0a authentication
*
* This class uses the OAuth 1.0a spec which has a slightly different work flow in
* how callback urls, request & access tokens are dealt with to prevent a possible
* man in the middle attack.
*
* @author Chris Chabot <chabotc@google.com>
*
*/
class apiOAuth extends apiAuth {
public $cacheKey;
protected $consumerToken;
protected $accessToken;
protected $privateKeyFile;
protected $developerKey;
public $service;
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller.
*/
public function __construct() {
global $apiConfig;
if (!empty($apiConfig['developer_key'])) {
$this->setDeveloperKey($apiConfig['developer_key']);
}
$this->consumerToken = new apiClientOAuthConsumer($apiConfig['oauth_consumer_key'], $apiConfig['oauth_consumer_secret'], NULL);
$this->signatureMethod = new apiClientOAuthSignatureMethod_HMAC_SHA1();
$this->cacheKey = 'OAuth:' . $apiConfig['oauth_consumer_key']; // Scope data to the local user as well, or else multiple local users will share the same OAuth credentials.
}
/**
* The 3 legged oauth class needs a way to store the access key and token
* it uses the apiCache class to do so.
*
* Constructing this class will initiate the 3 legged oauth work flow, including redirecting
* to the OAuth provider's site if required(!)
*
* @param string $consumerKey
* @param string $consumerSecret
* @return apiOAuth3Legged the logged-in provider instance
*/
public function authenticate($service) {
global $apiConfig;
$this->service = $service;
$this->service['authorization_token_url'] .= '?scope=' . apiClientOAuthUtil::urlencodeRFC3986($service['scope']) . '&domain=' . apiClientOAuthUtil::urlencodeRFC3986($apiConfig['site_name']) . '&oauth_token=';
if (isset($_GET['oauth_verifier']) && isset($_GET['oauth_token']) && isset($_GET['uid'])) {
$uid = $_GET['uid'];
$secret = apiClient::$cache->get($this->cacheKey.":nonce:" . $uid);
apiClient::$cache->delete($this->cacheKey.":nonce:" . $uid);
$token = $this->upgradeRequestToken($_GET['oauth_token'], $secret, $_GET['oauth_verifier']);
return json_encode($token);
} else {
// Initialize the OAuth dance, first request a request token, then kick the client to the authorize URL
// First we store the current URL in our cache, so that when the oauth dance is completed we can return there
$callbackUrl = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$uid = uniqid();
$token = $this->obtainRequestToken($callbackUrl, $uid);
apiClient::$cache->set($this->cacheKey.":nonce:" . $uid, $token->secret);
$this->redirectToAuthorization($token);
}
}
/**
* Sets the internal oauth access token (which is returned by the authenticate function), a user should only
* go through the authenticate() flow once (which involces a bunch of browser redirections and authentication screens, not fun)
* and every time the user comes back the access token from the authentication() flow should be re-used (it essentially never expires)
* @param object $accessToken
*/
public function setAccessToken($accessToken) {
$accessToken = json_decode($accessToken, true);
if ($accessToken == null) {
throw new apiAuthException("Could not json decode the access token");
}
if (! isset($accessToken['key']) || ! isset($accessToken['secret'])) {
throw new apiAuthException("Invalid OAuth token, missing key and/or secret");
}
$this->accessToken = new apiClientOAuthConsumer($accessToken['key'], $accessToken['secret']);
}
/**
* Returns the current access token
*/
public function getAccessToken() {
return $this->accessToken;
}
/**
* Set the developer key to use, these are obtained through the API Console
*/
public function setDeveloperKey($developerKey) {
$this->developerKey = $developerKey;
}
/**
* Upgrades an existing request token to an access token.
*
* @param apiCache $cache cache class to use (file,apc,memcache,mysql)
* @param oauthVerifier
*/
public function upgradeRequestToken($requestToken, $requestTokenSecret, $oauthVerifier) {
$ret = $this->requestAccessToken($requestToken, $requestTokenSecret, $oauthVerifier);
$matches = array();
@parse_str($ret, $matches);
if (!isset($matches['oauth_token']) || !isset($matches['oauth_token_secret'])) {
throw new apiAuthException("Error authorizing access key (result was: {$ret})");
}
// The token was upgraded to an access token, we can now continue to use it.
$this->accessToken = new apiClientOAuthConsumer(apiClientOAuthUtil::urldecodeRFC3986($matches['oauth_token']), apiClientOAuthUtil::urldecodeRFC3986($matches['oauth_token_secret']));
return $this->accessToken;
}
/**
* Sends the actual request to exchange an existing request token for an access token.
*
* @param string $requestToken the existing request token
* @param string $requestTokenSecret the request token secret
* @return array('http_code' => HTTP response code (200, 404, 401, etc), 'data' => the html document)
*/
protected function requestAccessToken($requestToken, $requestTokenSecret, $oauthVerifier) {
$accessToken = new apiClientOAuthConsumer($requestToken, $requestTokenSecret);
$accessRequest = apiClientOAuthRequest::from_consumer_and_token($this->consumerToken, $accessToken, "GET", $this->service['access_token_url'], array('oauth_verifier' => $oauthVerifier));
$accessRequest->sign_request($this->signatureMethod, $this->consumerToken, $accessToken);
$request = apiClient::$io->makeRequest(new apiHttpRequest($accessRequest));
if ($request->getResponseHttpCode() != 200) {
throw new apiAuthException("Could not fetch access token, http code: " . $request->getResponseHttpCode() . ', response body: '. $request->getResponseBody());
}
return $request->getResponseBody();
}
/**
* Obtains a request token from the specified provider.
*/
public function obtainRequestToken($callbackUrl, $uid) {
$callbackParams = (strpos($_SERVER['REQUEST_URI'], '?') !== false ? '&' : '?') . 'uid=' . urlencode($uid);
$ret = $this->requestRequestToken($callbackUrl . $callbackParams);
$matches = array();
preg_match('/oauth_token=(.*)&oauth_token_secret=(.*)&oauth_callback_confirmed=(.*)/', $ret, $matches);
if (!is_array($matches) || count($matches) != 4) {
throw new apiAuthException("Error retrieving request key ({$ret})");
}
return new apiClientOAuthToken(apiClientOAuthUtil::urldecodeRFC3986($matches[1]), apiClientOAuthUtil::urldecodeRFC3986($matches[2]));
}
/**
* Sends the actual request to obtain a request token.
*
* @return array('http_code' => HTTP response code (200, 404, 401, etc), 'data' => the html document)
*/
protected function requestRequestToken($callbackUrl) {
$requestTokenRequest = apiClientOAuthRequest::from_consumer_and_token($this->consumerToken, NULL, "GET", $this->service['request_token_url'], array());
$requestTokenRequest->set_parameter('scope', $this->service['scope']);
$requestTokenRequest->set_parameter('oauth_callback', $callbackUrl);
$requestTokenRequest->sign_request($this->signatureMethod, $this->consumerToken, NULL);
$request = apiClient::$io->makeRequest(new apiHttpRequest($requestTokenRequest));
if ($request->getResponseHttpCode() != 200) {
throw new apiAuthException("Couldn't fetch request token, http code: " . $request->getResponseHttpCode() . ', response body: '. $request->getResponseBody());
}
return $request->getResponseBody();
}
/**
* Redirect the uset to the (provider's) authorize page, if approved it should kick the user back to the call back URL
* which hopefully means we'll end up in the constructor of this class again, but with oauth_continue=1 set
*
* @param OAuthToken $token the request token
* @param string $callbackUrl the URL to return to post-authorization (passed to login site)
*/
public function redirectToAuthorization($token) {
$authorizeRedirect = $this->service['authorization_token_url']. $token->key;
header("Location: $authorizeRedirect");
}
/**
* Sign the request using OAuth. This uses the consumer token and key
*
* @param string $method the method (get/put/delete/post)
* @param string $url the url to sign (http://site/social/rest/people/1/@me)
* @param array $params the params that should be appended to the url (count=20 fields=foo, etc)
* @param string $postBody for POST/PUT requests, the postBody is included in the signature
* @return string the signed url
*/
public function sign(apiHttpRequest $request) {
// add the developer key to the request before signing it
if ($this->developerKey) {
$request->setUrl($request->getUrl() . ((strpos($request->getUrl(), '?') === false) ? '?' : '&') . 'key='.urlencode($this->developerKey));
}
// and sign the request
$oauthRequest = apiClientOAuthRequest::from_request($request->getMethod(), $request->getBaseUrl(), $request->getQueryParams());
$params = $this->mergeParameters($request->getQueryParams());
foreach ($params as $key => $val) {
if (is_array($val)) {
$val = implode(',', $val);
}
$oauthRequest->set_parameter($key, $val);
}
$oauthRequest->sign_request($this->signatureMethod, $this->consumerToken, $this->accessToken);
$authHeaders = $oauthRequest->to_header();
$headers = $request->getHeaders();
$headers[] = $authHeaders;
$request->setHeaders($headers);
// and add the access token key to it (since it doesn't include the secret, it's still secure to store this in cache)
$request->accessKey = $this->accessToken->key;
return $request;
}
/**
* Merges the supplied parameters with reasonable defaults for 2 legged oauth. User-supplied parameters
* will have precedent over the defaults.
*
* @param array $params the user-supplied params that will be appended to the url
* @return array the combined parameters
*/
protected function mergeParameters($params) {
$defaults = array(
'oauth_nonce' => md5(microtime() . mt_rand()),
'oauth_version' => apiClientOAuthRequest::$version, 'oauth_timestamp' => time(),
'oauth_consumer_key' => $this->consumerToken->key
);
if ($this->accessToken != null) {
$params['oauth_token'] = $this->accessToken->key;
}
return array_merge($defaults, $params);
}
public function createAuthUrl($scope) {return null;}
public function refreshToken($refreshToken) {/* noop*/}
public function revokeToken() {/* noop*/}
} | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiOAuth.php | PHP | asf20 | 11,571 |
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Verifies signatures using PEM encoded certificates.
*
* @author Brian Eaton <beaton@google.com>
*/
class apiPemVerifier extends apiVerifier {
private $publicKey;
/**
* Constructs a verifier from the supplied PEM-encoded certificate.
*
* $pem: a PEM encoded certificate (not a file).
*/
function __construct($pem) {
if (!function_exists('openssl_x509_read')) {
throw new Exception(
'The Google PHP API library needs the openssl PHP extension');
}
$this->publicKey = openssl_x509_read($pem);
if (!$this->publicKey) {
throw new apiAuthException("Unable to parse PEM: $pem");
}
}
function __destruct() {
if ($this->publicKey) {
openssl_x509_free($this->publicKey);
}
}
/**
* Verifies the signature on data.
*
* Returns true if the signature is valid, false otherwise.
*/
function verify($data, $signature) {
$status = openssl_verify($data, $signature, $this->publicKey, "sha256");
if ($status === -1) {
throw new apiAuthException("Signature verification error: " .
openssl_error_string());
}
return $status === 1;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/auth/apiPemVerifier.php | PHP | asf20 | 1,759 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "advertisers" collection of methods.
* Typical usage is:
* <code>
* $ganService = new apiGanService(...);
* $advertisers = $ganService->advertisers;
* </code>
*/
class AdvertisersServiceResource extends apiServiceResource {
/**
* Retrieves data about all advertisers that the requesting advertiser/publisher has access to.
* (advertisers.list)
*
* @param string $role The role of the requester. Valid values: 'advertisers' or 'publishers'.
* @param string $roleId The ID of the requesting advertiser or publisher.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string relationshipStatus Filters out all advertisers for which do not have the given relationship status with the requesting publisher.
* @opt_param double minSevenDayEpc Filters out all advertisers that have a seven day EPC average lower than the given value (inclusive). Min value: 0.0. Optional.
* @opt_param string advertiserCategory Caret(^) delimted list of advertiser categories. Valid categories are defined here: http://www.google.com/support/affiliatenetwork/advertiser/bin/answer.py?hl=en=107581. Filters out all advertisers not in one of the given advertiser categories. Optional.
* @opt_param double minNinetyDayEpc Filters out all advertisers that have a ninety day EPC average lower than the given value (inclusive). Min value: 0.0. Optional.
* @opt_param string pageToken The value of 'nextPageToken' from the previous page. Optional.
* @opt_param string maxResults Max number of items to return in this page. Optional. Defaults to 20.
* @opt_param int minPayoutRank A value between 1 and 4, where 1 represents the quartile of advertisers with the lowest ranks and 4 represents the quartile of advertisers with the highest ranks. Filters out all advertisers with a lower rank than the given quartile. For example if a 2 was given only advertisers with a payout rank of 25 or higher would be included. Optional.
* @return Advertisers
*/
public function listAdvertisers($role, $roleId, $optParams = array()) {
$params = array('role' => $role, 'roleId' => $roleId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Advertisers($data);
} else {
return $data;
}
}
/**
* Retrieves data about a single advertiser if that the requesting advertiser/publisher has access
* to it. Only publishers can lookup advertisers. Advertisers can request information about
* themselves by omitting the advertiserId query parameter. (advertisers.get)
*
* @param string $role The role of the requester. Valid values: 'advertisers' or 'publishers'.
* @param string $roleId The ID of the requesting advertiser or publisher.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string advertiserId The ID of the advertiser to look up. Optional.
* @return Advertiser
*/
public function get($role, $roleId, $optParams = array()) {
$params = array('role' => $role, 'roleId' => $roleId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Advertiser($data);
} else {
return $data;
}
}
}
/**
* The "ccOffers" collection of methods.
* Typical usage is:
* <code>
* $ganService = new apiGanService(...);
* $ccOffers = $ganService->ccOffers;
* </code>
*/
class CcOffersServiceResource extends apiServiceResource {
/**
* Retrieves credit card offers for the given publisher. (ccOffers.list)
*
* @param string $publisher The ID of the publisher in question.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string advertiser The advertiser ID of a card issuer whose offers to include. Optional, may be repeated.
* @opt_param string projection The set of fields to return.
* @return CcOffers
*/
public function listCcOffers($publisher, $optParams = array()) {
$params = array('publisher' => $publisher);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CcOffers($data);
} else {
return $data;
}
}
}
/**
* The "events" collection of methods.
* Typical usage is:
* <code>
* $ganService = new apiGanService(...);
* $events = $ganService->events;
* </code>
*/
class EventsServiceResource extends apiServiceResource {
/**
* Retrieves event data for a given advertiser/publisher. (events.list)
*
* @param string $role The role of the requester. Valid values: 'advertisers' or 'publishers'.
* @param string $roleId The ID of the requesting advertiser or publisher.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string orderId Caret(^) delimited list of order IDs. Filters out all events that do not reference one of the given order IDs. Optional.
* @opt_param string sku Caret(^) delimited list of SKUs. Filters out all events that do not reference one of the given SKU. Optional.
* @opt_param string eventDateMax Filters out all events later than given date. Optional. Defaults to 24 hours after eventMin.
* @opt_param string type Filters out all events that are not of the given type. Valid values: 'action', 'transaction', 'charge'. Optional.
* @opt_param string linkId Caret(^) delimited list of link IDs. Filters out all events that do not reference one of the given link IDs. Optional.
* @opt_param string status Filters out all events that do not have the given status. Valid values: 'active', 'canceled'. Optional.
* @opt_param string eventDateMin Filters out all events earlier than given date. Optional. Defaults to 24 hours from current date/time.
* @opt_param string memberId Caret(^) delimited list of member IDs. Filters out all events that do not reference one of the given member IDs. Optional.
* @opt_param string maxResults Max number of offers to return in this page. Optional. Defaults to 20.
* @opt_param string advertiserId Caret(^) delimited list of advertiser IDs. Filters out all events that do not reference one of the given advertiser IDs. Only used when under publishers role. Optional.
* @opt_param string pageToken The value of 'nextPageToken' from the previous page. Optional.
* @opt_param string productCategory Caret(^) delimited list of product categories. Filters out all events that do not reference a product in one of the given product categories. Optional.
* @opt_param string chargeType Filters out all charge events that are not of the given charge type. Valid values: 'other', 'slotting_fee', 'monthly_minimum', 'tier_bonus', 'credit', 'debit'. Optional.
* @opt_param string publisherId Caret(^) delimited list of publisher IDs. Filters out all events that do not reference one of the given publishers IDs. Only used when under advertiser role. Optional.
* @return Events
*/
public function listEvents($role, $roleId, $optParams = array()) {
$params = array('role' => $role, 'roleId' => $roleId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Events($data);
} else {
return $data;
}
}
}
/**
* The "publishers" collection of methods.
* Typical usage is:
* <code>
* $ganService = new apiGanService(...);
* $publishers = $ganService->publishers;
* </code>
*/
class PublishersServiceResource extends apiServiceResource {
/**
* Retrieves data about all publishers that the requesting advertiser/publisher has access to.
* (publishers.list)
*
* @param string $role The role of the requester. Valid values: 'advertisers' or 'publishers'.
* @param string $roleId The ID of the requesting advertiser or publisher.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string publisherCategory Caret(^) delimted list of publisher categories. Valid categories: (unclassified|community_and_content|shopping_and_promotion|loyalty_and_rewards|network|search_specialist|comparison_shopping|email). Filters out all publishers not in one of the given advertiser categories. Optional.
* @opt_param string relationshipStatus Filters out all publishers for which do not have the given relationship status with the requesting publisher.
* @opt_param double minSevenDayEpc Filters out all publishers that have a seven day EPC average lower than the given value (inclusive). Min value 0.0. Optional.
* @opt_param double minNinetyDayEpc Filters out all publishers that have a ninety day EPC average lower than the given value (inclusive). Min value: 0.0. Optional.
* @opt_param string pageToken The value of 'nextPageToken' from the previous page. Optional.
* @opt_param string maxResults Max number of items to return in this page. Optional. Defaults to 20.
* @opt_param int minPayoutRank A value between 1 and 4, where 1 represents the quartile of publishers with the lowest ranks and 4 represents the quartile of publishers with the highest ranks. Filters out all publishers with a lower rank than the given quartile. For example if a 2 was given only publishers with a payout rank of 25 or higher would be included. Optional.
* @return Publishers
*/
public function listPublishers($role, $roleId, $optParams = array()) {
$params = array('role' => $role, 'roleId' => $roleId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Publishers($data);
} else {
return $data;
}
}
/**
* Retrieves data about a single advertiser if that the requesting advertiser/publisher has access
* to it. Only advertisers can look up publishers. Publishers can request information about
* themselves by omitting the publisherId query parameter. (publishers.get)
*
* @param string $role The role of the requester. Valid values: 'advertisers' or 'publishers'.
* @param string $roleId The ID of the requesting advertiser or publisher.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string publisherId The ID of the publisher to look up. Optional.
* @return Publisher
*/
public function get($role, $roleId, $optParams = array()) {
$params = array('role' => $role, 'roleId' => $roleId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Publisher($data);
} else {
return $data;
}
}
}
/**
* Service definition for Gan (v1beta1).
*
* <p>
* Lets you have programmatic access to your Google Affiliate Network data
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://code.google.com/apis/gan/" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiGanService extends apiService {
public $advertisers;
public $ccOffers;
public $events;
public $publishers;
/**
* Constructs the internal representation of the Gan service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/gan/v1beta1/';
$this->version = 'v1beta1';
$this->serviceName = 'gan';
$apiClient->addService($this->serviceName, $this->version);
$this->advertisers = new AdvertisersServiceResource($this, $this->serviceName, 'advertisers', json_decode('{"methods": {"list": {"parameters": {"relationshipStatus": {"enum": ["approved", "available", "deactivated", "declined", "pending"], "type": "string", "location": "query"}, "minSevenDayEpc": {"format": "double", "type": "number", "location": "query"}, "advertiserCategory": {"type": "string", "location": "query"}, "minNinetyDayEpc": {"format": "double", "type": "number", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "role": {"required": true, "enum": ["advertisers", "publishers"], "location": "path", "type": "string"}, "maxResults": {"format": "uint32", "maximum": "100", "minimum": "0", "location": "query", "type": "integer"}, "roleId": {"required": true, "type": "string", "location": "path"}, "minPayoutRank": {"format": "int32", "maximum": "4", "minimum": "1", "location": "query", "type": "integer"}}, "id": "gan.advertisers.list", "httpMethod": "GET", "path": "{role}/{roleId}/advertisers", "response": {"$ref": "Advertisers"}}, "get": {"parameters": {"advertiserId": {"type": "string", "location": "query"}, "roleId": {"required": true, "type": "string", "location": "path"}, "role": {"required": true, "enum": ["advertisers", "publishers"], "location": "path", "type": "string"}}, "id": "gan.advertisers.get", "httpMethod": "GET", "path": "{role}/{roleId}/advertiser", "response": {"$ref": "Advertiser"}}}}', true));
$this->ccOffers = new CcOffersServiceResource($this, $this->serviceName, 'ccOffers', json_decode('{"methods": {"list": {"parameters": {"advertiser": {"repeated": true, "type": "string", "location": "query"}, "projection": {"enum": ["full", "summary"], "type": "string", "location": "query"}, "publisher": {"required": true, "type": "string", "location": "path"}}, "id": "gan.ccOffers.list", "httpMethod": "GET", "path": "publishers/{publisher}/ccOffers", "response": {"$ref": "CcOffers"}}}}', true));
$this->events = new EventsServiceResource($this, $this->serviceName, 'events', json_decode('{"methods": {"list": {"parameters": {"orderId": {"type": "string", "location": "query"}, "sku": {"type": "string", "location": "query"}, "eventDateMax": {"type": "string", "location": "query"}, "linkId": {"type": "string", "location": "query"}, "eventDateMin": {"type": "string", "location": "query"}, "memberId": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "maximum": "100", "minimum": "0", "location": "query", "type": "integer"}, "advertiserId": {"type": "string", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "publisherId": {"type": "string", "location": "query"}, "status": {"enum": ["active", "canceled"], "type": "string", "location": "query"}, "productCategory": {"type": "string", "location": "query"}, "chargeType": {"enum": ["credit", "debit", "monthly_minimum", "other", "slotting_fee", "tier_bonus"], "type": "string", "location": "query"}, "roleId": {"required": true, "type": "string", "location": "path"}, "role": {"required": true, "enum": ["advertisers", "publishers"], "location": "path", "type": "string"}, "type": {"enum": ["action", "charge", "transaction"], "type": "string", "location": "query"}}, "id": "gan.events.list", "httpMethod": "GET", "path": "{role}/{roleId}/events", "response": {"$ref": "Events"}}}}', true));
$this->publishers = new PublishersServiceResource($this, $this->serviceName, 'publishers', json_decode('{"methods": {"list": {"parameters": {"publisherCategory": {"type": "string", "location": "query"}, "relationshipStatus": {"enum": ["approved", "available", "deactivated", "declined", "pending"], "type": "string", "location": "query"}, "minSevenDayEpc": {"format": "double", "type": "number", "location": "query"}, "minNinetyDayEpc": {"format": "double", "type": "number", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "role": {"required": true, "enum": ["advertisers", "publishers"], "location": "path", "type": "string"}, "maxResults": {"format": "uint32", "maximum": "100", "minimum": "0", "location": "query", "type": "integer"}, "roleId": {"required": true, "type": "string", "location": "path"}, "minPayoutRank": {"format": "int32", "maximum": "4", "minimum": "1", "location": "query", "type": "integer"}}, "id": "gan.publishers.list", "httpMethod": "GET", "path": "{role}/{roleId}/publishers", "response": {"$ref": "Publishers"}}, "get": {"parameters": {"publisherId": {"type": "string", "location": "query"}, "role": {"required": true, "enum": ["advertisers", "publishers"], "location": "path", "type": "string"}, "roleId": {"required": true, "type": "string", "location": "path"}}, "id": "gan.publishers.get", "httpMethod": "GET", "path": "{role}/{roleId}/publisher", "response": {"$ref": "Publisher"}}}}', true));
}
}
class Advertiser extends apiModel {
public $category;
public $productFeedsEnabled;
public $kind;
public $siteUrl;
public $contactPhone;
public $description;
public $payoutRank;
protected $__epcSevenDayAverageType = 'Money';
protected $__epcSevenDayAverageDataType = '';
public $epcSevenDayAverage;
public $commissionDuration;
public $status;
protected $__epcNinetyDayAverageType = 'Money';
protected $__epcNinetyDayAverageDataType = '';
public $epcNinetyDayAverage;
public $contactEmail;
protected $__itemType = 'Advertiser';
protected $__itemDataType = '';
public $item;
public $joinDate;
public $logoUrl;
public $id;
public $name;
public function setCategory($category) {
$this->category = $category;
}
public function getCategory() {
return $this->category;
}
public function setProductFeedsEnabled($productFeedsEnabled) {
$this->productFeedsEnabled = $productFeedsEnabled;
}
public function getProductFeedsEnabled() {
return $this->productFeedsEnabled;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setSiteUrl($siteUrl) {
$this->siteUrl = $siteUrl;
}
public function getSiteUrl() {
return $this->siteUrl;
}
public function setContactPhone($contactPhone) {
$this->contactPhone = $contactPhone;
}
public function getContactPhone() {
return $this->contactPhone;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setPayoutRank($payoutRank) {
$this->payoutRank = $payoutRank;
}
public function getPayoutRank() {
return $this->payoutRank;
}
public function setEpcSevenDayAverage(Money $epcSevenDayAverage) {
$this->epcSevenDayAverage = $epcSevenDayAverage;
}
public function getEpcSevenDayAverage() {
return $this->epcSevenDayAverage;
}
public function setCommissionDuration($commissionDuration) {
$this->commissionDuration = $commissionDuration;
}
public function getCommissionDuration() {
return $this->commissionDuration;
}
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setEpcNinetyDayAverage(Money $epcNinetyDayAverage) {
$this->epcNinetyDayAverage = $epcNinetyDayAverage;
}
public function getEpcNinetyDayAverage() {
return $this->epcNinetyDayAverage;
}
public function setContactEmail($contactEmail) {
$this->contactEmail = $contactEmail;
}
public function getContactEmail() {
return $this->contactEmail;
}
public function setItem(Advertiser $item) {
$this->item = $item;
}
public function getItem() {
return $this->item;
}
public function setJoinDate($joinDate) {
$this->joinDate = $joinDate;
}
public function getJoinDate() {
return $this->joinDate;
}
public function setLogoUrl($logoUrl) {
$this->logoUrl = $logoUrl;
}
public function getLogoUrl() {
return $this->logoUrl;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Advertisers extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Advertiser';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Advertiser) */ $items) {
$this->assertIsArray($items, 'Advertiser', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class CcOffer extends apiModel {
public $rewardsHaveBlackoutDates;
public $introPurchasePeriodLength;
public $introBalanceTransferRate;
public $cardBenefits;
public $introBalanceTransferAprDisplay;
public $issuer;
public $introBalanceTransferFeeRate;
public $cashAdvanceFeeDisplay;
public $annualFeeDisplay;
public $minimumFinanceCharge;
public $balanceTransferFeeDisplay;
public $landingPageUrl;
public $introPurchaseRate;
public $cashAdvanceAprDisplay;
public $maxCashAdvanceRate;
public $firstYearAnnualFee;
public $introBalanceTransferPeriodUnits;
public $variableRatesUpdateFrequency;
public $overLimitFee;
public $rewardsExpire;
public $additionalCardBenefits;
public $ageMinimum;
public $balanceTransferAprDisplay;
public $introBalanceTransferPeriodLength;
public $network;
public $introPurchaseRateType;
public $introAprDisplay;
public $flightAccidentInsurance;
public $annualRewardMaximum;
public $disclaimer;
public $creditLimitMin;
public $creditLimitMax;
public $gracePeriodDisplay;
public $cashAdvanceFeeAmount;
public $travelInsurance;
public $existingCustomerOnly;
public $initialSetupAndProcessingFee;
public $issuerId;
public $rewardUnit;
public $prohibitedCategories;
protected $__defaultFeesType = 'CcOfferDefaultFees';
protected $__defaultFeesDataType = 'array';
public $defaultFees;
public $introPurchasePeriodUnits;
public $trackingUrl;
public $latePaymentFee;
public $statementCopyFee;
public $variableRatesLastUpdated;
public $minBalanceTransferRate;
public $emergencyInsurance;
public $introPurchasePeriodEndDate;
public $cardName;
public $returnedPaymentFee;
public $cashAdvanceAdditionalDetails;
public $cashAdvanceLimit;
public $balanceTransferFeeRate;
public $balanceTransferRateType;
protected $__rewardsType = 'CcOfferRewards';
protected $__rewardsDataType = 'array';
public $rewards;
public $extendedWarranty;
public $carRentalInsurance;
public $cashAdvanceFeeRate;
public $rewardPartner;
public $foreignCurrencyTransactionFee;
public $kind;
public $introBalanceTransferFeeAmount;
public $creditRatingDisplay;
public $additionalCardHolderFee;
public $purchaseRateType;
public $cashAdvanceRateType;
protected $__bonusRewardsType = 'CcOfferBonusRewards';
protected $__bonusRewardsDataType = 'array';
public $bonusRewards;
public $balanceTransferLimit;
public $luggageInsurance;
public $minCashAdvanceRate;
public $offerId;
public $minPurchaseRate;
public $offersImmediateCashReward;
public $fraudLiability;
public $cardType;
public $approvedCategories;
public $annualFee;
public $maxBalanceTransferRate;
public $maxPurchaseRate;
public $issuerWebsite;
public $introBalanceTransferRateType;
public $aprDisplay;
public $imageUrl;
public $ageMinimumDetails;
public $balanceTransferFeeAmount;
public $introBalanceTransferPeriodEndDate;
public function setRewardsHaveBlackoutDates($rewardsHaveBlackoutDates) {
$this->rewardsHaveBlackoutDates = $rewardsHaveBlackoutDates;
}
public function getRewardsHaveBlackoutDates() {
return $this->rewardsHaveBlackoutDates;
}
public function setIntroPurchasePeriodLength($introPurchasePeriodLength) {
$this->introPurchasePeriodLength = $introPurchasePeriodLength;
}
public function getIntroPurchasePeriodLength() {
return $this->introPurchasePeriodLength;
}
public function setIntroBalanceTransferRate($introBalanceTransferRate) {
$this->introBalanceTransferRate = $introBalanceTransferRate;
}
public function getIntroBalanceTransferRate() {
return $this->introBalanceTransferRate;
}
public function setCardBenefits(/* array(string) */ $cardBenefits) {
$this->assertIsArray($cardBenefits, 'string', __METHOD__);
$this->cardBenefits = $cardBenefits;
}
public function getCardBenefits() {
return $this->cardBenefits;
}
public function setIntroBalanceTransferAprDisplay($introBalanceTransferAprDisplay) {
$this->introBalanceTransferAprDisplay = $introBalanceTransferAprDisplay;
}
public function getIntroBalanceTransferAprDisplay() {
return $this->introBalanceTransferAprDisplay;
}
public function setIssuer($issuer) {
$this->issuer = $issuer;
}
public function getIssuer() {
return $this->issuer;
}
public function setIntroBalanceTransferFeeRate($introBalanceTransferFeeRate) {
$this->introBalanceTransferFeeRate = $introBalanceTransferFeeRate;
}
public function getIntroBalanceTransferFeeRate() {
return $this->introBalanceTransferFeeRate;
}
public function setCashAdvanceFeeDisplay($cashAdvanceFeeDisplay) {
$this->cashAdvanceFeeDisplay = $cashAdvanceFeeDisplay;
}
public function getCashAdvanceFeeDisplay() {
return $this->cashAdvanceFeeDisplay;
}
public function setAnnualFeeDisplay($annualFeeDisplay) {
$this->annualFeeDisplay = $annualFeeDisplay;
}
public function getAnnualFeeDisplay() {
return $this->annualFeeDisplay;
}
public function setMinimumFinanceCharge($minimumFinanceCharge) {
$this->minimumFinanceCharge = $minimumFinanceCharge;
}
public function getMinimumFinanceCharge() {
return $this->minimumFinanceCharge;
}
public function setBalanceTransferFeeDisplay($balanceTransferFeeDisplay) {
$this->balanceTransferFeeDisplay = $balanceTransferFeeDisplay;
}
public function getBalanceTransferFeeDisplay() {
return $this->balanceTransferFeeDisplay;
}
public function setLandingPageUrl($landingPageUrl) {
$this->landingPageUrl = $landingPageUrl;
}
public function getLandingPageUrl() {
return $this->landingPageUrl;
}
public function setIntroPurchaseRate($introPurchaseRate) {
$this->introPurchaseRate = $introPurchaseRate;
}
public function getIntroPurchaseRate() {
return $this->introPurchaseRate;
}
public function setCashAdvanceAprDisplay($cashAdvanceAprDisplay) {
$this->cashAdvanceAprDisplay = $cashAdvanceAprDisplay;
}
public function getCashAdvanceAprDisplay() {
return $this->cashAdvanceAprDisplay;
}
public function setMaxCashAdvanceRate($maxCashAdvanceRate) {
$this->maxCashAdvanceRate = $maxCashAdvanceRate;
}
public function getMaxCashAdvanceRate() {
return $this->maxCashAdvanceRate;
}
public function setFirstYearAnnualFee($firstYearAnnualFee) {
$this->firstYearAnnualFee = $firstYearAnnualFee;
}
public function getFirstYearAnnualFee() {
return $this->firstYearAnnualFee;
}
public function setIntroBalanceTransferPeriodUnits($introBalanceTransferPeriodUnits) {
$this->introBalanceTransferPeriodUnits = $introBalanceTransferPeriodUnits;
}
public function getIntroBalanceTransferPeriodUnits() {
return $this->introBalanceTransferPeriodUnits;
}
public function setVariableRatesUpdateFrequency($variableRatesUpdateFrequency) {
$this->variableRatesUpdateFrequency = $variableRatesUpdateFrequency;
}
public function getVariableRatesUpdateFrequency() {
return $this->variableRatesUpdateFrequency;
}
public function setOverLimitFee($overLimitFee) {
$this->overLimitFee = $overLimitFee;
}
public function getOverLimitFee() {
return $this->overLimitFee;
}
public function setRewardsExpire($rewardsExpire) {
$this->rewardsExpire = $rewardsExpire;
}
public function getRewardsExpire() {
return $this->rewardsExpire;
}
public function setAdditionalCardBenefits(/* array(string) */ $additionalCardBenefits) {
$this->assertIsArray($additionalCardBenefits, 'string', __METHOD__);
$this->additionalCardBenefits = $additionalCardBenefits;
}
public function getAdditionalCardBenefits() {
return $this->additionalCardBenefits;
}
public function setAgeMinimum($ageMinimum) {
$this->ageMinimum = $ageMinimum;
}
public function getAgeMinimum() {
return $this->ageMinimum;
}
public function setBalanceTransferAprDisplay($balanceTransferAprDisplay) {
$this->balanceTransferAprDisplay = $balanceTransferAprDisplay;
}
public function getBalanceTransferAprDisplay() {
return $this->balanceTransferAprDisplay;
}
public function setIntroBalanceTransferPeriodLength($introBalanceTransferPeriodLength) {
$this->introBalanceTransferPeriodLength = $introBalanceTransferPeriodLength;
}
public function getIntroBalanceTransferPeriodLength() {
return $this->introBalanceTransferPeriodLength;
}
public function setNetwork($network) {
$this->network = $network;
}
public function getNetwork() {
return $this->network;
}
public function setIntroPurchaseRateType($introPurchaseRateType) {
$this->introPurchaseRateType = $introPurchaseRateType;
}
public function getIntroPurchaseRateType() {
return $this->introPurchaseRateType;
}
public function setIntroAprDisplay($introAprDisplay) {
$this->introAprDisplay = $introAprDisplay;
}
public function getIntroAprDisplay() {
return $this->introAprDisplay;
}
public function setFlightAccidentInsurance($flightAccidentInsurance) {
$this->flightAccidentInsurance = $flightAccidentInsurance;
}
public function getFlightAccidentInsurance() {
return $this->flightAccidentInsurance;
}
public function setAnnualRewardMaximum($annualRewardMaximum) {
$this->annualRewardMaximum = $annualRewardMaximum;
}
public function getAnnualRewardMaximum() {
return $this->annualRewardMaximum;
}
public function setDisclaimer($disclaimer) {
$this->disclaimer = $disclaimer;
}
public function getDisclaimer() {
return $this->disclaimer;
}
public function setCreditLimitMin($creditLimitMin) {
$this->creditLimitMin = $creditLimitMin;
}
public function getCreditLimitMin() {
return $this->creditLimitMin;
}
public function setCreditLimitMax($creditLimitMax) {
$this->creditLimitMax = $creditLimitMax;
}
public function getCreditLimitMax() {
return $this->creditLimitMax;
}
public function setGracePeriodDisplay($gracePeriodDisplay) {
$this->gracePeriodDisplay = $gracePeriodDisplay;
}
public function getGracePeriodDisplay() {
return $this->gracePeriodDisplay;
}
public function setCashAdvanceFeeAmount($cashAdvanceFeeAmount) {
$this->cashAdvanceFeeAmount = $cashAdvanceFeeAmount;
}
public function getCashAdvanceFeeAmount() {
return $this->cashAdvanceFeeAmount;
}
public function setTravelInsurance($travelInsurance) {
$this->travelInsurance = $travelInsurance;
}
public function getTravelInsurance() {
return $this->travelInsurance;
}
public function setExistingCustomerOnly($existingCustomerOnly) {
$this->existingCustomerOnly = $existingCustomerOnly;
}
public function getExistingCustomerOnly() {
return $this->existingCustomerOnly;
}
public function setInitialSetupAndProcessingFee($initialSetupAndProcessingFee) {
$this->initialSetupAndProcessingFee = $initialSetupAndProcessingFee;
}
public function getInitialSetupAndProcessingFee() {
return $this->initialSetupAndProcessingFee;
}
public function setIssuerId($issuerId) {
$this->issuerId = $issuerId;
}
public function getIssuerId() {
return $this->issuerId;
}
public function setRewardUnit($rewardUnit) {
$this->rewardUnit = $rewardUnit;
}
public function getRewardUnit() {
return $this->rewardUnit;
}
public function setProhibitedCategories(/* array(string) */ $prohibitedCategories) {
$this->assertIsArray($prohibitedCategories, 'string', __METHOD__);
$this->prohibitedCategories = $prohibitedCategories;
}
public function getProhibitedCategories() {
return $this->prohibitedCategories;
}
public function setDefaultFees(/* array(CcOfferDefaultFees) */ $defaultFees) {
$this->assertIsArray($defaultFees, 'CcOfferDefaultFees', __METHOD__);
$this->defaultFees = $defaultFees;
}
public function getDefaultFees() {
return $this->defaultFees;
}
public function setIntroPurchasePeriodUnits($introPurchasePeriodUnits) {
$this->introPurchasePeriodUnits = $introPurchasePeriodUnits;
}
public function getIntroPurchasePeriodUnits() {
return $this->introPurchasePeriodUnits;
}
public function setTrackingUrl($trackingUrl) {
$this->trackingUrl = $trackingUrl;
}
public function getTrackingUrl() {
return $this->trackingUrl;
}
public function setLatePaymentFee($latePaymentFee) {
$this->latePaymentFee = $latePaymentFee;
}
public function getLatePaymentFee() {
return $this->latePaymentFee;
}
public function setStatementCopyFee($statementCopyFee) {
$this->statementCopyFee = $statementCopyFee;
}
public function getStatementCopyFee() {
return $this->statementCopyFee;
}
public function setVariableRatesLastUpdated($variableRatesLastUpdated) {
$this->variableRatesLastUpdated = $variableRatesLastUpdated;
}
public function getVariableRatesLastUpdated() {
return $this->variableRatesLastUpdated;
}
public function setMinBalanceTransferRate($minBalanceTransferRate) {
$this->minBalanceTransferRate = $minBalanceTransferRate;
}
public function getMinBalanceTransferRate() {
return $this->minBalanceTransferRate;
}
public function setEmergencyInsurance($emergencyInsurance) {
$this->emergencyInsurance = $emergencyInsurance;
}
public function getEmergencyInsurance() {
return $this->emergencyInsurance;
}
public function setIntroPurchasePeriodEndDate($introPurchasePeriodEndDate) {
$this->introPurchasePeriodEndDate = $introPurchasePeriodEndDate;
}
public function getIntroPurchasePeriodEndDate() {
return $this->introPurchasePeriodEndDate;
}
public function setCardName($cardName) {
$this->cardName = $cardName;
}
public function getCardName() {
return $this->cardName;
}
public function setReturnedPaymentFee($returnedPaymentFee) {
$this->returnedPaymentFee = $returnedPaymentFee;
}
public function getReturnedPaymentFee() {
return $this->returnedPaymentFee;
}
public function setCashAdvanceAdditionalDetails($cashAdvanceAdditionalDetails) {
$this->cashAdvanceAdditionalDetails = $cashAdvanceAdditionalDetails;
}
public function getCashAdvanceAdditionalDetails() {
return $this->cashAdvanceAdditionalDetails;
}
public function setCashAdvanceLimit($cashAdvanceLimit) {
$this->cashAdvanceLimit = $cashAdvanceLimit;
}
public function getCashAdvanceLimit() {
return $this->cashAdvanceLimit;
}
public function setBalanceTransferFeeRate($balanceTransferFeeRate) {
$this->balanceTransferFeeRate = $balanceTransferFeeRate;
}
public function getBalanceTransferFeeRate() {
return $this->balanceTransferFeeRate;
}
public function setBalanceTransferRateType($balanceTransferRateType) {
$this->balanceTransferRateType = $balanceTransferRateType;
}
public function getBalanceTransferRateType() {
return $this->balanceTransferRateType;
}
public function setRewards(/* array(CcOfferRewards) */ $rewards) {
$this->assertIsArray($rewards, 'CcOfferRewards', __METHOD__);
$this->rewards = $rewards;
}
public function getRewards() {
return $this->rewards;
}
public function setExtendedWarranty($extendedWarranty) {
$this->extendedWarranty = $extendedWarranty;
}
public function getExtendedWarranty() {
return $this->extendedWarranty;
}
public function setCarRentalInsurance($carRentalInsurance) {
$this->carRentalInsurance = $carRentalInsurance;
}
public function getCarRentalInsurance() {
return $this->carRentalInsurance;
}
public function setCashAdvanceFeeRate($cashAdvanceFeeRate) {
$this->cashAdvanceFeeRate = $cashAdvanceFeeRate;
}
public function getCashAdvanceFeeRate() {
return $this->cashAdvanceFeeRate;
}
public function setRewardPartner($rewardPartner) {
$this->rewardPartner = $rewardPartner;
}
public function getRewardPartner() {
return $this->rewardPartner;
}
public function setForeignCurrencyTransactionFee($foreignCurrencyTransactionFee) {
$this->foreignCurrencyTransactionFee = $foreignCurrencyTransactionFee;
}
public function getForeignCurrencyTransactionFee() {
return $this->foreignCurrencyTransactionFee;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setIntroBalanceTransferFeeAmount($introBalanceTransferFeeAmount) {
$this->introBalanceTransferFeeAmount = $introBalanceTransferFeeAmount;
}
public function getIntroBalanceTransferFeeAmount() {
return $this->introBalanceTransferFeeAmount;
}
public function setCreditRatingDisplay($creditRatingDisplay) {
$this->creditRatingDisplay = $creditRatingDisplay;
}
public function getCreditRatingDisplay() {
return $this->creditRatingDisplay;
}
public function setAdditionalCardHolderFee($additionalCardHolderFee) {
$this->additionalCardHolderFee = $additionalCardHolderFee;
}
public function getAdditionalCardHolderFee() {
return $this->additionalCardHolderFee;
}
public function setPurchaseRateType($purchaseRateType) {
$this->purchaseRateType = $purchaseRateType;
}
public function getPurchaseRateType() {
return $this->purchaseRateType;
}
public function setCashAdvanceRateType($cashAdvanceRateType) {
$this->cashAdvanceRateType = $cashAdvanceRateType;
}
public function getCashAdvanceRateType() {
return $this->cashAdvanceRateType;
}
public function setBonusRewards(/* array(CcOfferBonusRewards) */ $bonusRewards) {
$this->assertIsArray($bonusRewards, 'CcOfferBonusRewards', __METHOD__);
$this->bonusRewards = $bonusRewards;
}
public function getBonusRewards() {
return $this->bonusRewards;
}
public function setBalanceTransferLimit($balanceTransferLimit) {
$this->balanceTransferLimit = $balanceTransferLimit;
}
public function getBalanceTransferLimit() {
return $this->balanceTransferLimit;
}
public function setLuggageInsurance($luggageInsurance) {
$this->luggageInsurance = $luggageInsurance;
}
public function getLuggageInsurance() {
return $this->luggageInsurance;
}
public function setMinCashAdvanceRate($minCashAdvanceRate) {
$this->minCashAdvanceRate = $minCashAdvanceRate;
}
public function getMinCashAdvanceRate() {
return $this->minCashAdvanceRate;
}
public function setOfferId($offerId) {
$this->offerId = $offerId;
}
public function getOfferId() {
return $this->offerId;
}
public function setMinPurchaseRate($minPurchaseRate) {
$this->minPurchaseRate = $minPurchaseRate;
}
public function getMinPurchaseRate() {
return $this->minPurchaseRate;
}
public function setOffersImmediateCashReward($offersImmediateCashReward) {
$this->offersImmediateCashReward = $offersImmediateCashReward;
}
public function getOffersImmediateCashReward() {
return $this->offersImmediateCashReward;
}
public function setFraudLiability($fraudLiability) {
$this->fraudLiability = $fraudLiability;
}
public function getFraudLiability() {
return $this->fraudLiability;
}
public function setCardType($cardType) {
$this->cardType = $cardType;
}
public function getCardType() {
return $this->cardType;
}
public function setApprovedCategories(/* array(string) */ $approvedCategories) {
$this->assertIsArray($approvedCategories, 'string', __METHOD__);
$this->approvedCategories = $approvedCategories;
}
public function getApprovedCategories() {
return $this->approvedCategories;
}
public function setAnnualFee($annualFee) {
$this->annualFee = $annualFee;
}
public function getAnnualFee() {
return $this->annualFee;
}
public function setMaxBalanceTransferRate($maxBalanceTransferRate) {
$this->maxBalanceTransferRate = $maxBalanceTransferRate;
}
public function getMaxBalanceTransferRate() {
return $this->maxBalanceTransferRate;
}
public function setMaxPurchaseRate($maxPurchaseRate) {
$this->maxPurchaseRate = $maxPurchaseRate;
}
public function getMaxPurchaseRate() {
return $this->maxPurchaseRate;
}
public function setIssuerWebsite($issuerWebsite) {
$this->issuerWebsite = $issuerWebsite;
}
public function getIssuerWebsite() {
return $this->issuerWebsite;
}
public function setIntroBalanceTransferRateType($introBalanceTransferRateType) {
$this->introBalanceTransferRateType = $introBalanceTransferRateType;
}
public function getIntroBalanceTransferRateType() {
return $this->introBalanceTransferRateType;
}
public function setAprDisplay($aprDisplay) {
$this->aprDisplay = $aprDisplay;
}
public function getAprDisplay() {
return $this->aprDisplay;
}
public function setImageUrl($imageUrl) {
$this->imageUrl = $imageUrl;
}
public function getImageUrl() {
return $this->imageUrl;
}
public function setAgeMinimumDetails($ageMinimumDetails) {
$this->ageMinimumDetails = $ageMinimumDetails;
}
public function getAgeMinimumDetails() {
return $this->ageMinimumDetails;
}
public function setBalanceTransferFeeAmount($balanceTransferFeeAmount) {
$this->balanceTransferFeeAmount = $balanceTransferFeeAmount;
}
public function getBalanceTransferFeeAmount() {
return $this->balanceTransferFeeAmount;
}
public function setIntroBalanceTransferPeriodEndDate($introBalanceTransferPeriodEndDate) {
$this->introBalanceTransferPeriodEndDate = $introBalanceTransferPeriodEndDate;
}
public function getIntroBalanceTransferPeriodEndDate() {
return $this->introBalanceTransferPeriodEndDate;
}
}
class CcOfferBonusRewards extends apiModel {
public $amount;
public $details;
public function setAmount($amount) {
$this->amount = $amount;
}
public function getAmount() {
return $this->amount;
}
public function setDetails($details) {
$this->details = $details;
}
public function getDetails() {
return $this->details;
}
}
class CcOfferDefaultFees extends apiModel {
public $category;
public $maxRate;
public $minRate;
public $rateType;
public function setCategory($category) {
$this->category = $category;
}
public function getCategory() {
return $this->category;
}
public function setMaxRate($maxRate) {
$this->maxRate = $maxRate;
}
public function getMaxRate() {
return $this->maxRate;
}
public function setMinRate($minRate) {
$this->minRate = $minRate;
}
public function getMinRate() {
return $this->minRate;
}
public function setRateType($rateType) {
$this->rateType = $rateType;
}
public function getRateType() {
return $this->rateType;
}
}
class CcOfferRewards extends apiModel {
public $category;
public $minRewardTier;
public $maxRewardTier;
public $expirationMonths;
public $amount;
public $additionalDetails;
public function setCategory($category) {
$this->category = $category;
}
public function getCategory() {
return $this->category;
}
public function setMinRewardTier($minRewardTier) {
$this->minRewardTier = $minRewardTier;
}
public function getMinRewardTier() {
return $this->minRewardTier;
}
public function setMaxRewardTier($maxRewardTier) {
$this->maxRewardTier = $maxRewardTier;
}
public function getMaxRewardTier() {
return $this->maxRewardTier;
}
public function setExpirationMonths($expirationMonths) {
$this->expirationMonths = $expirationMonths;
}
public function getExpirationMonths() {
return $this->expirationMonths;
}
public function setAmount($amount) {
$this->amount = $amount;
}
public function getAmount() {
return $this->amount;
}
public function setAdditionalDetails($additionalDetails) {
$this->additionalDetails = $additionalDetails;
}
public function getAdditionalDetails() {
return $this->additionalDetails;
}
}
class CcOffers extends apiModel {
protected $__itemsType = 'CcOffer';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(CcOffer) */ $items) {
$this->assertIsArray($items, 'CcOffer', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class Event extends apiModel {
protected $__networkFeeType = 'Money';
protected $__networkFeeDataType = '';
public $networkFee;
public $advertiserName;
public $kind;
public $modifyDate;
public $type;
public $orderId;
public $publisherName;
public $memberId;
public $advertiserId;
public $status;
public $chargeId;
protected $__productsType = 'EventProducts';
protected $__productsDataType = 'array';
public $products;
protected $__earningsType = 'Money';
protected $__earningsDataType = '';
public $earnings;
public $chargeType;
protected $__publisherFeeType = 'Money';
protected $__publisherFeeDataType = '';
public $publisherFee;
protected $__commissionableSalesType = 'Money';
protected $__commissionableSalesDataType = '';
public $commissionableSales;
public $publisherId;
public $eventDate;
public function setNetworkFee(Money $networkFee) {
$this->networkFee = $networkFee;
}
public function getNetworkFee() {
return $this->networkFee;
}
public function setAdvertiserName($advertiserName) {
$this->advertiserName = $advertiserName;
}
public function getAdvertiserName() {
return $this->advertiserName;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setModifyDate($modifyDate) {
$this->modifyDate = $modifyDate;
}
public function getModifyDate() {
return $this->modifyDate;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setOrderId($orderId) {
$this->orderId = $orderId;
}
public function getOrderId() {
return $this->orderId;
}
public function setPublisherName($publisherName) {
$this->publisherName = $publisherName;
}
public function getPublisherName() {
return $this->publisherName;
}
public function setMemberId($memberId) {
$this->memberId = $memberId;
}
public function getMemberId() {
return $this->memberId;
}
public function setAdvertiserId($advertiserId) {
$this->advertiserId = $advertiserId;
}
public function getAdvertiserId() {
return $this->advertiserId;
}
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setChargeId($chargeId) {
$this->chargeId = $chargeId;
}
public function getChargeId() {
return $this->chargeId;
}
public function setProducts(/* array(EventProducts) */ $products) {
$this->assertIsArray($products, 'EventProducts', __METHOD__);
$this->products = $products;
}
public function getProducts() {
return $this->products;
}
public function setEarnings(Money $earnings) {
$this->earnings = $earnings;
}
public function getEarnings() {
return $this->earnings;
}
public function setChargeType($chargeType) {
$this->chargeType = $chargeType;
}
public function getChargeType() {
return $this->chargeType;
}
public function setPublisherFee(Money $publisherFee) {
$this->publisherFee = $publisherFee;
}
public function getPublisherFee() {
return $this->publisherFee;
}
public function setCommissionableSales(Money $commissionableSales) {
$this->commissionableSales = $commissionableSales;
}
public function getCommissionableSales() {
return $this->commissionableSales;
}
public function setPublisherId($publisherId) {
$this->publisherId = $publisherId;
}
public function getPublisherId() {
return $this->publisherId;
}
public function setEventDate($eventDate) {
$this->eventDate = $eventDate;
}
public function getEventDate() {
return $this->eventDate;
}
}
class EventProducts extends apiModel {
protected $__networkFeeType = 'Money';
protected $__networkFeeDataType = '';
public $networkFee;
public $sku;
public $categoryName;
public $skuName;
protected $__publisherFeeType = 'Money';
protected $__publisherFeeDataType = '';
public $publisherFee;
protected $__earningsType = 'Money';
protected $__earningsDataType = '';
public $earnings;
protected $__unitPriceType = 'Money';
protected $__unitPriceDataType = '';
public $unitPrice;
public $categoryId;
public $quantity;
public function setNetworkFee(Money $networkFee) {
$this->networkFee = $networkFee;
}
public function getNetworkFee() {
return $this->networkFee;
}
public function setSku($sku) {
$this->sku = $sku;
}
public function getSku() {
return $this->sku;
}
public function setCategoryName($categoryName) {
$this->categoryName = $categoryName;
}
public function getCategoryName() {
return $this->categoryName;
}
public function setSkuName($skuName) {
$this->skuName = $skuName;
}
public function getSkuName() {
return $this->skuName;
}
public function setPublisherFee(Money $publisherFee) {
$this->publisherFee = $publisherFee;
}
public function getPublisherFee() {
return $this->publisherFee;
}
public function setEarnings(Money $earnings) {
$this->earnings = $earnings;
}
public function getEarnings() {
return $this->earnings;
}
public function setUnitPrice(Money $unitPrice) {
$this->unitPrice = $unitPrice;
}
public function getUnitPrice() {
return $this->unitPrice;
}
public function setCategoryId($categoryId) {
$this->categoryId = $categoryId;
}
public function getCategoryId() {
return $this->categoryId;
}
public function setQuantity($quantity) {
$this->quantity = $quantity;
}
public function getQuantity() {
return $this->quantity;
}
}
class Events extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Event';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Event) */ $items) {
$this->assertIsArray($items, 'Event', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class Money extends apiModel {
public $amount;
public $currencyCode;
public function setAmount($amount) {
$this->amount = $amount;
}
public function getAmount() {
return $this->amount;
}
public function setCurrencyCode($currencyCode) {
$this->currencyCode = $currencyCode;
}
public function getCurrencyCode() {
return $this->currencyCode;
}
}
class Publisher extends apiModel {
public $status;
public $kind;
public $name;
public $classification;
protected $__epcSevenDayAverageType = 'Money';
protected $__epcSevenDayAverageDataType = '';
public $epcSevenDayAverage;
public $payoutRank;
protected $__epcNinetyDayAverageType = 'Money';
protected $__epcNinetyDayAverageDataType = '';
public $epcNinetyDayAverage;
protected $__itemType = 'Publisher2';
protected $__itemDataType = '';
public $item;
public $joinDate;
public $sites;
public $id;
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setClassification($classification) {
$this->classification = $classification;
}
public function getClassification() {
return $this->classification;
}
public function setEpcSevenDayAverage(Money $epcSevenDayAverage) {
$this->epcSevenDayAverage = $epcSevenDayAverage;
}
public function getEpcSevenDayAverage() {
return $this->epcSevenDayAverage;
}
public function setPayoutRank($payoutRank) {
$this->payoutRank = $payoutRank;
}
public function getPayoutRank() {
return $this->payoutRank;
}
public function setEpcNinetyDayAverage(Money $epcNinetyDayAverage) {
$this->epcNinetyDayAverage = $epcNinetyDayAverage;
}
public function getEpcNinetyDayAverage() {
return $this->epcNinetyDayAverage;
}
public function setItem(Publisher2 $item) {
$this->item = $item;
}
public function getItem() {
return $this->item;
}
public function setJoinDate($joinDate) {
$this->joinDate = $joinDate;
}
public function getJoinDate() {
return $this->joinDate;
}
public function setSites(/* array(string) */ $sites) {
$this->assertIsArray($sites, 'string', __METHOD__);
$this->sites = $sites;
}
public function getSites() {
return $this->sites;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class Publishers extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Publisher';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Publisher) */ $items) {
$this->assertIsArray($items, 'Publisher', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiGanService.php | PHP | asf20 | 55,823 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "text" collection of methods.
* Typical usage is:
* <code>
* $freebaseService = new apiFreebaseService(...);
* $text = $freebaseService->text;
* </code>
*/
class TextServiceResource extends apiServiceResource {
/**
* Returns blob attached to node at specified id as HTML (text.get)
*
* @param string $id The id of the item that you want data about
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string maxlength The max number of characters to return. Valid only for 'plain' format.
* @opt_param string format Sanitizing transformation.
* @return ContentserviceGet
*/
public function get($id, $optParams = array()) {
$params = array('id' => $id);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new ContentserviceGet($data);
} else {
return $data;
}
}
}
/**
* The "mqlread" collection of methods.
* Typical usage is:
* <code>
* $freebaseService = new apiFreebaseService(...);
* $mqlread = $freebaseService->mqlread;
* </code>
*/
class MqlreadServiceResource extends apiServiceResource {
/**
* Performs MQL Queries. (mqlread.mqlread)
*
* @param string $query An envelope containing a single MQL query.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string lang The language of the results - an id of a /type/lang object.
* @opt_param bool html_escape Whether or not to escape entities.
* @opt_param string indent How many spaces to indent the json.
* @opt_param string uniqueness_failure How MQL responds to uniqueness failures.
* @opt_param string dateline The dateline that you get in a mqlwrite response to ensure consistent results.
* @opt_param string cursor The mql cursor.
* @opt_param string callback JS method name for JSONP callbacks.
* @opt_param bool cost Show the costs or not.
* @opt_param string as_of_time Run the query as it would've been run at the specified point in time.
*/
public function mqlread($query, $optParams = array()) {
$params = array('query' => $query);
$params = array_merge($params, $optParams);
$data = $this->__call('mqlread', array($params));
return $data;
}
}
/**
* The "image" collection of methods.
* Typical usage is:
* <code>
* $freebaseService = new apiFreebaseService(...);
* $image = $freebaseService->image;
* </code>
*/
class ImageServiceResource extends apiServiceResource {
/**
* Returns the scaled/cropped image attached to a freebase node. (image.image)
*
* @param string $id Freebase entity or content id, mid, or guid.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string maxwidth Maximum width in pixels for resulting image.
* @opt_param string maxheight Maximum height in pixels for resulting image.
* @opt_param string fallbackid Use the image associated with this secondary id if no image is associated with the primary id.
* @opt_param bool pad A boolean specifying whether the resulting image should be padded up to the requested dimensions.
* @opt_param string mode Method used to scale or crop image.
*/
public function image($id, $optParams = array()) {
$params = array('id' => $id);
$params = array_merge($params, $optParams);
$data = $this->__call('image', array($params));
return $data;
}
}
/**
* Service definition for Freebase (v1).
*
* <p>
* Lets you access the Freebase repository of open data.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://wiki.freebase.com/wiki/New_Freebase_API" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiFreebaseService extends apiService {
public $mqlread;
public $image;
public $text;
/**
* Constructs the internal representation of the Freebase service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/freebase/v1/';
$this->version = 'v1';
$this->serviceName = 'freebase';
$apiClient->addService($this->serviceName, $this->version);
$this->text = new TextServiceResource($this, $this->serviceName, 'text', json_decode('{"methods": {"get": {"parameters": {"format": {"default": "plain", "enum": ["html", "plain", "raw"], "location": "query", "type": "string"}, "id": {"repeated": true, "required": true, "type": "string", "location": "path"}, "maxlength": {"format": "uint32", "type": "integer", "location": "query"}}, "id": "freebase.text.get", "httpMethod": "GET", "path": "text{/id*}", "response": {"$ref": "ContentserviceGet"}}}}', true));
$this->mqlread = new MqlreadServiceResource($this, $this->serviceName, 'mqlread', json_decode('{"httpMethod": "GET", "parameters": {"lang": {"default": "/lang/en", "type": "string", "location": "query"}, "cursor": {"type": "string", "location": "query"}, "indent": {"format": "uint32", "default": "0", "maximum": "10", "location": "query", "type": "integer"}, "uniqueness_failure": {"default": "hard", "enum": ["hard", "soft"], "location": "query", "type": "string"}, "dateline": {"type": "string", "location": "query"}, "html_escape": {"default": "true", "type": "boolean", "location": "query"}, "callback": {"type": "string", "location": "query"}, "cost": {"default": "false", "type": "boolean", "location": "query"}, "query": {"required": true, "type": "string", "location": "query"}, "as_of_time": {"type": "string", "location": "query"}}, "path": "mqlread", "id": "freebase.mqlread"}', true));
$this->image = new ImageServiceResource($this, $this->serviceName, 'image', json_decode('{"httpMethod": "GET", "parameters": {"maxwidth": {"format": "uint32", "type": "integer", "location": "query", "maximum": "4096"}, "maxheight": {"format": "uint32", "type": "integer", "location": "query", "maximum": "4096"}, "fallbackid": {"default": "/freebase/no_image_png", "type": "string", "location": "query"}, "pad": {"default": "false", "type": "boolean", "location": "query"}, "mode": {"default": "fit", "enum": ["fill", "fillcrop", "fillcropmid", "fit"], "location": "query", "type": "string"}, "id": {"repeated": true, "required": true, "type": "string", "location": "path"}}, "path": "image{/id*}", "id": "freebase.image"}', true));
}
}
class ContentserviceGet extends apiModel {
public $result;
public function setResult($result) {
$this->result = $result;
}
public function getResult() {
return $this->result;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiFreebaseService.php | PHP | asf20 | 7,613 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "pagespeedapi" collection of methods.
* Typical usage is:
* <code>
* $pagespeedonlineService = new apiPagespeedonlineService(...);
* $pagespeedapi = $pagespeedonlineService->pagespeedapi;
* </code>
*/
class PagespeedapiServiceResource extends apiServiceResource {
/**
* Runs Page Speed analysis on the page at the specified URL, and returns a Page Speed score, a list
* of suggestions to make that page faster, and other information. (pagespeedapi.runpagespeed)
*
* @param string $url The URL to fetch and analyze
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string locale The locale used to localize formatted results
* @opt_param string rule A Page Speed rule to run; if none are given, all rules are run
* @opt_param string strategy The analysis strategy to use
* @return Result
*/
public function runpagespeed($url, $optParams = array()) {
$params = array('url' => $url);
$params = array_merge($params, $optParams);
$data = $this->__call('runpagespeed', array($params));
if ($this->useObjects()) {
return new Result($data);
} else {
return $data;
}
}
}
/**
* Service definition for Pagespeedonline (v1).
*
* <p>
* Lets you analyze the performance of a web page and get tailored suggestions to make that page faster.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://code.google.com/apis/pagespeedonline/v1/getting_started.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiPagespeedonlineService extends apiService {
public $pagespeedapi;
/**
* Constructs the internal representation of the Pagespeedonline service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/pagespeedonline/v1/';
$this->version = 'v1';
$this->serviceName = 'pagespeedonline';
$apiClient->addService($this->serviceName, $this->version);
$this->pagespeedapi = new PagespeedapiServiceResource($this, $this->serviceName, 'pagespeedapi', json_decode('{"methods": {"runpagespeed": {"parameters": {"locale": {"type": "string", "location": "query"}, "url": {"required": true, "type": "string", "location": "query"}, "rule": {"repeated": true, "type": "string", "location": "query"}, "strategy": {"enum": ["desktop", "mobile"], "type": "string", "location": "query"}}, "id": "pagespeedonline.pagespeedapi.runpagespeed", "httpMethod": "GET", "path": "runPagespeed", "response": {"$ref": "Result"}}}}', true));
}
}
class Result extends apiModel {
public $kind;
protected $__formattedResultsType = 'ResultFormattedResults';
protected $__formattedResultsDataType = '';
public $formattedResults;
public $title;
protected $__versionType = 'ResultVersion';
protected $__versionDataType = '';
public $version;
public $score;
public $responseCode;
public $invalidRules;
protected $__pageStatsType = 'ResultPageStats';
protected $__pageStatsDataType = '';
public $pageStats;
public $id;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setFormattedResults(ResultFormattedResults $formattedResults) {
$this->formattedResults = $formattedResults;
}
public function getFormattedResults() {
return $this->formattedResults;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setVersion(ResultVersion $version) {
$this->version = $version;
}
public function getVersion() {
return $this->version;
}
public function setScore($score) {
$this->score = $score;
}
public function getScore() {
return $this->score;
}
public function setResponseCode($responseCode) {
$this->responseCode = $responseCode;
}
public function getResponseCode() {
return $this->responseCode;
}
public function setInvalidRules(/* array(string) */ $invalidRules) {
$this->assertIsArray($invalidRules, 'string', __METHOD__);
$this->invalidRules = $invalidRules;
}
public function getInvalidRules() {
return $this->invalidRules;
}
public function setPageStats(ResultPageStats $pageStats) {
$this->pageStats = $pageStats;
}
public function getPageStats() {
return $this->pageStats;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class ResultFormattedResults extends apiModel {
public $locale;
protected $__ruleResultsType = 'ResultFormattedResultsRuleResults';
protected $__ruleResultsDataType = 'map';
public $ruleResults;
public function setLocale($locale) {
$this->locale = $locale;
}
public function getLocale() {
return $this->locale;
}
public function setRuleResults(ResultFormattedResultsRuleResults $ruleResults) {
$this->ruleResults = $ruleResults;
}
public function getRuleResults() {
return $this->ruleResults;
}
}
class ResultFormattedResultsRuleResults extends apiModel {
public $localizedRuleName;
protected $__urlBlocksType = 'ResultFormattedResultsRuleResultsUrlBlocks';
protected $__urlBlocksDataType = 'array';
public $urlBlocks;
public $ruleScore;
public $ruleImpact;
public function setLocalizedRuleName($localizedRuleName) {
$this->localizedRuleName = $localizedRuleName;
}
public function getLocalizedRuleName() {
return $this->localizedRuleName;
}
public function setUrlBlocks(/* array(ResultFormattedResultsRuleResultsUrlBlocks) */ $urlBlocks) {
$this->assertIsArray($urlBlocks, 'ResultFormattedResultsRuleResultsUrlBlocks', __METHOD__);
$this->urlBlocks = $urlBlocks;
}
public function getUrlBlocks() {
return $this->urlBlocks;
}
public function setRuleScore($ruleScore) {
$this->ruleScore = $ruleScore;
}
public function getRuleScore() {
return $this->ruleScore;
}
public function setRuleImpact($ruleImpact) {
$this->ruleImpact = $ruleImpact;
}
public function getRuleImpact() {
return $this->ruleImpact;
}
}
class ResultFormattedResultsRuleResultsUrlBlocks extends apiModel {
protected $__headerType = 'ResultFormattedResultsRuleResultsUrlBlocksHeader';
protected $__headerDataType = '';
public $header;
protected $__urlsType = 'ResultFormattedResultsRuleResultsUrlBlocksUrls';
protected $__urlsDataType = 'array';
public $urls;
public function setHeader(ResultFormattedResultsRuleResultsUrlBlocksHeader $header) {
$this->header = $header;
}
public function getHeader() {
return $this->header;
}
public function setUrls(/* array(ResultFormattedResultsRuleResultsUrlBlocksUrls) */ $urls) {
$this->assertIsArray($urls, 'ResultFormattedResultsRuleResultsUrlBlocksUrls', __METHOD__);
$this->urls = $urls;
}
public function getUrls() {
return $this->urls;
}
}
class ResultFormattedResultsRuleResultsUrlBlocksHeader extends apiModel {
protected $__argsType = 'ResultFormattedResultsRuleResultsUrlBlocksHeaderArgs';
protected $__argsDataType = 'array';
public $args;
public $format;
public function setArgs(/* array(ResultFormattedResultsRuleResultsUrlBlocksHeaderArgs) */ $args) {
$this->assertIsArray($args, 'ResultFormattedResultsRuleResultsUrlBlocksHeaderArgs', __METHOD__);
$this->args = $args;
}
public function getArgs() {
return $this->args;
}
public function setFormat($format) {
$this->format = $format;
}
public function getFormat() {
return $this->format;
}
}
class ResultFormattedResultsRuleResultsUrlBlocksHeaderArgs extends apiModel {
public $type;
public $value;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class ResultFormattedResultsRuleResultsUrlBlocksUrls extends apiModel {
protected $__detailsType = 'ResultFormattedResultsRuleResultsUrlBlocksUrlsDetails';
protected $__detailsDataType = 'array';
public $details;
protected $__resultType = 'ResultFormattedResultsRuleResultsUrlBlocksUrlsResult';
protected $__resultDataType = '';
public $result;
public function setDetails(/* array(ResultFormattedResultsRuleResultsUrlBlocksUrlsDetails) */ $details) {
$this->assertIsArray($details, 'ResultFormattedResultsRuleResultsUrlBlocksUrlsDetails', __METHOD__);
$this->details = $details;
}
public function getDetails() {
return $this->details;
}
public function setResult(ResultFormattedResultsRuleResultsUrlBlocksUrlsResult $result) {
$this->result = $result;
}
public function getResult() {
return $this->result;
}
}
class ResultFormattedResultsRuleResultsUrlBlocksUrlsDetails extends apiModel {
protected $__argsType = 'ResultFormattedResultsRuleResultsUrlBlocksUrlsDetailsArgs';
protected $__argsDataType = 'array';
public $args;
public $format;
public function setArgs(/* array(ResultFormattedResultsRuleResultsUrlBlocksUrlsDetailsArgs) */ $args) {
$this->assertIsArray($args, 'ResultFormattedResultsRuleResultsUrlBlocksUrlsDetailsArgs', __METHOD__);
$this->args = $args;
}
public function getArgs() {
return $this->args;
}
public function setFormat($format) {
$this->format = $format;
}
public function getFormat() {
return $this->format;
}
}
class ResultFormattedResultsRuleResultsUrlBlocksUrlsDetailsArgs extends apiModel {
public $type;
public $value;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class ResultFormattedResultsRuleResultsUrlBlocksUrlsResult extends apiModel {
protected $__argsType = 'ResultFormattedResultsRuleResultsUrlBlocksUrlsResultArgs';
protected $__argsDataType = 'array';
public $args;
public $format;
public function setArgs(/* array(ResultFormattedResultsRuleResultsUrlBlocksUrlsResultArgs) */ $args) {
$this->assertIsArray($args, 'ResultFormattedResultsRuleResultsUrlBlocksUrlsResultArgs', __METHOD__);
$this->args = $args;
}
public function getArgs() {
return $this->args;
}
public function setFormat($format) {
$this->format = $format;
}
public function getFormat() {
return $this->format;
}
}
class ResultFormattedResultsRuleResultsUrlBlocksUrlsResultArgs extends apiModel {
public $type;
public $value;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class ResultPageStats extends apiModel {
public $otherResponseBytes;
public $flashResponseBytes;
public $totalRequestBytes;
public $numberCssResources;
public $numberResources;
public $cssResponseBytes;
public $javascriptResponseBytes;
public $imageResponseBytes;
public $numberHosts;
public $numberStaticResources;
public $htmlResponseBytes;
public $numberJsResources;
public $textResponseBytes;
public function setOtherResponseBytes($otherResponseBytes) {
$this->otherResponseBytes = $otherResponseBytes;
}
public function getOtherResponseBytes() {
return $this->otherResponseBytes;
}
public function setFlashResponseBytes($flashResponseBytes) {
$this->flashResponseBytes = $flashResponseBytes;
}
public function getFlashResponseBytes() {
return $this->flashResponseBytes;
}
public function setTotalRequestBytes($totalRequestBytes) {
$this->totalRequestBytes = $totalRequestBytes;
}
public function getTotalRequestBytes() {
return $this->totalRequestBytes;
}
public function setNumberCssResources($numberCssResources) {
$this->numberCssResources = $numberCssResources;
}
public function getNumberCssResources() {
return $this->numberCssResources;
}
public function setNumberResources($numberResources) {
$this->numberResources = $numberResources;
}
public function getNumberResources() {
return $this->numberResources;
}
public function setCssResponseBytes($cssResponseBytes) {
$this->cssResponseBytes = $cssResponseBytes;
}
public function getCssResponseBytes() {
return $this->cssResponseBytes;
}
public function setJavascriptResponseBytes($javascriptResponseBytes) {
$this->javascriptResponseBytes = $javascriptResponseBytes;
}
public function getJavascriptResponseBytes() {
return $this->javascriptResponseBytes;
}
public function setImageResponseBytes($imageResponseBytes) {
$this->imageResponseBytes = $imageResponseBytes;
}
public function getImageResponseBytes() {
return $this->imageResponseBytes;
}
public function setNumberHosts($numberHosts) {
$this->numberHosts = $numberHosts;
}
public function getNumberHosts() {
return $this->numberHosts;
}
public function setNumberStaticResources($numberStaticResources) {
$this->numberStaticResources = $numberStaticResources;
}
public function getNumberStaticResources() {
return $this->numberStaticResources;
}
public function setHtmlResponseBytes($htmlResponseBytes) {
$this->htmlResponseBytes = $htmlResponseBytes;
}
public function getHtmlResponseBytes() {
return $this->htmlResponseBytes;
}
public function setNumberJsResources($numberJsResources) {
$this->numberJsResources = $numberJsResources;
}
public function getNumberJsResources() {
return $this->numberJsResources;
}
public function setTextResponseBytes($textResponseBytes) {
$this->textResponseBytes = $textResponseBytes;
}
public function getTextResponseBytes() {
return $this->textResponseBytes;
}
}
class ResultVersion extends apiModel {
public $major;
public $minor;
public function setMajor($major) {
$this->major = $major;
}
public function getMajor() {
return $this->major;
}
public function setMinor($minor) {
$this->minor = $minor;
}
public function getMinor() {
return $this->minor;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiPagespeedonlineService.php | PHP | asf20 | 15,172 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "files" collection of methods.
* Typical usage is:
* <code>
* $driveService = new apiDriveService(...);
* $files = $driveService->files;
* </code>
*/
class FilesServiceResource extends apiServiceResource {
/**
* Inserts a file, and any settable metadata or blob content sent with the request. (files.insert)
*
* @param DriveFile $postBody
* @return DriveFile
*/
public function insert(DriveFile $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new DriveFile($data);
} else {
return $data;
}
}
/**
* Updates file metadata and/or content. This method supports patch semantics. (files.patch)
*
* @param string $id The id for the file in question.
* @param DriveFile $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool updateViewedDate Whether to update the view date after successfully updating the file.
* @opt_param bool newRevision Whether a blob upload should create a new revision. If not set or false, the blob data in the current head revision will be replaced.
* @return DriveFile
*/
public function patch($id, DriveFile $postBody, $optParams = array()) {
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new DriveFile($data);
} else {
return $data;
}
}
/**
* Updates file metadata and/or content (files.update)
*
* @param string $id The id for the file in question.
* @param DriveFile $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool updateViewedDate Whether to update the view date after successfully updating the file.
* @opt_param bool newRevision Whether a blob upload should create a new revision. If not set or false, the blob data in the current head revision will be replaced.
* @return DriveFile
*/
public function update($id, DriveFile $postBody, $optParams = array()) {
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new DriveFile($data);
} else {
return $data;
}
}
/**
* Gets a file's metadata by id. (files.get)
*
* @param string $id The id for the file in question.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool updateViewedDate Whether to update the view date after successfully retrieving the file.
* @opt_param string projection Restrict information returned for simplicity and optimization.
* @return DriveFile
*/
public function get($id, $optParams = array()) {
$params = array('id' => $id);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new DriveFile($data);
} else {
return $data;
}
}
}
/**
* Service definition for Drive (v1).
*
* <p>
* The API to interact with Drive
* </p>
*
* <p>
* For more information about this service, see the
* <a href="" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiDriveService extends apiService {
public $files;
/**
* Constructs the internal representation of the Drive service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/drive/v1/';
$this->version = 'v1';
$this->serviceName = 'drive';
$apiClient->addService($this->serviceName, $this->version);
$this->files = new FilesServiceResource($this, $this->serviceName, 'files', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/drive.file"], "mediaUpload": {"maxSize": "10GB", "accept": ["*/*"], "protocols": {"simple": {"path": "/upload/drive/v1/files", "multipart": true}, "resumable": {"path": "/resumable/upload/drive/v1/files", "multipart": true}}}, "request": {"$ref": "File"}, "response": {"$ref": "File"}, "httpMethod": "POST", "path": "files", "id": "drive.files.insert"}, "get": {"scopes": ["https://www.googleapis.com/auth/drive.file"], "parameters": {"updateViewedDate": {"default": "true", "type": "boolean", "location": "query"}, "id": {"required": true, "type": "string", "location": "path"}, "projection": {"enum": ["BASIC", "FULL"], "type": "string", "location": "query"}}, "id": "drive.files.get", "httpMethod": "GET", "path": "files/{id}", "response": {"$ref": "File"}}, "update": {"scopes": ["https://www.googleapis.com/auth/drive.file"], "parameters": {"updateViewedDate": {"default": "true", "type": "boolean", "location": "query"}, "id": {"required": true, "type": "string", "location": "path"}, "newRevision": {"default": "false", "type": "boolean", "location": "query"}}, "mediaUpload": {"maxSize": "10GB", "accept": ["*/*"], "protocols": {"simple": {"path": "/upload/drive/v1/files/{id}", "multipart": true}, "resumable": {"path": "/resumable/upload/drive/v1/files/{id}", "multipart": true}}}, "request": {"$ref": "File"}, "id": "drive.files.update", "httpMethod": "PUT", "path": "files/{id}", "response": {"$ref": "File"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/drive.file"], "parameters": {"updateViewedDate": {"default": "true", "type": "boolean", "location": "query"}, "id": {"required": true, "type": "string", "location": "path"}, "newRevision": {"default": "false", "type": "boolean", "location": "query"}}, "request": {"$ref": "File"}, "id": "drive.files.patch", "httpMethod": "PATCH", "path": "files/{id}", "response": {"$ref": "File"}}}}', true));
}
}
class DriveFile extends apiModel {
public $mimeType;
public $kind;
public $description;
public $title;
public $modifiedByMeDate;
protected $__labelsType = 'DriveFileLabels';
protected $__labelsDataType = '';
public $labels;
protected $__indexableTextType = 'DriveFileIndexableText';
protected $__indexableTextDataType = '';
public $indexableText;
protected $__parentsCollectionType = 'DriveFileParentsCollection';
protected $__parentsCollectionDataType = 'array';
public $parentsCollection;
public $downloadUrl;
protected $__userPermissionType = 'Permission';
protected $__userPermissionDataType = '';
public $userPermission;
public $etag;
public $modifiedDate;
public $createdDate;
public $fileExtension;
public $lastViewedDate;
public $id;
public $selfLink;
public function setMimeType($mimeType) {
$this->mimeType = $mimeType;
}
public function getMimeType() {
return $this->mimeType;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setModifiedByMeDate($modifiedByMeDate) {
$this->modifiedByMeDate = $modifiedByMeDate;
}
public function getModifiedByMeDate() {
return $this->modifiedByMeDate;
}
public function setLabels(DriveFileLabels $labels) {
$this->labels = $labels;
}
public function getLabels() {
return $this->labels;
}
public function setIndexableText(DriveFileIndexableText $indexableText) {
$this->indexableText = $indexableText;
}
public function getIndexableText() {
return $this->indexableText;
}
public function setParentsCollection(/* array(DriveFileParentsCollection) */ $parentsCollection) {
$this->assertIsArray($parentsCollection, 'DriveFileParentsCollection', __METHOD__);
$this->parentsCollection = $parentsCollection;
}
public function getParentsCollection() {
return $this->parentsCollection;
}
public function setDownloadUrl($downloadUrl) {
$this->downloadUrl = $downloadUrl;
}
public function getDownloadUrl() {
return $this->downloadUrl;
}
public function setUserPermission(Permission $userPermission) {
$this->userPermission = $userPermission;
}
public function getUserPermission() {
return $this->userPermission;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setModifiedDate($modifiedDate) {
$this->modifiedDate = $modifiedDate;
}
public function getModifiedDate() {
return $this->modifiedDate;
}
public function setCreatedDate($createdDate) {
$this->createdDate = $createdDate;
}
public function getCreatedDate() {
return $this->createdDate;
}
public function setFileExtension($fileExtension) {
$this->fileExtension = $fileExtension;
}
public function getFileExtension() {
return $this->fileExtension;
}
public function setLastViewedDate($lastViewedDate) {
$this->lastViewedDate = $lastViewedDate;
}
public function getLastViewedDate() {
return $this->lastViewedDate;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class DriveFileIndexableText extends apiModel {
public $text;
public $type;
public function setText($text) {
$this->text = $text;
}
public function getText() {
return $this->text;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class DriveFileLabels extends apiModel {
public $hidden;
public $starred;
public $trashed;
public function setHidden($hidden) {
$this->hidden = $hidden;
}
public function getHidden() {
return $this->hidden;
}
public function setStarred($starred) {
$this->starred = $starred;
}
public function getStarred() {
return $this->starred;
}
public function setTrashed($trashed) {
$this->trashed = $trashed;
}
public function getTrashed() {
return $this->trashed;
}
}
class DriveFileParentsCollection extends apiModel {
public $kind;
public $id;
public $parentLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setParentLink($parentLink) {
$this->parentLink = $parentLink;
}
public function getParentLink() {
return $this->parentLink;
}
}
class Permission extends apiModel {
public $kind;
public $value;
public $id;
public $etag;
public $role;
public $type;
public $additionalRoles;
public $selfLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setRole($role) {
$this->role = $role;
}
public function getRole() {
return $this->role;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setAdditionalRoles(/* array(string) */ $additionalRoles) {
$this->assertIsArray($additionalRoles, 'string', __METHOD__);
$this->additionalRoles = $additionalRoles;
}
public function getAdditionalRoles() {
return $this->additionalRoles;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiDriveService.php | PHP | asf20 | 13,142 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "bookshelves" collection of methods.
* Typical usage is:
* <code>
* $booksService = new apiBooksService(...);
* $bookshelves = $booksService->bookshelves;
* </code>
*/
class BookshelvesServiceResource extends apiServiceResource {
/**
* Retrieves a list of public bookshelves for the specified user. (bookshelves.list)
*
* @param string $userId Id of user for whom to retrieve bookshelves.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
* @return Bookshelves
*/
public function listBookshelves($userId, $optParams = array()) {
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Bookshelves($data);
} else {
return $data;
}
}
/**
* Retrieves a specific bookshelf for the specified user. (bookshelves.get)
*
* @param string $userId Id of user for whom to retrieve bookshelves.
* @param string $shelf Id of bookshelf to retrieve.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
* @return Bookshelf
*/
public function get($userId, $shelf, $optParams = array()) {
$params = array('userId' => $userId, 'shelf' => $shelf);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Bookshelf($data);
} else {
return $data;
}
}
}
/**
* The "volumes" collection of methods.
* Typical usage is:
* <code>
* $booksService = new apiBooksService(...);
* $volumes = $booksService->volumes;
* </code>
*/
class BookshelvesVolumesServiceResource extends apiServiceResource {
/**
* Retrieves volumes in a specific bookshelf for the specified user. (volumes.list)
*
* @param string $userId Id of user for whom to retrieve bookshelf volumes.
* @param string $shelf Id of bookshelf to retrieve volumes.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param bool showPreorders Set to true to show pre-ordered books. Defaults to false.
* @opt_param string maxResults Maximum number of results to return
* @opt_param string source String to identify the originator of this request.
* @opt_param string startIndex Index of the first element to return (starts at 0)
* @return Volumes
*/
public function listBookshelvesVolumes($userId, $shelf, $optParams = array()) {
$params = array('userId' => $userId, 'shelf' => $shelf);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Volumes($data);
} else {
return $data;
}
}
}
/**
* The "myconfig" collection of methods.
* Typical usage is:
* <code>
* $booksService = new apiBooksService(...);
* $myconfig = $booksService->myconfig;
* </code>
*/
class MyconfigServiceResource extends apiServiceResource {
/**
* Release downloaded content access restriction. (myconfig.releaseDownloadAccess)
*
* @param string $volumeIds The volume(s) to release restrictions for.
* @param string $cpksver The device/version identifier from which to release the restriction.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string locale ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
* @return DownloadAccesses
*/
public function releaseDownloadAccess($volumeIds, $cpksver, $optParams = array()) {
$params = array('volumeIds' => $volumeIds, 'cpksver' => $cpksver);
$params = array_merge($params, $optParams);
$data = $this->__call('releaseDownloadAccess', array($params));
if ($this->useObjects()) {
return new DownloadAccesses($data);
} else {
return $data;
}
}
/**
* Request concurrent and download access restrictions. (myconfig.requestAccess)
*
* @param string $source String to identify the originator of this request.
* @param string $volumeId The volume to request concurrent/download restrictions for.
* @param string $nonce The client nonce value.
* @param string $cpksver The device/version identifier from which to request the restrictions.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string locale ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @return RequestAccess
*/
public function requestAccess($source, $volumeId, $nonce, $cpksver, $optParams = array()) {
$params = array('source' => $source, 'volumeId' => $volumeId, 'nonce' => $nonce, 'cpksver' => $cpksver);
$params = array_merge($params, $optParams);
$data = $this->__call('requestAccess', array($params));
if ($this->useObjects()) {
return new RequestAccess($data);
} else {
return $data;
}
}
/**
* Request downloaded content access for specified volumes on the My eBooks shelf.
* (myconfig.syncVolumeLicenses)
*
* @param string $source String to identify the originator of this request.
* @param string $nonce The client nonce value.
* @param string $cpksver The device/version identifier from which to release the restriction.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string locale ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US.
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string volumeIds The volume(s) to request download restrictions for.
* @return Volumes
*/
public function syncVolumeLicenses($source, $nonce, $cpksver, $optParams = array()) {
$params = array('source' => $source, 'nonce' => $nonce, 'cpksver' => $cpksver);
$params = array_merge($params, $optParams);
$data = $this->__call('syncVolumeLicenses', array($params));
if ($this->useObjects()) {
return new Volumes($data);
} else {
return $data;
}
}
}
/**
* The "volumes" collection of methods.
* Typical usage is:
* <code>
* $booksService = new apiBooksService(...);
* $volumes = $booksService->volumes;
* </code>
*/
class VolumesServiceResource extends apiServiceResource {
/**
* Performs a book search. (volumes.list)
*
* @param string $q Full-text search query string.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string orderBy Sort search results.
* @opt_param string projection Restrict information returned to a set of selected fields.
* @opt_param string libraryRestrict Restrict search to this user's library.
* @opt_param string langRestrict Restrict results to books with this language code.
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string printType Restrict to books or magazines.
* @opt_param string maxResults Maximum number of results to return.
* @opt_param string filter Filter search results.
* @opt_param string source String to identify the originator of this request.
* @opt_param string startIndex Index of the first result to return (starts at 0)
* @opt_param string download Restrict to volumes by download availability.
* @opt_param string partner Identifier of partner for whom to restrict and brand results.
* @opt_param bool showPreorders Set to true to show books available for preorder. Defaults to false.
* @return Volumes
*/
public function listVolumes($q, $optParams = array()) {
$params = array('q' => $q);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Volumes($data);
} else {
return $data;
}
}
/**
* Gets volume information for a single volume. (volumes.get)
*
* @param string $volumeId Id of volume to retrieve.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string source String to identify the originator of this request.
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string projection Restrict information returned to a set of selected fields.
* @opt_param string partner Identifier of partner for whom to brand results.
* @return Volume
*/
public function get($volumeId, $optParams = array()) {
$params = array('volumeId' => $volumeId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Volume($data);
} else {
return $data;
}
}
}
/**
* The "mylibrary" collection of methods.
* Typical usage is:
* <code>
* $booksService = new apiBooksService(...);
* $mylibrary = $booksService->mylibrary;
* </code>
*/
class MylibraryServiceResource extends apiServiceResource {
}
/**
* The "bookshelves" collection of methods.
* Typical usage is:
* <code>
* $booksService = new apiBooksService(...);
* $bookshelves = $booksService->bookshelves;
* </code>
*/
class MylibraryBookshelvesServiceResource extends apiServiceResource {
/**
* Clears all volumes from a bookshelf. (bookshelves.clearVolumes)
*
* @param string $shelf Id of bookshelf from which to remove a volume.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
*/
public function clearVolumes($shelf, $optParams = array()) {
$params = array('shelf' => $shelf);
$params = array_merge($params, $optParams);
$data = $this->__call('clearVolumes', array($params));
return $data;
}
/**
* Removes a volume from a bookshelf. (bookshelves.removeVolume)
*
* @param string $shelf Id of bookshelf from which to remove a volume.
* @param string $volumeId Id of volume to remove.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
*/
public function removeVolume($shelf, $volumeId, $optParams = array()) {
$params = array('shelf' => $shelf, 'volumeId' => $volumeId);
$params = array_merge($params, $optParams);
$data = $this->__call('removeVolume', array($params));
return $data;
}
/**
* Retrieves a list of bookshelves belonging to the authenticated user. (bookshelves.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
* @return Bookshelves
*/
public function listMylibraryBookshelves($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Bookshelves($data);
} else {
return $data;
}
}
/**
* Adds a volume to a bookshelf. (bookshelves.addVolume)
*
* @param string $shelf Id of bookshelf to which to add a volume.
* @param string $volumeId Id of volume to add.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
*/
public function addVolume($shelf, $volumeId, $optParams = array()) {
$params = array('shelf' => $shelf, 'volumeId' => $volumeId);
$params = array_merge($params, $optParams);
$data = $this->__call('addVolume', array($params));
return $data;
}
/**
* Retrieves a specific bookshelf belonging to the authenticated user. (bookshelves.get)
*
* @param string $shelf Id of bookshelf to retrieve.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
* @return Bookshelf
*/
public function get($shelf, $optParams = array()) {
$params = array('shelf' => $shelf);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Bookshelf($data);
} else {
return $data;
}
}
}
/**
* The "volumes" collection of methods.
* Typical usage is:
* <code>
* $booksService = new apiBooksService(...);
* $volumes = $booksService->volumes;
* </code>
*/
class MylibraryBookshelvesVolumesServiceResource extends apiServiceResource {
/**
* Gets volume information for volumes on a bookshelf. (volumes.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string shelf The bookshelf id or name retrieve volumes for.
* @opt_param string projection Restrict information returned to a set of selected fields.
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param bool showPreorders Set to true to show pre-ordered books. Defaults to false.
* @opt_param string maxResults Maximum number of results to return
* @opt_param string q Full-text search query string in this bookshelf.
* @opt_param string source String to identify the originator of this request.
* @opt_param string startIndex Index of the first element to return (starts at 0)
* @return Volumes
*/
public function listMylibraryBookshelvesVolumes($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Volumes($data);
} else {
return $data;
}
}
}
/**
* The "annotations" collection of methods.
* Typical usage is:
* <code>
* $booksService = new apiBooksService(...);
* $annotations = $booksService->annotations;
* </code>
*/
class MylibraryAnnotationsServiceResource extends apiServiceResource {
/**
* Inserts a new annotation. (annotations.insert)
*
* @param Annotation $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
* @return Annotation
*/
public function insert(Annotation $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Annotation($data);
} else {
return $data;
}
}
/**
* Gets an annotation by its id. (annotations.get)
*
* @param string $annotationId The annotation identifier for the annotation to retrieve.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
* @return Annotation
*/
public function get($annotationId, $optParams = array()) {
$params = array('annotationId' => $annotationId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Annotation($data);
} else {
return $data;
}
}
/**
* Retrieves a list of annotations, possibly filtered. (annotations.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string source String to identify the originator of this request.
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string volumeId The volume to restrict annotations to.
* @opt_param string maxResults Maximum number of results to return
* @opt_param string pageToken The value of the nextToken from the previous page.
* @opt_param string pageIds The page id(s) for the volume that is being queried.
* @opt_param string contentVersion The content version for the requested volume.
* @opt_param string layerId The layer id to limit annotation by.
* @return Annotations
*/
public function listMylibraryAnnotations($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Annotations($data);
} else {
return $data;
}
}
/**
* Updates an existing annotation. (annotations.update)
*
* @param string $annotationId The annotation identifier for the annotation to update.
* @param Annotation $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
* @return Annotation
*/
public function update($annotationId, Annotation $postBody, $optParams = array()) {
$params = array('annotationId' => $annotationId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Annotation($data);
} else {
return $data;
}
}
/**
* Deletes an annotation. (annotations.delete)
*
* @param string $annotationId The annotation identifier for the annotation to delete.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string country ISO-3166-1 code to override the IP-based location.
* @opt_param string source String to identify the originator of this request.
*/
public function delete($annotationId, $optParams = array()) {
$params = array('annotationId' => $annotationId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* Service definition for Books (v1).
*
* <p>
* Lets you search for books and manage your Google Books library.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://code.google.com/apis/books/docs/v1/getting_started.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiBooksService extends apiService {
public $bookshelves;
public $bookshelves_volumes;
public $myconfig;
public $volumes;
public $mylibrary;
public $mylibrary_bookshelves;
public $mylibrary_annotations;
/**
* Constructs the internal representation of the Books service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/books/v1/';
$this->version = 'v1';
$this->serviceName = 'books';
$apiClient->addService($this->serviceName, $this->version);
$this->bookshelves = new BookshelvesServiceResource($this, $this->serviceName, 'bookshelves', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "userId": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "id": "books.bookshelves.list", "httpMethod": "GET", "path": "users/{userId}/bookshelves", "response": {"$ref": "Bookshelves"}}, "get": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "userId": {"required": true, "type": "string", "location": "path"}, "shelf": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "id": "books.bookshelves.get", "httpMethod": "GET", "path": "users/{userId}/bookshelves/{shelf}", "response": {"$ref": "Bookshelf"}}}}', true));
$this->bookshelves_volumes = new BookshelvesVolumesServiceResource($this, $this->serviceName, 'volumes', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "showPreorders": {"type": "boolean", "location": "query"}, "maxResults": {"format": "uint32", "minimum": "0", "type": "integer", "location": "query"}, "source": {"type": "string", "location": "query"}, "startIndex": {"format": "uint32", "minimum": "0", "type": "integer", "location": "query"}, "shelf": {"required": true, "type": "string", "location": "path"}, "userId": {"required": true, "type": "string", "location": "path"}}, "id": "books.bookshelves.volumes.list", "httpMethod": "GET", "path": "users/{userId}/bookshelves/{shelf}/volumes", "response": {"$ref": "Volumes"}}}}', true));
$this->myconfig = new MyconfigServiceResource($this, $this->serviceName, 'myconfig', json_decode('{"methods": {"releaseDownloadAccess": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"locale": {"type": "string", "location": "query"}, "country": {"type": "string", "location": "query"}, "source": {"type": "string", "location": "query"}, "cpksver": {"required": true, "type": "string", "location": "query"}, "volumeIds": {"repeated": true, "required": true, "type": "string", "location": "query"}}, "id": "books.myconfig.releaseDownloadAccess", "httpMethod": "POST", "path": "myconfig/releaseDownloadAccess", "response": {"$ref": "DownloadAccesses"}}, "requestAccess": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"nonce": {"required": true, "type": "string", "location": "query"}, "locale": {"type": "string", "location": "query"}, "country": {"type": "string", "location": "query"}, "cpksver": {"required": true, "type": "string", "location": "query"}, "volumeId": {"required": true, "type": "string", "location": "query"}, "source": {"required": true, "type": "string", "location": "query"}}, "id": "books.myconfig.requestAccess", "httpMethod": "POST", "path": "myconfig/requestAccess", "response": {"$ref": "RequestAccess"}}, "syncVolumeLicenses": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"nonce": {"required": true, "type": "string", "location": "query"}, "locale": {"type": "string", "location": "query"}, "country": {"type": "string", "location": "query"}, "cpksver": {"required": true, "type": "string", "location": "query"}, "source": {"required": true, "type": "string", "location": "query"}, "volumeIds": {"repeated": true, "type": "string", "location": "query"}}, "id": "books.myconfig.syncVolumeLicenses", "httpMethod": "POST", "path": "myconfig/syncVolumeLicenses", "response": {"$ref": "Volumes"}}}}', true));
$this->volumes = new VolumesServiceResource($this, $this->serviceName, 'volumes', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"orderBy": {"enum": ["newest", "relevance"], "type": "string", "location": "query"}, "filter": {"enum": ["ebooks", "free-ebooks", "full", "paid-ebooks", "partial"], "type": "string", "location": "query"}, "projection": {"enum": ["full", "lite"], "type": "string", "location": "query"}, "libraryRestrict": {"enum": ["my-library", "no-restrict"], "type": "string", "location": "query"}, "langRestrict": {"type": "string", "location": "query"}, "country": {"type": "string", "location": "query"}, "printType": {"enum": ["all", "books", "magazines"], "type": "string", "location": "query"}, "maxResults": {"format": "uint32", "maximum": "40", "minimum": "0", "location": "query", "type": "integer"}, "q": {"required": true, "type": "string", "location": "query"}, "source": {"type": "string", "location": "query"}, "startIndex": {"format": "uint32", "minimum": "0", "type": "integer", "location": "query"}, "download": {"enum": ["epub"], "type": "string", "location": "query"}, "partner": {"type": "string", "location": "query"}, "showPreorders": {"type": "boolean", "location": "query"}}, "id": "books.volumes.list", "httpMethod": "GET", "path": "volumes", "response": {"$ref": "Volumes"}}, "get": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"partner": {"type": "string", "location": "query"}, "source": {"type": "string", "location": "query"}, "projection": {"enum": ["full", "lite"], "type": "string", "location": "query"}, "volumeId": {"required": true, "type": "string", "location": "path"}, "country": {"type": "string", "location": "query"}}, "id": "books.volumes.get", "httpMethod": "GET", "path": "volumes/{volumeId}", "response": {"$ref": "Volume"}}}}', true));
$this->mylibrary = new MylibraryServiceResource($this, $this->serviceName, 'mylibrary', json_decode('{}', true));
$this->mylibrary_bookshelves = new MylibraryBookshelvesServiceResource($this, $this->serviceName, 'bookshelves', json_decode('{"methods": {"clearVolumes": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "shelf": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "httpMethod": "POST", "path": "mylibrary/bookshelves/{shelf}/clearVolumes", "id": "books.mylibrary.bookshelves.clearVolumes"}, "removeVolume": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "volumeId": {"required": true, "type": "string", "location": "query"}, "shelf": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "httpMethod": "POST", "path": "mylibrary/bookshelves/{shelf}/removeVolume", "id": "books.mylibrary.bookshelves.removeVolume"}, "list": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "source": {"type": "string", "location": "query"}}, "response": {"$ref": "Bookshelves"}, "httpMethod": "GET", "path": "mylibrary/bookshelves", "id": "books.mylibrary.bookshelves.list"}, "addVolume": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "volumeId": {"required": true, "type": "string", "location": "query"}, "shelf": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "httpMethod": "POST", "path": "mylibrary/bookshelves/{shelf}/addVolume", "id": "books.mylibrary.bookshelves.addVolume"}, "get": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "shelf": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "id": "books.mylibrary.bookshelves.get", "httpMethod": "GET", "path": "mylibrary/bookshelves/{shelf}", "response": {"$ref": "Bookshelf"}}}}', true));
$this->mylibrary_annotations = new MylibraryAnnotationsServiceResource($this, $this->serviceName, 'annotations', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "source": {"type": "string", "location": "query"}}, "request": {"$ref": "Annotation"}, "id": "books.mylibrary.annotations.insert", "httpMethod": "POST", "path": "mylibrary/annotations", "response": {"$ref": "Annotation"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "annotationId": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "httpMethod": "DELETE", "path": "mylibrary/annotations/{annotationId}", "id": "books.mylibrary.annotations.delete"}, "list": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "country": {"type": "string", "location": "query"}, "volumeId": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "maximum": "40", "minimum": "0", "location": "query", "type": "integer"}, "source": {"type": "string", "location": "query"}, "pageIds": {"repeated": true, "type": "string", "location": "query"}, "contentVersion": {"type": "string", "location": "query"}, "layerId": {"type": "string", "location": "query"}}, "response": {"$ref": "Annotations"}, "httpMethod": "GET", "path": "mylibrary/annotations", "id": "books.mylibrary.annotations.list"}, "update": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "annotationId": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "request": {"$ref": "Annotation"}, "id": "books.mylibrary.annotations.update", "httpMethod": "PUT", "path": "mylibrary/annotations/{annotationId}", "response": {"$ref": "Annotation"}}, "get": {"scopes": ["https://www.googleapis.com/auth/books"], "parameters": {"country": {"type": "string", "location": "query"}, "annotationId": {"required": true, "type": "string", "location": "path"}, "source": {"type": "string", "location": "query"}}, "id": "books.mylibrary.annotations.get", "httpMethod": "GET", "path": "mylibrary/annotations/{annotationId}", "response": {"$ref": "Annotation"}}}}', true));
}
}
class Annotation extends apiModel {
public $kind;
public $updated;
public $created;
public $beforeSelectedText;
protected $__currentVersionRangesType = 'AnnotationCurrentVersionRanges';
protected $__currentVersionRangesDataType = '';
public $currentVersionRanges;
public $afterSelectedText;
protected $__clientVersionRangesType = 'AnnotationClientVersionRanges';
protected $__clientVersionRangesDataType = '';
public $clientVersionRanges;
public $volumeId;
public $pageIds;
public $layerId;
public $selectedText;
public $highlightStyle;
public $data;
public $id;
public $selfLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setBeforeSelectedText($beforeSelectedText) {
$this->beforeSelectedText = $beforeSelectedText;
}
public function getBeforeSelectedText() {
return $this->beforeSelectedText;
}
public function setCurrentVersionRanges(AnnotationCurrentVersionRanges $currentVersionRanges) {
$this->currentVersionRanges = $currentVersionRanges;
}
public function getCurrentVersionRanges() {
return $this->currentVersionRanges;
}
public function setAfterSelectedText($afterSelectedText) {
$this->afterSelectedText = $afterSelectedText;
}
public function getAfterSelectedText() {
return $this->afterSelectedText;
}
public function setClientVersionRanges(AnnotationClientVersionRanges $clientVersionRanges) {
$this->clientVersionRanges = $clientVersionRanges;
}
public function getClientVersionRanges() {
return $this->clientVersionRanges;
}
public function setVolumeId($volumeId) {
$this->volumeId = $volumeId;
}
public function getVolumeId() {
return $this->volumeId;
}
public function setPageIds(/* array(string) */ $pageIds) {
$this->assertIsArray($pageIds, 'string', __METHOD__);
$this->pageIds = $pageIds;
}
public function getPageIds() {
return $this->pageIds;
}
public function setLayerId($layerId) {
$this->layerId = $layerId;
}
public function getLayerId() {
return $this->layerId;
}
public function setSelectedText($selectedText) {
$this->selectedText = $selectedText;
}
public function getSelectedText() {
return $this->selectedText;
}
public function setHighlightStyle($highlightStyle) {
$this->highlightStyle = $highlightStyle;
}
public function getHighlightStyle() {
return $this->highlightStyle;
}
public function setData($data) {
$this->data = $data;
}
public function getData() {
return $this->data;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class AnnotationClientVersionRanges extends apiModel {
public $contentVersion;
protected $__gbTextRangeType = 'BooksAnnotationsRange';
protected $__gbTextRangeDataType = '';
public $gbTextRange;
protected $__cfiRangeType = 'BooksAnnotationsRange';
protected $__cfiRangeDataType = '';
public $cfiRange;
protected $__gbImageRangeType = 'BooksAnnotationsRange';
protected $__gbImageRangeDataType = '';
public $gbImageRange;
public function setContentVersion($contentVersion) {
$this->contentVersion = $contentVersion;
}
public function getContentVersion() {
return $this->contentVersion;
}
public function setGbTextRange(BooksAnnotationsRange $gbTextRange) {
$this->gbTextRange = $gbTextRange;
}
public function getGbTextRange() {
return $this->gbTextRange;
}
public function setCfiRange(BooksAnnotationsRange $cfiRange) {
$this->cfiRange = $cfiRange;
}
public function getCfiRange() {
return $this->cfiRange;
}
public function setGbImageRange(BooksAnnotationsRange $gbImageRange) {
$this->gbImageRange = $gbImageRange;
}
public function getGbImageRange() {
return $this->gbImageRange;
}
}
class AnnotationCurrentVersionRanges extends apiModel {
public $contentVersion;
protected $__gbTextRangeType = 'BooksAnnotationsRange';
protected $__gbTextRangeDataType = '';
public $gbTextRange;
protected $__cfiRangeType = 'BooksAnnotationsRange';
protected $__cfiRangeDataType = '';
public $cfiRange;
protected $__gbImageRangeType = 'BooksAnnotationsRange';
protected $__gbImageRangeDataType = '';
public $gbImageRange;
public function setContentVersion($contentVersion) {
$this->contentVersion = $contentVersion;
}
public function getContentVersion() {
return $this->contentVersion;
}
public function setGbTextRange(BooksAnnotationsRange $gbTextRange) {
$this->gbTextRange = $gbTextRange;
}
public function getGbTextRange() {
return $this->gbTextRange;
}
public function setCfiRange(BooksAnnotationsRange $cfiRange) {
$this->cfiRange = $cfiRange;
}
public function getCfiRange() {
return $this->cfiRange;
}
public function setGbImageRange(BooksAnnotationsRange $gbImageRange) {
$this->gbImageRange = $gbImageRange;
}
public function getGbImageRange() {
return $this->gbImageRange;
}
}
class Annotations extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Annotation';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $totalItems;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Annotation) */ $items) {
$this->assertIsArray($items, 'Annotation', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
}
class BooksAnnotationsRange extends apiModel {
public $startPosition;
public $endPosition;
public $startOffset;
public $endOffset;
public function setStartPosition($startPosition) {
$this->startPosition = $startPosition;
}
public function getStartPosition() {
return $this->startPosition;
}
public function setEndPosition($endPosition) {
$this->endPosition = $endPosition;
}
public function getEndPosition() {
return $this->endPosition;
}
public function setStartOffset($startOffset) {
$this->startOffset = $startOffset;
}
public function getStartOffset() {
return $this->startOffset;
}
public function setEndOffset($endOffset) {
$this->endOffset = $endOffset;
}
public function getEndOffset() {
return $this->endOffset;
}
}
class Bookshelf extends apiModel {
public $kind;
public $description;
public $created;
public $volumeCount;
public $title;
public $updated;
public $access;
public $volumesLastUpdated;
public $id;
public $selfLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setVolumeCount($volumeCount) {
$this->volumeCount = $volumeCount;
}
public function getVolumeCount() {
return $this->volumeCount;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setAccess($access) {
$this->access = $access;
}
public function getAccess() {
return $this->access;
}
public function setVolumesLastUpdated($volumesLastUpdated) {
$this->volumesLastUpdated = $volumesLastUpdated;
}
public function getVolumesLastUpdated() {
return $this->volumesLastUpdated;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class Bookshelves extends apiModel {
protected $__itemsType = 'Bookshelf';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Bookshelf) */ $items) {
$this->assertIsArray($items, 'Bookshelf', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class ConcurrentAccessRestriction extends apiModel {
public $nonce;
public $kind;
public $restricted;
public $volumeId;
public $maxConcurrentDevices;
public $deviceAllowed;
public $source;
public $timeWindowSeconds;
public $signature;
public $reasonCode;
public $message;
public function setNonce($nonce) {
$this->nonce = $nonce;
}
public function getNonce() {
return $this->nonce;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setRestricted($restricted) {
$this->restricted = $restricted;
}
public function getRestricted() {
return $this->restricted;
}
public function setVolumeId($volumeId) {
$this->volumeId = $volumeId;
}
public function getVolumeId() {
return $this->volumeId;
}
public function setMaxConcurrentDevices($maxConcurrentDevices) {
$this->maxConcurrentDevices = $maxConcurrentDevices;
}
public function getMaxConcurrentDevices() {
return $this->maxConcurrentDevices;
}
public function setDeviceAllowed($deviceAllowed) {
$this->deviceAllowed = $deviceAllowed;
}
public function getDeviceAllowed() {
return $this->deviceAllowed;
}
public function setSource($source) {
$this->source = $source;
}
public function getSource() {
return $this->source;
}
public function setTimeWindowSeconds($timeWindowSeconds) {
$this->timeWindowSeconds = $timeWindowSeconds;
}
public function getTimeWindowSeconds() {
return $this->timeWindowSeconds;
}
public function setSignature($signature) {
$this->signature = $signature;
}
public function getSignature() {
return $this->signature;
}
public function setReasonCode($reasonCode) {
$this->reasonCode = $reasonCode;
}
public function getReasonCode() {
return $this->reasonCode;
}
public function setMessage($message) {
$this->message = $message;
}
public function getMessage() {
return $this->message;
}
}
class DownloadAccessRestriction extends apiModel {
public $nonce;
public $kind;
public $justAcquired;
public $maxDownloadDevices;
public $downloadsAcquired;
public $signature;
public $volumeId;
public $deviceAllowed;
public $source;
public $restricted;
public $reasonCode;
public $message;
public function setNonce($nonce) {
$this->nonce = $nonce;
}
public function getNonce() {
return $this->nonce;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setJustAcquired($justAcquired) {
$this->justAcquired = $justAcquired;
}
public function getJustAcquired() {
return $this->justAcquired;
}
public function setMaxDownloadDevices($maxDownloadDevices) {
$this->maxDownloadDevices = $maxDownloadDevices;
}
public function getMaxDownloadDevices() {
return $this->maxDownloadDevices;
}
public function setDownloadsAcquired($downloadsAcquired) {
$this->downloadsAcquired = $downloadsAcquired;
}
public function getDownloadsAcquired() {
return $this->downloadsAcquired;
}
public function setSignature($signature) {
$this->signature = $signature;
}
public function getSignature() {
return $this->signature;
}
public function setVolumeId($volumeId) {
$this->volumeId = $volumeId;
}
public function getVolumeId() {
return $this->volumeId;
}
public function setDeviceAllowed($deviceAllowed) {
$this->deviceAllowed = $deviceAllowed;
}
public function getDeviceAllowed() {
return $this->deviceAllowed;
}
public function setSource($source) {
$this->source = $source;
}
public function getSource() {
return $this->source;
}
public function setRestricted($restricted) {
$this->restricted = $restricted;
}
public function getRestricted() {
return $this->restricted;
}
public function setReasonCode($reasonCode) {
$this->reasonCode = $reasonCode;
}
public function getReasonCode() {
return $this->reasonCode;
}
public function setMessage($message) {
$this->message = $message;
}
public function getMessage() {
return $this->message;
}
}
class DownloadAccesses extends apiModel {
protected $__downloadAccessListType = 'DownloadAccessRestriction';
protected $__downloadAccessListDataType = 'array';
public $downloadAccessList;
public $kind;
public function setDownloadAccessList(/* array(DownloadAccessRestriction) */ $downloadAccessList) {
$this->assertIsArray($downloadAccessList, 'DownloadAccessRestriction', __METHOD__);
$this->downloadAccessList = $downloadAccessList;
}
public function getDownloadAccessList() {
return $this->downloadAccessList;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class ReadingPosition extends apiModel {
public $kind;
public $gbImagePosition;
public $epubCfiPosition;
public $updated;
public $volumeId;
public $pdfPosition;
public $gbTextPosition;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setGbImagePosition($gbImagePosition) {
$this->gbImagePosition = $gbImagePosition;
}
public function getGbImagePosition() {
return $this->gbImagePosition;
}
public function setEpubCfiPosition($epubCfiPosition) {
$this->epubCfiPosition = $epubCfiPosition;
}
public function getEpubCfiPosition() {
return $this->epubCfiPosition;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setVolumeId($volumeId) {
$this->volumeId = $volumeId;
}
public function getVolumeId() {
return $this->volumeId;
}
public function setPdfPosition($pdfPosition) {
$this->pdfPosition = $pdfPosition;
}
public function getPdfPosition() {
return $this->pdfPosition;
}
public function setGbTextPosition($gbTextPosition) {
$this->gbTextPosition = $gbTextPosition;
}
public function getGbTextPosition() {
return $this->gbTextPosition;
}
}
class RequestAccess extends apiModel {
protected $__downloadAccessType = 'DownloadAccessRestriction';
protected $__downloadAccessDataType = '';
public $downloadAccess;
public $kind;
protected $__concurrentAccessType = 'ConcurrentAccessRestriction';
protected $__concurrentAccessDataType = '';
public $concurrentAccess;
public function setDownloadAccess(DownloadAccessRestriction $downloadAccess) {
$this->downloadAccess = $downloadAccess;
}
public function getDownloadAccess() {
return $this->downloadAccess;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setConcurrentAccess(ConcurrentAccessRestriction $concurrentAccess) {
$this->concurrentAccess = $concurrentAccess;
}
public function getConcurrentAccess() {
return $this->concurrentAccess;
}
}
class Review extends apiModel {
public $rating;
public $kind;
protected $__authorType = 'ReviewAuthor';
protected $__authorDataType = '';
public $author;
public $title;
public $volumeId;
public $content;
protected $__sourceType = 'ReviewSource';
protected $__sourceDataType = '';
public $source;
public $date;
public $type;
public $fullTextUrl;
public function setRating($rating) {
$this->rating = $rating;
}
public function getRating() {
return $this->rating;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAuthor(ReviewAuthor $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setVolumeId($volumeId) {
$this->volumeId = $volumeId;
}
public function getVolumeId() {
return $this->volumeId;
}
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setSource(ReviewSource $source) {
$this->source = $source;
}
public function getSource() {
return $this->source;
}
public function setDate($date) {
$this->date = $date;
}
public function getDate() {
return $this->date;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setFullTextUrl($fullTextUrl) {
$this->fullTextUrl = $fullTextUrl;
}
public function getFullTextUrl() {
return $this->fullTextUrl;
}
}
class ReviewAuthor extends apiModel {
public $displayName;
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
}
class ReviewSource extends apiModel {
public $extraDescription;
public $url;
public $description;
public function setExtraDescription($extraDescription) {
$this->extraDescription = $extraDescription;
}
public function getExtraDescription() {
return $this->extraDescription;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
}
class Volume extends apiModel {
public $kind;
protected $__accessInfoType = 'VolumeAccessInfo';
protected $__accessInfoDataType = '';
public $accessInfo;
protected $__saleInfoType = 'VolumeSaleInfo';
protected $__saleInfoDataType = '';
public $saleInfo;
public $etag;
protected $__userInfoType = 'VolumeUserInfo';
protected $__userInfoDataType = '';
public $userInfo;
protected $__volumeInfoType = 'VolumeVolumeInfo';
protected $__volumeInfoDataType = '';
public $volumeInfo;
public $id;
public $selfLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAccessInfo(VolumeAccessInfo $accessInfo) {
$this->accessInfo = $accessInfo;
}
public function getAccessInfo() {
return $this->accessInfo;
}
public function setSaleInfo(VolumeSaleInfo $saleInfo) {
$this->saleInfo = $saleInfo;
}
public function getSaleInfo() {
return $this->saleInfo;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setUserInfo(VolumeUserInfo $userInfo) {
$this->userInfo = $userInfo;
}
public function getUserInfo() {
return $this->userInfo;
}
public function setVolumeInfo(VolumeVolumeInfo $volumeInfo) {
$this->volumeInfo = $volumeInfo;
}
public function getVolumeInfo() {
return $this->volumeInfo;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class VolumeAccessInfo extends apiModel {
public $publicDomain;
public $embeddable;
protected $__downloadAccessType = 'DownloadAccessRestriction';
protected $__downloadAccessDataType = '';
public $downloadAccess;
public $country;
public $textToSpeechPermission;
protected $__pdfType = 'VolumeAccessInfoPdf';
protected $__pdfDataType = '';
public $pdf;
public $viewability;
protected $__epubType = 'VolumeAccessInfoEpub';
protected $__epubDataType = '';
public $epub;
public $accessViewStatus;
public function setPublicDomain($publicDomain) {
$this->publicDomain = $publicDomain;
}
public function getPublicDomain() {
return $this->publicDomain;
}
public function setEmbeddable($embeddable) {
$this->embeddable = $embeddable;
}
public function getEmbeddable() {
return $this->embeddable;
}
public function setDownloadAccess(DownloadAccessRestriction $downloadAccess) {
$this->downloadAccess = $downloadAccess;
}
public function getDownloadAccess() {
return $this->downloadAccess;
}
public function setCountry($country) {
$this->country = $country;
}
public function getCountry() {
return $this->country;
}
public function setTextToSpeechPermission($textToSpeechPermission) {
$this->textToSpeechPermission = $textToSpeechPermission;
}
public function getTextToSpeechPermission() {
return $this->textToSpeechPermission;
}
public function setPdf(VolumeAccessInfoPdf $pdf) {
$this->pdf = $pdf;
}
public function getPdf() {
return $this->pdf;
}
public function setViewability($viewability) {
$this->viewability = $viewability;
}
public function getViewability() {
return $this->viewability;
}
public function setEpub(VolumeAccessInfoEpub $epub) {
$this->epub = $epub;
}
public function getEpub() {
return $this->epub;
}
public function setAccessViewStatus($accessViewStatus) {
$this->accessViewStatus = $accessViewStatus;
}
public function getAccessViewStatus() {
return $this->accessViewStatus;
}
}
class VolumeAccessInfoEpub extends apiModel {
public $downloadLink;
public $acsTokenLink;
public function setDownloadLink($downloadLink) {
$this->downloadLink = $downloadLink;
}
public function getDownloadLink() {
return $this->downloadLink;
}
public function setAcsTokenLink($acsTokenLink) {
$this->acsTokenLink = $acsTokenLink;
}
public function getAcsTokenLink() {
return $this->acsTokenLink;
}
}
class VolumeAccessInfoPdf extends apiModel {
public $downloadLink;
public $acsTokenLink;
public function setDownloadLink($downloadLink) {
$this->downloadLink = $downloadLink;
}
public function getDownloadLink() {
return $this->downloadLink;
}
public function setAcsTokenLink($acsTokenLink) {
$this->acsTokenLink = $acsTokenLink;
}
public function getAcsTokenLink() {
return $this->acsTokenLink;
}
}
class VolumeSaleInfo extends apiModel {
public $country;
protected $__retailPriceType = 'VolumeSaleInfoRetailPrice';
protected $__retailPriceDataType = '';
public $retailPrice;
public $isEbook;
public $saleability;
public $buyLink;
public $onSaleDate;
protected $__listPriceType = 'VolumeSaleInfoListPrice';
protected $__listPriceDataType = '';
public $listPrice;
public function setCountry($country) {
$this->country = $country;
}
public function getCountry() {
return $this->country;
}
public function setRetailPrice(VolumeSaleInfoRetailPrice $retailPrice) {
$this->retailPrice = $retailPrice;
}
public function getRetailPrice() {
return $this->retailPrice;
}
public function setIsEbook($isEbook) {
$this->isEbook = $isEbook;
}
public function getIsEbook() {
return $this->isEbook;
}
public function setSaleability($saleability) {
$this->saleability = $saleability;
}
public function getSaleability() {
return $this->saleability;
}
public function setBuyLink($buyLink) {
$this->buyLink = $buyLink;
}
public function getBuyLink() {
return $this->buyLink;
}
public function setOnSaleDate($onSaleDate) {
$this->onSaleDate = $onSaleDate;
}
public function getOnSaleDate() {
return $this->onSaleDate;
}
public function setListPrice(VolumeSaleInfoListPrice $listPrice) {
$this->listPrice = $listPrice;
}
public function getListPrice() {
return $this->listPrice;
}
}
class VolumeSaleInfoListPrice extends apiModel {
public $amount;
public $currencyCode;
public function setAmount($amount) {
$this->amount = $amount;
}
public function getAmount() {
return $this->amount;
}
public function setCurrencyCode($currencyCode) {
$this->currencyCode = $currencyCode;
}
public function getCurrencyCode() {
return $this->currencyCode;
}
}
class VolumeSaleInfoRetailPrice extends apiModel {
public $amount;
public $currencyCode;
public function setAmount($amount) {
$this->amount = $amount;
}
public function getAmount() {
return $this->amount;
}
public function setCurrencyCode($currencyCode) {
$this->currencyCode = $currencyCode;
}
public function getCurrencyCode() {
return $this->currencyCode;
}
}
class VolumeUserInfo extends apiModel {
public $updated;
public $isPreordered;
public $isPurchased;
protected $__readingPositionType = 'ReadingPosition';
protected $__readingPositionDataType = '';
public $readingPosition;
protected $__reviewType = 'Review';
protected $__reviewDataType = '';
public $review;
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setIsPreordered($isPreordered) {
$this->isPreordered = $isPreordered;
}
public function getIsPreordered() {
return $this->isPreordered;
}
public function setIsPurchased($isPurchased) {
$this->isPurchased = $isPurchased;
}
public function getIsPurchased() {
return $this->isPurchased;
}
public function setReadingPosition(ReadingPosition $readingPosition) {
$this->readingPosition = $readingPosition;
}
public function getReadingPosition() {
return $this->readingPosition;
}
public function setReview(Review $review) {
$this->review = $review;
}
public function getReview() {
return $this->review;
}
}
class VolumeVolumeInfo extends apiModel {
public $publisher;
public $subtitle;
public $description;
public $language;
public $pageCount;
protected $__imageLinksType = 'VolumeVolumeInfoImageLinks';
protected $__imageLinksDataType = '';
public $imageLinks;
public $publishedDate;
public $previewLink;
public $printType;
public $ratingsCount;
public $mainCategory;
protected $__dimensionsType = 'VolumeVolumeInfoDimensions';
protected $__dimensionsDataType = '';
public $dimensions;
public $contentVersion;
protected $__industryIdentifiersType = 'VolumeVolumeInfoIndustryIdentifiers';
protected $__industryIdentifiersDataType = 'array';
public $industryIdentifiers;
public $authors;
public $title;
public $canonicalVolumeLink;
public $infoLink;
public $categories;
public $averageRating;
public function setPublisher($publisher) {
$this->publisher = $publisher;
}
public function getPublisher() {
return $this->publisher;
}
public function setSubtitle($subtitle) {
$this->subtitle = $subtitle;
}
public function getSubtitle() {
return $this->subtitle;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setLanguage($language) {
$this->language = $language;
}
public function getLanguage() {
return $this->language;
}
public function setPageCount($pageCount) {
$this->pageCount = $pageCount;
}
public function getPageCount() {
return $this->pageCount;
}
public function setImageLinks(VolumeVolumeInfoImageLinks $imageLinks) {
$this->imageLinks = $imageLinks;
}
public function getImageLinks() {
return $this->imageLinks;
}
public function setPublishedDate($publishedDate) {
$this->publishedDate = $publishedDate;
}
public function getPublishedDate() {
return $this->publishedDate;
}
public function setPreviewLink($previewLink) {
$this->previewLink = $previewLink;
}
public function getPreviewLink() {
return $this->previewLink;
}
public function setPrintType($printType) {
$this->printType = $printType;
}
public function getPrintType() {
return $this->printType;
}
public function setRatingsCount($ratingsCount) {
$this->ratingsCount = $ratingsCount;
}
public function getRatingsCount() {
return $this->ratingsCount;
}
public function setMainCategory($mainCategory) {
$this->mainCategory = $mainCategory;
}
public function getMainCategory() {
return $this->mainCategory;
}
public function setDimensions(VolumeVolumeInfoDimensions $dimensions) {
$this->dimensions = $dimensions;
}
public function getDimensions() {
return $this->dimensions;
}
public function setContentVersion($contentVersion) {
$this->contentVersion = $contentVersion;
}
public function getContentVersion() {
return $this->contentVersion;
}
public function setIndustryIdentifiers(/* array(VolumeVolumeInfoIndustryIdentifiers) */ $industryIdentifiers) {
$this->assertIsArray($industryIdentifiers, 'VolumeVolumeInfoIndustryIdentifiers', __METHOD__);
$this->industryIdentifiers = $industryIdentifiers;
}
public function getIndustryIdentifiers() {
return $this->industryIdentifiers;
}
public function setAuthors(/* array(string) */ $authors) {
$this->assertIsArray($authors, 'string', __METHOD__);
$this->authors = $authors;
}
public function getAuthors() {
return $this->authors;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setCanonicalVolumeLink($canonicalVolumeLink) {
$this->canonicalVolumeLink = $canonicalVolumeLink;
}
public function getCanonicalVolumeLink() {
return $this->canonicalVolumeLink;
}
public function setInfoLink($infoLink) {
$this->infoLink = $infoLink;
}
public function getInfoLink() {
return $this->infoLink;
}
public function setCategories(/* array(string) */ $categories) {
$this->assertIsArray($categories, 'string', __METHOD__);
$this->categories = $categories;
}
public function getCategories() {
return $this->categories;
}
public function setAverageRating($averageRating) {
$this->averageRating = $averageRating;
}
public function getAverageRating() {
return $this->averageRating;
}
}
class VolumeVolumeInfoDimensions extends apiModel {
public $width;
public $thickness;
public $height;
public function setWidth($width) {
$this->width = $width;
}
public function getWidth() {
return $this->width;
}
public function setThickness($thickness) {
$this->thickness = $thickness;
}
public function getThickness() {
return $this->thickness;
}
public function setHeight($height) {
$this->height = $height;
}
public function getHeight() {
return $this->height;
}
}
class VolumeVolumeInfoImageLinks extends apiModel {
public $medium;
public $smallThumbnail;
public $large;
public $extraLarge;
public $small;
public $thumbnail;
public function setMedium($medium) {
$this->medium = $medium;
}
public function getMedium() {
return $this->medium;
}
public function setSmallThumbnail($smallThumbnail) {
$this->smallThumbnail = $smallThumbnail;
}
public function getSmallThumbnail() {
return $this->smallThumbnail;
}
public function setLarge($large) {
$this->large = $large;
}
public function getLarge() {
return $this->large;
}
public function setExtraLarge($extraLarge) {
$this->extraLarge = $extraLarge;
}
public function getExtraLarge() {
return $this->extraLarge;
}
public function setSmall($small) {
$this->small = $small;
}
public function getSmall() {
return $this->small;
}
public function setThumbnail($thumbnail) {
$this->thumbnail = $thumbnail;
}
public function getThumbnail() {
return $this->thumbnail;
}
}
class VolumeVolumeInfoIndustryIdentifiers extends apiModel {
public $identifier;
public $type;
public function setIdentifier($identifier) {
$this->identifier = $identifier;
}
public function getIdentifier() {
return $this->identifier;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class Volumes extends apiModel {
public $totalItems;
protected $__itemsType = 'Volume';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setItems(/* array(Volume) */ $items) {
$this->assertIsArray($items, 'Volume', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiBooksService.php | PHP | asf20 | 66,553 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "urlchannels" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $urlchannels = $adsenseService->urlchannels;
* </code>
*/
class UrlchannelsServiceResource extends apiServiceResource {
/**
* List all URL channels in the specified ad client for this AdSense account. (urlchannels.list)
*
* @param string $adClientId Ad client for which to list URL channels.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of URL channels to include in the response, used for paging.
* @return UrlChannels
*/
public function listUrlchannels($adClientId, $optParams = array()) {
$params = array('adClientId' => $adClientId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new UrlChannels($data);
} else {
return $data;
}
}
}
/**
* The "adunits" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $adunits = $adsenseService->adunits;
* </code>
*/
class AdunitsServiceResource extends apiServiceResource {
/**
* List all ad units in the specified ad client for this AdSense account. (adunits.list)
*
* @param string $adClientId Ad client for which to list ad units.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool includeInactive Whether to include inactive ad units. Default: true.
* @opt_param string pageToken A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of ad units to include in the response, used for paging.
* @return AdUnits
*/
public function listAdunits($adClientId, $optParams = array()) {
$params = array('adClientId' => $adClientId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new AdUnits($data);
} else {
return $data;
}
}
/**
* Gets the specified ad unit in the specified ad client. (adunits.get)
*
* @param string $adClientId Ad client for which to get the ad unit.
* @param string $adUnitId Ad unit to retrieve.
* @return AdUnit
*/
public function get($adClientId, $adUnitId, $optParams = array()) {
$params = array('adClientId' => $adClientId, 'adUnitId' => $adUnitId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new AdUnit($data);
} else {
return $data;
}
}
}
/**
* The "customchannels" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $customchannels = $adsenseService->customchannels;
* </code>
*/
class AdunitsCustomchannelsServiceResource extends apiServiceResource {
/**
* List all custom channels which the specified ad unit belongs to. (customchannels.list)
*
* @param string $adClientId Ad client which contains the ad unit.
* @param string $adUnitId Ad unit for which to list custom channels.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of custom channels to include in the response, used for paging.
* @return CustomChannels
*/
public function listAdunitsCustomchannels($adClientId, $adUnitId, $optParams = array()) {
$params = array('adClientId' => $adClientId, 'adUnitId' => $adUnitId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CustomChannels($data);
} else {
return $data;
}
}
}
/**
* The "adclients" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $adclients = $adsenseService->adclients;
* </code>
*/
class AdclientsServiceResource extends apiServiceResource {
/**
* List all ad clients in this AdSense account. (adclients.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of ad clients to include in the response, used for paging.
* @return AdClients
*/
public function listAdclients($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new AdClients($data);
} else {
return $data;
}
}
}
/**
* The "reports" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $reports = $adsenseService->reports;
* </code>
*/
class ReportsServiceResource extends apiServiceResource {
/**
* Generate an AdSense report based on the report request sent in the query parameters. Returns the
* result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter.
* (reports.generate)
*
* @param string $startDate Start of the date range to report on in "YYYY-MM-DD" format, inclusive.
* @param string $endDate End of the date range to report on in "YYYY-MM-DD" format, inclusive.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string sort The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending.
* @opt_param string locale Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified.
* @opt_param string metric Numeric columns to include in the report.
* @opt_param int maxResults The maximum number of rows of report data to return.
* @opt_param string filter Filters to be run on the report.
* @opt_param string currency Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set.
* @opt_param int startIndex Index of the first row of report data to return.
* @opt_param string dimension Dimensions to base the report on.
* @opt_param string accountId Accounts upon which to report.
* @return AdsenseReportsGenerateResponse
*/
public function generate($startDate, $endDate, $optParams = array()) {
$params = array('startDate' => $startDate, 'endDate' => $endDate);
$params = array_merge($params, $optParams);
$data = $this->__call('generate', array($params));
if ($this->useObjects()) {
return new AdsenseReportsGenerateResponse($data);
} else {
return $data;
}
}
}
/**
* The "accounts" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $accounts = $adsenseService->accounts;
* </code>
*/
class AccountsServiceResource extends apiServiceResource {
/**
* List all accounts available to this AdSense account. (accounts.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through accounts. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of accounts to include in the response, used for paging.
* @return Accounts
*/
public function listAccounts($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Accounts($data);
} else {
return $data;
}
}
/**
* Get information about the selected AdSense account. (accounts.get)
*
* @param string $accountId Account to get information about.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool tree Whether the tree of sub accounts should be returned.
* @return Account
*/
public function get($accountId, $optParams = array()) {
$params = array('accountId' => $accountId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Account($data);
} else {
return $data;
}
}
}
/**
* The "urlchannels" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $urlchannels = $adsenseService->urlchannels;
* </code>
*/
class AccountsUrlchannelsServiceResource extends apiServiceResource {
/**
* List all URL channels in the specified ad client for the specified account. (urlchannels.list)
*
* @param string $accountId Account to which the ad client belongs.
* @param string $adClientId Ad client for which to list URL channels.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through URL channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of URL channels to include in the response, used for paging.
* @return UrlChannels
*/
public function listAccountsUrlchannels($accountId, $adClientId, $optParams = array()) {
$params = array('accountId' => $accountId, 'adClientId' => $adClientId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new UrlChannels($data);
} else {
return $data;
}
}
}
/**
* The "adunits" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $adunits = $adsenseService->adunits;
* </code>
*/
class AccountsAdunitsServiceResource extends apiServiceResource {
/**
* List all ad units in the specified ad client for the specified account. (adunits.list)
*
* @param string $accountId Account to which the ad client belongs.
* @param string $adClientId Ad client for which to list ad units.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool includeInactive Whether to include inactive ad units. Default: true.
* @opt_param string pageToken A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of ad units to include in the response, used for paging.
* @return AdUnits
*/
public function listAccountsAdunits($accountId, $adClientId, $optParams = array()) {
$params = array('accountId' => $accountId, 'adClientId' => $adClientId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new AdUnits($data);
} else {
return $data;
}
}
/**
* Gets the specified ad unit in the specified ad client for the specified account. (adunits.get)
*
* @param string $accountId Account to which the ad client belongs.
* @param string $adClientId Ad client for which to get the ad unit.
* @param string $adUnitId Ad unit to retrieve.
* @return AdUnit
*/
public function get($accountId, $adClientId, $adUnitId, $optParams = array()) {
$params = array('accountId' => $accountId, 'adClientId' => $adClientId, 'adUnitId' => $adUnitId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new AdUnit($data);
} else {
return $data;
}
}
}
/**
* The "customchannels" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $customchannels = $adsenseService->customchannels;
* </code>
*/
class AccountsAdunitsCustomchannelsServiceResource extends apiServiceResource {
/**
* List all custom channels which the specified ad unit belongs to. (customchannels.list)
*
* @param string $accountId Account to which the ad client belongs.
* @param string $adClientId Ad client which contains the ad unit.
* @param string $adUnitId Ad unit for which to list custom channels.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of custom channels to include in the response, used for paging.
* @return CustomChannels
*/
public function listAccountsAdunitsCustomchannels($accountId, $adClientId, $adUnitId, $optParams = array()) {
$params = array('accountId' => $accountId, 'adClientId' => $adClientId, 'adUnitId' => $adUnitId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CustomChannels($data);
} else {
return $data;
}
}
}
/**
* The "adclients" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $adclients = $adsenseService->adclients;
* </code>
*/
class AccountsAdclientsServiceResource extends apiServiceResource {
/**
* List all ad clients in the specified account. (adclients.list)
*
* @param string $accountId Account for which to list ad clients.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through ad clients. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of ad clients to include in the response, used for paging.
* @return AdClients
*/
public function listAccountsAdclients($accountId, $optParams = array()) {
$params = array('accountId' => $accountId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new AdClients($data);
} else {
return $data;
}
}
}
/**
* The "reports" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $reports = $adsenseService->reports;
* </code>
*/
class AccountsReportsServiceResource extends apiServiceResource {
/**
* Generate an AdSense report based on the report request sent in the query parameters. Returns the
* result as JSON; to retrieve output in CSV format specify "alt=csv" as a query parameter.
* (reports.generate)
*
* @param string $startDate Start of the date range to report on in "YYYY-MM-DD" format, inclusive.
* @param string $endDate End of the date range to report on in "YYYY-MM-DD" format, inclusive.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string accountId Account upon which to report.
* @opt_param string sort The name of a dimension or metric to sort the resulting report on, optionally prefixed with "+" to sort ascending or "-" to sort descending. If no prefix is specified, the column is sorted ascending.
* @opt_param string locale Optional locale to use for translating report output to a local language. Defaults to "en_US" if not specified.
* @opt_param string metric Numeric columns to include in the report.
* @opt_param int maxResults The maximum number of rows of report data to return.
* @opt_param string filter Filters to be run on the report.
* @opt_param string currency Optional currency to use when reporting on monetary metrics. Defaults to the account's currency if not set.
* @opt_param int startIndex Index of the first row of report data to return.
* @opt_param string dimension Dimensions to base the report on.
* @return AdsenseReportsGenerateResponse
*/
public function generate($startDate, $endDate, $optParams = array()) {
$params = array('startDate' => $startDate, 'endDate' => $endDate);
$params = array_merge($params, $optParams);
$data = $this->__call('generate', array($params));
if ($this->useObjects()) {
return new AdsenseReportsGenerateResponse($data);
} else {
return $data;
}
}
}
/**
* The "customchannels" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $customchannels = $adsenseService->customchannels;
* </code>
*/
class AccountsCustomchannelsServiceResource extends apiServiceResource {
/**
* List all custom channels in the specified ad client for the specified account.
* (customchannels.list)
*
* @param string $accountId Account to which the ad client belongs.
* @param string $adClientId Ad client for which to list custom channels.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of custom channels to include in the response, used for paging.
* @return CustomChannels
*/
public function listAccountsCustomchannels($accountId, $adClientId, $optParams = array()) {
$params = array('accountId' => $accountId, 'adClientId' => $adClientId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CustomChannels($data);
} else {
return $data;
}
}
/**
* Get the specified custom channel from the specified ad client for the specified account.
* (customchannels.get)
*
* @param string $accountId Account to which the ad client belongs.
* @param string $adClientId Ad client which contains the custom channel.
* @param string $customChannelId Custom channel to retrieve.
* @return CustomChannel
*/
public function get($accountId, $adClientId, $customChannelId, $optParams = array()) {
$params = array('accountId' => $accountId, 'adClientId' => $adClientId, 'customChannelId' => $customChannelId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new CustomChannel($data);
} else {
return $data;
}
}
}
/**
* The "adunits" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $adunits = $adsenseService->adunits;
* </code>
*/
class AccountsCustomchannelsAdunitsServiceResource extends apiServiceResource {
/**
* List all ad units in the specified custom channel. (adunits.list)
*
* @param string $accountId Account to which the ad client belongs.
* @param string $adClientId Ad client which contains the custom channel.
* @param string $customChannelId Custom channel for which to list ad units.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool includeInactive Whether to include inactive ad units. Default: true.
* @opt_param int maxResults The maximum number of ad units to include in the response, used for paging.
* @opt_param string pageToken A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @return AdUnits
*/
public function listAccountsCustomchannelsAdunits($accountId, $adClientId, $customChannelId, $optParams = array()) {
$params = array('accountId' => $accountId, 'adClientId' => $adClientId, 'customChannelId' => $customChannelId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new AdUnits($data);
} else {
return $data;
}
}
}
/**
* The "customchannels" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $customchannels = $adsenseService->customchannels;
* </code>
*/
class CustomchannelsServiceResource extends apiServiceResource {
/**
* List all custom channels in the specified ad client for this AdSense account.
* (customchannels.list)
*
* @param string $adClientId Ad client for which to list custom channels.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token, used to page through custom channels. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of custom channels to include in the response, used for paging.
* @return CustomChannels
*/
public function listCustomchannels($adClientId, $optParams = array()) {
$params = array('adClientId' => $adClientId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CustomChannels($data);
} else {
return $data;
}
}
/**
* Get the specified custom channel from the specified ad client. (customchannels.get)
*
* @param string $adClientId Ad client which contains the custom channel.
* @param string $customChannelId Custom channel to retrieve.
* @return CustomChannel
*/
public function get($adClientId, $customChannelId, $optParams = array()) {
$params = array('adClientId' => $adClientId, 'customChannelId' => $customChannelId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new CustomChannel($data);
} else {
return $data;
}
}
}
/**
* The "adunits" collection of methods.
* Typical usage is:
* <code>
* $adsenseService = new apiAdsenseService(...);
* $adunits = $adsenseService->adunits;
* </code>
*/
class CustomchannelsAdunitsServiceResource extends apiServiceResource {
/**
* List all ad units in the specified custom channel. (adunits.list)
*
* @param string $adClientId Ad client which contains the custom channel.
* @param string $customChannelId Custom channel for which to list ad units.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool includeInactive Whether to include inactive ad units. Default: true.
* @opt_param string pageToken A continuation token, used to page through ad units. To retrieve the next page, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param int maxResults The maximum number of ad units to include in the response, used for paging.
* @return AdUnits
*/
public function listCustomchannelsAdunits($adClientId, $customChannelId, $optParams = array()) {
$params = array('adClientId' => $adClientId, 'customChannelId' => $customChannelId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new AdUnits($data);
} else {
return $data;
}
}
}
/**
* Service definition for Adsense (v1.1).
*
* <p>
* Gives AdSense publishers access to their inventory and the ability to generate reports
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://code.google.com/apis/adsense/management/" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiAdsenseService extends apiService {
public $urlchannels;
public $adunits;
public $adunits_customchannels;
public $adunits_customchannels_customchannels;
public $adclients;
public $reports;
public $accounts;
public $accounts_urlchannels;
public $accounts_urlchannels_urlchannels;
public $accounts_urlchannels_adunits;
public $accounts_urlchannels_adclients;
public $accounts_urlchannels_reports;
public $accounts_urlchannels_customchannels;
public $accounts_adunits;
public $accounts_adunits_urlchannels;
public $accounts_adunits_adunits;
public $accounts_adunits_adclients;
public $accounts_adunits_reports;
public $accounts_adunits_customchannels;
public $accounts_adclients;
public $accounts_adclients_urlchannels;
public $accounts_adclients_adunits;
public $accounts_adclients_adclients;
public $accounts_adclients_reports;
public $accounts_adclients_customchannels;
public $accounts_reports;
public $accounts_reports_urlchannels;
public $accounts_reports_adunits;
public $accounts_reports_adclients;
public $accounts_reports_reports;
public $accounts_reports_customchannels;
public $accounts_customchannels;
public $accounts_customchannels_urlchannels;
public $accounts_customchannels_adunits;
public $accounts_customchannels_adclients;
public $accounts_customchannels_reports;
public $accounts_customchannels_customchannels;
public $customchannels;
public $customchannels_adunits;
public $customchannels_adunits_adunits;
/**
* Constructs the internal representation of the Adsense service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/adsense/v1.1/';
$this->version = 'v1.1';
$this->serviceName = 'adsense';
$apiClient->addService($this->serviceName, $this->version);
$this->urlchannels = new UrlchannelsServiceResource($this, $this->serviceName, 'urlchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}}, "id": "adsense.urlchannels.list", "httpMethod": "GET", "path": "adclients/{adClientId}/urlchannels", "response": {"$ref": "UrlChannels"}}}}', true));
$this->adunits = new AdunitsServiceResource($this, $this->serviceName, 'adunits', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"includeInactive": {"type": "boolean", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}}, "id": "adsense.adunits.list", "httpMethod": "GET", "path": "adclients/{adClientId}/adunits", "response": {"$ref": "AdUnits"}}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"adClientId": {"required": true, "type": "string", "location": "path"}, "adUnitId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.adunits.get", "httpMethod": "GET", "path": "adclients/{adClientId}/adunits/{adUnitId}", "response": {"$ref": "AdUnit"}}}}', true));
$this->adunits_customchannels = new AdunitsCustomchannelsServiceResource($this, $this->serviceName, 'customchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "adUnitId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}}, "id": "adsense.adunits.customchannels.list", "httpMethod": "GET", "path": "adclients/{adClientId}/adunits/{adUnitId}/customchannels", "response": {"$ref": "CustomChannels"}}}}', true));
$this->adclients = new AdclientsServiceResource($this, $this->serviceName, 'adclients', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}}, "response": {"$ref": "AdClients"}, "httpMethod": "GET", "path": "adclients", "id": "adsense.adclients.list"}}}', true));
$this->reports = new ReportsServiceResource($this, $this->serviceName, 'reports', json_decode('{"methods": {"generate": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"sort": {"repeated": true, "type": "string", "location": "query"}, "startDate": {"required": true, "type": "string", "location": "query"}, "endDate": {"required": true, "type": "string", "location": "query"}, "locale": {"type": "string", "location": "query"}, "metric": {"repeated": true, "type": "string", "location": "query"}, "maxResults": {"format": "int32", "maximum": "50000", "minimum": "0", "location": "query", "type": "integer"}, "filter": {"repeated": true, "type": "string", "location": "query"}, "currency": {"type": "string", "location": "query"}, "startIndex": {"format": "int32", "maximum": "5000", "minimum": "0", "location": "query", "type": "integer"}, "dimension": {"repeated": true, "type": "string", "location": "query"}, "accountId": {"repeated": true, "type": "string", "location": "query"}}, "id": "adsense.reports.generate", "httpMethod": "GET", "path": "reports", "response": {"$ref": "AdsenseReportsGenerateResponse"}}}}', true));
$this->accounts = new AccountsServiceResource($this, $this->serviceName, 'accounts', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}}, "response": {"$ref": "Accounts"}, "httpMethod": "GET", "path": "accounts", "id": "adsense.accounts.list"}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"tree": {"type": "boolean", "location": "query"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.get", "httpMethod": "GET", "path": "accounts/{accountId}", "response": {"$ref": "Account"}}}}', true));
$this->accounts_urlchannels = new AccountsUrlchannelsServiceResource($this, $this->serviceName, 'urlchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.urlchannels.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/urlchannels", "response": {"$ref": "UrlChannels"}}}}', true));
$this->accounts_adunits = new AccountsAdunitsServiceResource($this, $this->serviceName, 'adunits', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"includeInactive": {"type": "boolean", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.adunits.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/adunits", "response": {"$ref": "AdUnits"}}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"adClientId": {"required": true, "type": "string", "location": "path"}, "adUnitId": {"required": true, "type": "string", "location": "path"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.adunits.get", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}", "response": {"$ref": "AdUnit"}}}}', true));
$this->accounts_adunits_customchannels = new AccountsAdunitsCustomchannelsServiceResource($this, $this->serviceName, 'customchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "adUnitId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.adunits.customchannels.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/adunits/{adUnitId}/customchannels", "response": {"$ref": "CustomChannels"}}}}', true));
$this->accounts_adclients = new AccountsAdclientsServiceResource($this, $this->serviceName, 'adclients', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.adclients.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients", "response": {"$ref": "AdClients"}}}}', true));
$this->accounts_reports = new AccountsReportsServiceResource($this, $this->serviceName, 'reports', json_decode('{"methods": {"generate": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"sort": {"repeated": true, "type": "string", "location": "query"}, "startDate": {"required": true, "type": "string", "location": "query"}, "endDate": {"required": true, "type": "string", "location": "query"}, "locale": {"type": "string", "location": "query"}, "metric": {"repeated": true, "type": "string", "location": "query"}, "maxResults": {"format": "int32", "maximum": "50000", "minimum": "0", "location": "query", "type": "integer"}, "filter": {"repeated": true, "type": "string", "location": "query"}, "currency": {"type": "string", "location": "query"}, "startIndex": {"format": "int32", "maximum": "5000", "minimum": "0", "location": "query", "type": "integer"}, "dimension": {"repeated": true, "type": "string", "location": "query"}, "accountId": {"type": "string", "location": "path"}}, "id": "adsense.accounts.reports.generate", "httpMethod": "GET", "path": "accounts/{accountId}/reports", "response": {"$ref": "AdsenseReportsGenerateResponse"}}}}', true));
$this->accounts_customchannels = new AccountsCustomchannelsServiceResource($this, $this->serviceName, 'customchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.customchannels.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/customchannels", "response": {"$ref": "CustomChannels"}}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"customChannelId": {"required": true, "type": "string", "location": "path"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.customchannels.get", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/customchannels/{customChannelId}", "response": {"$ref": "CustomChannel"}}}}', true));
$this->accounts_customchannels_adunits = new AccountsCustomchannelsAdunitsServiceResource($this, $this->serviceName, 'adunits', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"includeInactive": {"type": "boolean", "location": "query"}, "customChannelId": {"required": true, "type": "string", "location": "path"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}, "pageToken": {"type": "string", "location": "query"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.accounts.customchannels.adunits.list", "httpMethod": "GET", "path": "accounts/{accountId}/adclients/{adClientId}/customchannels/{customChannelId}/adunits", "response": {"$ref": "AdUnits"}}}}', true));
$this->customchannels = new CustomchannelsServiceResource($this, $this->serviceName, 'customchannels', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}}, "id": "adsense.customchannels.list", "httpMethod": "GET", "path": "adclients/{adClientId}/customchannels", "response": {"$ref": "CustomChannels"}}, "get": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"customChannelId": {"required": true, "type": "string", "location": "path"}, "adClientId": {"required": true, "type": "string", "location": "path"}}, "id": "adsense.customchannels.get", "httpMethod": "GET", "path": "adclients/{adClientId}/customchannels/{customChannelId}", "response": {"$ref": "CustomChannel"}}}}', true));
$this->customchannels_adunits = new CustomchannelsAdunitsServiceResource($this, $this->serviceName, 'adunits', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/adsense.readonly"], "parameters": {"includeInactive": {"type": "boolean", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "customChannelId": {"required": true, "type": "string", "location": "path"}, "adClientId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "int32", "maximum": "10000", "minimum": "0", "location": "query", "type": "integer"}}, "id": "adsense.customchannels.adunits.list", "httpMethod": "GET", "path": "adclients/{adClientId}/customchannels/{customChannelId}/adunits", "response": {"$ref": "AdUnits"}}}}', true));
}
}
class Account extends apiModel {
public $kind;
public $id;
protected $__subAccountsType = 'Account';
protected $__subAccountsDataType = 'array';
public $subAccounts;
public $name;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSubAccounts(/* array(Account) */ $subAccounts) {
$this->assertIsArray($subAccounts, 'Account', __METHOD__);
$this->subAccounts = $subAccounts;
}
public function getSubAccounts() {
return $this->subAccounts;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Accounts extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Account';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Account) */ $items) {
$this->assertIsArray($items, 'Account', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class AdClient extends apiModel {
public $productCode;
public $kind;
public $id;
public $supportsReporting;
public function setProductCode($productCode) {
$this->productCode = $productCode;
}
public function getProductCode() {
return $this->productCode;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSupportsReporting($supportsReporting) {
$this->supportsReporting = $supportsReporting;
}
public function getSupportsReporting() {
return $this->supportsReporting;
}
}
class AdClients extends apiModel {
public $nextPageToken;
protected $__itemsType = 'AdClient';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(AdClient) */ $items) {
$this->assertIsArray($items, 'AdClient', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class AdUnit extends apiModel {
public $status;
public $kind;
public $code;
public $id;
public $name;
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setCode($code) {
$this->code = $code;
}
public function getCode() {
return $this->code;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class AdUnits extends apiModel {
public $nextPageToken;
protected $__itemsType = 'AdUnit';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(AdUnit) */ $items) {
$this->assertIsArray($items, 'AdUnit', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class AdsenseReportsGenerateResponse extends apiModel {
public $kind;
public $rows;
public $warnings;
public $totals;
protected $__headersType = 'AdsenseReportsGenerateResponseHeaders';
protected $__headersDataType = 'array';
public $headers;
public $totalMatchedRows;
public $averages;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setRows(/* array(string) */ $rows) {
$this->assertIsArray($rows, 'string', __METHOD__);
$this->rows = $rows;
}
public function getRows() {
return $this->rows;
}
public function setWarnings(/* array(string) */ $warnings) {
$this->assertIsArray($warnings, 'string', __METHOD__);
$this->warnings = $warnings;
}
public function getWarnings() {
return $this->warnings;
}
public function setTotals(/* array(string) */ $totals) {
$this->assertIsArray($totals, 'string', __METHOD__);
$this->totals = $totals;
}
public function getTotals() {
return $this->totals;
}
public function setHeaders(/* array(AdsenseReportsGenerateResponseHeaders) */ $headers) {
$this->assertIsArray($headers, 'AdsenseReportsGenerateResponseHeaders', __METHOD__);
$this->headers = $headers;
}
public function getHeaders() {
return $this->headers;
}
public function setTotalMatchedRows($totalMatchedRows) {
$this->totalMatchedRows = $totalMatchedRows;
}
public function getTotalMatchedRows() {
return $this->totalMatchedRows;
}
public function setAverages(/* array(string) */ $averages) {
$this->assertIsArray($averages, 'string', __METHOD__);
$this->averages = $averages;
}
public function getAverages() {
return $this->averages;
}
}
class AdsenseReportsGenerateResponseHeaders extends apiModel {
public $currency;
public $type;
public $name;
public function setCurrency($currency) {
$this->currency = $currency;
}
public function getCurrency() {
return $this->currency;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class CustomChannel extends apiModel {
public $kind;
public $code;
protected $__targetingInfoType = 'CustomChannelTargetingInfo';
protected $__targetingInfoDataType = '';
public $targetingInfo;
public $id;
public $name;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setCode($code) {
$this->code = $code;
}
public function getCode() {
return $this->code;
}
public function setTargetingInfo(CustomChannelTargetingInfo $targetingInfo) {
$this->targetingInfo = $targetingInfo;
}
public function getTargetingInfo() {
return $this->targetingInfo;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class CustomChannelTargetingInfo extends apiModel {
public $location;
public $adsAppearOn;
public $siteLanguage;
public $description;
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setAdsAppearOn($adsAppearOn) {
$this->adsAppearOn = $adsAppearOn;
}
public function getAdsAppearOn() {
return $this->adsAppearOn;
}
public function setSiteLanguage($siteLanguage) {
$this->siteLanguage = $siteLanguage;
}
public function getSiteLanguage() {
return $this->siteLanguage;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
}
class CustomChannels extends apiModel {
public $nextPageToken;
protected $__itemsType = 'CustomChannel';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(CustomChannel) */ $items) {
$this->assertIsArray($items, 'CustomChannel', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class UrlChannel extends apiModel {
public $kind;
public $id;
public $urlPattern;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setUrlPattern($urlPattern) {
$this->urlPattern = $urlPattern;
}
public function getUrlPattern() {
return $this->urlPattern;
}
}
class UrlChannels extends apiModel {
public $nextPageToken;
protected $__itemsType = 'UrlChannel';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(UrlChannel) */ $items) {
$this->assertIsArray($items, 'UrlChannel', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiAdsenseService.php | PHP | asf20 | 53,715 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "management" collection of methods.
* Typical usage is:
* <code>
* $analyticsService = new apiAnalyticsService(...);
* $management = $analyticsService->management;
* </code>
*/
class ManagementServiceResource extends apiServiceResource {
}
/**
* The "webproperties" collection of methods.
* Typical usage is:
* <code>
* $analyticsService = new apiAnalyticsService(...);
* $webproperties = $analyticsService->webproperties;
* </code>
*/
class ManagementWebpropertiesServiceResource extends apiServiceResource {
/**
* Lists web properties to which the user has access. (webproperties.list)
*
* @param string $accountId Account ID for the web properties to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which user has access.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param int max-results The maximum number of entries to include in this response.
* @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
* @return Webproperties
*/
public function listManagementWebproperties($accountId, $optParams = array()) {
$params = array('accountId' => $accountId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Webproperties($data);
} else {
return $data;
}
}
}
/**
* The "segments" collection of methods.
* Typical usage is:
* <code>
* $analyticsService = new apiAnalyticsService(...);
* $segments = $analyticsService->segments;
* </code>
*/
class ManagementSegmentsServiceResource extends apiServiceResource {
/**
* Lists advanced segments to which the user has access. (segments.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param int max-results The maximum number of entries to include in this response.
* @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
* @return Segments
*/
public function listManagementSegments($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Segments($data);
} else {
return $data;
}
}
}
/**
* The "accounts" collection of methods.
* Typical usage is:
* <code>
* $analyticsService = new apiAnalyticsService(...);
* $accounts = $analyticsService->accounts;
* </code>
*/
class ManagementAccountsServiceResource extends apiServiceResource {
/**
* Lists all accounts to which the user has access. (accounts.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param int max-results The maximum number of entries to include in this response.
* @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
* @return Accounts
*/
public function listManagementAccounts($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Accounts($data);
} else {
return $data;
}
}
}
/**
* The "goals" collection of methods.
* Typical usage is:
* <code>
* $analyticsService = new apiAnalyticsService(...);
* $goals = $analyticsService->goals;
* </code>
*/
class ManagementGoalsServiceResource extends apiServiceResource {
/**
* Lists goals to which the user has access. (goals.list)
*
* @param string $accountId Account ID for the web properties to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.
* @param string $webPropertyId Web property ID for the web properties to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties to which the user has access.
* @param string $profileId Profile ID for the web properties to retrieve. Can either be a specific profile ID or '~all', which refers to all the profiles to which the user has access.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param int max-results The maximum number of entries to include in this response.
* @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
* @return Goals
*/
public function listManagementGoals($accountId, $webPropertyId, $profileId, $optParams = array()) {
$params = array('accountId' => $accountId, 'webPropertyId' => $webPropertyId, 'profileId' => $profileId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Goals($data);
} else {
return $data;
}
}
}
/**
* The "profiles" collection of methods.
* Typical usage is:
* <code>
* $analyticsService = new apiAnalyticsService(...);
* $profiles = $analyticsService->profiles;
* </code>
*/
class ManagementProfilesServiceResource extends apiServiceResource {
/**
* Lists profiles to which the user has access. (profiles.list)
*
* @param string $accountId Account ID for the web properties to retrieve. Can either be a specific account ID or '~all', which refers to all the accounts to which the user has access.
* @param string $webPropertyId Web property ID for the web properties to retrieve. Can either be a specific web property ID or '~all', which refers to all the web properties to which the user has access.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param int max-results The maximum number of entries to include in this response.
* @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
* @return Profiles
*/
public function listManagementProfiles($accountId, $webPropertyId, $optParams = array()) {
$params = array('accountId' => $accountId, 'webPropertyId' => $webPropertyId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Profiles($data);
} else {
return $data;
}
}
}
/**
* The "data" collection of methods.
* Typical usage is:
* <code>
* $analyticsService = new apiAnalyticsService(...);
* $data = $analyticsService->data;
* </code>
*/
class DataServiceResource extends apiServiceResource {
}
/**
* The "ga" collection of methods.
* Typical usage is:
* <code>
* $analyticsService = new apiAnalyticsService(...);
* $ga = $analyticsService->ga;
* </code>
*/
class DataGaServiceResource extends apiServiceResource {
/**
* Returns Analytics data for a profile. (ga.get)
*
* @param string $ids Unique table ID for retrieving Analytics data. Table ID is of the form ga:XXXX, where XXXX is the Analytics profile ID.
* @param string $start_date Start date for fetching Analytics data. All requests should specify a start date formatted as YYYY-MM-DD.
* @param string $end_date End date for fetching Analytics data. All requests should specify an end date formatted as YYYY-MM-DD.
* @param string $metrics A comma-separated list of Analytics metrics. E.g., 'ga:visits,ga:pageviews'. At least one metric must be specified.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param int max-results The maximum number of entries to include in this feed.
* @opt_param string sort A comma-separated list of dimensions or metrics that determine the sort order for Analytics data.
* @opt_param string dimensions A comma-separated list of Analytics dimensions. E.g., 'ga:browser,ga:city'.
* @opt_param int start-index An index of the first entity to retrieve. Use this parameter as a pagination mechanism along with the max-results parameter.
* @opt_param string segment An Analytics advanced segment to be applied to data.
* @opt_param string filters A comma-separated list of dimension or metric filters to be applied to Analytics data.
* @return GaData
*/
public function get($ids, $start_date, $end_date, $metrics, $optParams = array()) {
$params = array('ids' => $ids, 'start-date' => $start_date, 'end-date' => $end_date, 'metrics' => $metrics);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new GaData($data);
} else {
return $data;
}
}
}
/**
* Service definition for Analytics (v3).
*
* <p>
* View and manage your Google Analytics data
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/analytics" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiAnalyticsService extends apiService {
public $management_webproperties;
public $management_segments;
public $management_accounts;
public $management_goals;
public $management_profiles;
public $data_ga;
/**
* Constructs the internal representation of the Analytics service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/analytics/v3/';
$this->version = 'v3';
$this->serviceName = 'analytics';
$apiClient->addService($this->serviceName, $this->version);
$this->management_webproperties = new ManagementWebpropertiesServiceResource($this, $this->serviceName, 'webproperties', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"format": "int32", "type": "integer", "location": "query"}, "start-index": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}, "accountId": {"required": true, "type": "string", "location": "path"}}, "id": "analytics.management.webproperties.list", "httpMethod": "GET", "path": "management/accounts/{accountId}/webproperties", "response": {"$ref": "Webproperties"}}}}', true));
$this->management_segments = new ManagementSegmentsServiceResource($this, $this->serviceName, 'segments', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"format": "int32", "type": "integer", "location": "query"}, "start-index": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}}, "response": {"$ref": "Segments"}, "httpMethod": "GET", "path": "management/segments", "id": "analytics.management.segments.list"}}}', true));
$this->management_accounts = new ManagementAccountsServiceResource($this, $this->serviceName, 'accounts', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"format": "int32", "type": "integer", "location": "query"}, "start-index": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}}, "response": {"$ref": "Accounts"}, "httpMethod": "GET", "path": "management/accounts", "id": "analytics.management.accounts.list"}}}', true));
$this->management_goals = new ManagementGoalsServiceResource($this, $this->serviceName, 'goals', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"format": "int32", "type": "integer", "location": "query"}, "profileId": {"required": true, "type": "string", "location": "path"}, "start-index": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}, "accountId": {"required": true, "type": "string", "location": "path"}, "webPropertyId": {"required": true, "type": "string", "location": "path"}}, "id": "analytics.management.goals.list", "httpMethod": "GET", "path": "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/goals", "response": {"$ref": "Goals"}}}}', true));
$this->management_profiles = new ManagementProfilesServiceResource($this, $this->serviceName, 'profiles', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"format": "int32", "type": "integer", "location": "query"}, "start-index": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}, "accountId": {"required": true, "type": "string", "location": "path"}, "webPropertyId": {"required": true, "type": "string", "location": "path"}}, "id": "analytics.management.profiles.list", "httpMethod": "GET", "path": "management/accounts/{accountId}/webproperties/{webPropertyId}/profiles", "response": {"$ref": "Profiles"}}}}', true));
$this->data_ga = new DataGaServiceResource($this, $this->serviceName, 'ga', json_decode('{"methods": {"get": {"scopes": ["https://www.googleapis.com/auth/analytics.readonly"], "parameters": {"max-results": {"format": "int32", "type": "integer", "location": "query"}, "sort": {"type": "string", "location": "query"}, "dimensions": {"type": "string", "location": "query"}, "start-date": {"required": true, "type": "string", "location": "query"}, "start-index": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}, "end-date": {"required": true, "type": "string", "location": "query"}, "ids": {"required": true, "type": "string", "location": "query"}, "metrics": {"required": true, "type": "string", "location": "query"}, "filters": {"type": "string", "location": "query"}, "segment": {"type": "string", "location": "query"}}, "id": "analytics.data.ga.get", "httpMethod": "GET", "path": "data/ga", "response": {"$ref": "GaData"}}}}', true));
}
}
class Account extends apiModel {
public $kind;
public $name;
public $created;
public $updated;
protected $__childLinkType = 'AccountChildLink';
protected $__childLinkDataType = '';
public $childLink;
public $id;
public $selfLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setChildLink(AccountChildLink $childLink) {
$this->childLink = $childLink;
}
public function getChildLink() {
return $this->childLink;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class AccountChildLink extends apiModel {
public $href;
public $type;
public function setHref($href) {
$this->href = $href;
}
public function getHref() {
return $this->href;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class Accounts extends apiModel {
public $username;
public $kind;
protected $__itemsType = 'Account';
protected $__itemsDataType = 'array';
public $items;
public $itemsPerPage;
public $previousLink;
public $startIndex;
public $nextLink;
public $totalResults;
public function setUsername($username) {
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(Account) */ $items) {
$this->assertIsArray($items, 'Account', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setItemsPerPage($itemsPerPage) {
$this->itemsPerPage = $itemsPerPage;
}
public function getItemsPerPage() {
return $this->itemsPerPage;
}
public function setPreviousLink($previousLink) {
$this->previousLink = $previousLink;
}
public function getPreviousLink() {
return $this->previousLink;
}
public function setStartIndex($startIndex) {
$this->startIndex = $startIndex;
}
public function getStartIndex() {
return $this->startIndex;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setTotalResults($totalResults) {
$this->totalResults = $totalResults;
}
public function getTotalResults() {
return $this->totalResults;
}
}
class GaData extends apiModel {
public $kind;
public $rows;
public $containsSampledData;
public $totalResults;
public $itemsPerPage;
public $totalsForAllResults;
public $nextLink;
public $id;
protected $__queryType = 'GaDataQuery';
protected $__queryDataType = '';
public $query;
public $previousLink;
protected $__profileInfoType = 'GaDataProfileInfo';
protected $__profileInfoDataType = '';
public $profileInfo;
protected $__columnHeadersType = 'GaDataColumnHeaders';
protected $__columnHeadersDataType = 'array';
public $columnHeaders;
public $selfLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setRows(/* array(string) */ $rows) {
$this->assertIsArray($rows, 'string', __METHOD__);
$this->rows = $rows;
}
public function getRows() {
return $this->rows;
}
public function setContainsSampledData($containsSampledData) {
$this->containsSampledData = $containsSampledData;
}
public function getContainsSampledData() {
return $this->containsSampledData;
}
public function setTotalResults($totalResults) {
$this->totalResults = $totalResults;
}
public function getTotalResults() {
return $this->totalResults;
}
public function setItemsPerPage($itemsPerPage) {
$this->itemsPerPage = $itemsPerPage;
}
public function getItemsPerPage() {
return $this->itemsPerPage;
}
public function setTotalsForAllResults($totalsForAllResults) {
$this->totalsForAllResults = $totalsForAllResults;
}
public function getTotalsForAllResults() {
return $this->totalsForAllResults;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setQuery(GaDataQuery $query) {
$this->query = $query;
}
public function getQuery() {
return $this->query;
}
public function setPreviousLink($previousLink) {
$this->previousLink = $previousLink;
}
public function getPreviousLink() {
return $this->previousLink;
}
public function setProfileInfo(GaDataProfileInfo $profileInfo) {
$this->profileInfo = $profileInfo;
}
public function getProfileInfo() {
return $this->profileInfo;
}
public function setColumnHeaders(/* array(GaDataColumnHeaders) */ $columnHeaders) {
$this->assertIsArray($columnHeaders, 'GaDataColumnHeaders', __METHOD__);
$this->columnHeaders = $columnHeaders;
}
public function getColumnHeaders() {
return $this->columnHeaders;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class GaDataColumnHeaders extends apiModel {
public $dataType;
public $columnType;
public $name;
public function setDataType($dataType) {
$this->dataType = $dataType;
}
public function getDataType() {
return $this->dataType;
}
public function setColumnType($columnType) {
$this->columnType = $columnType;
}
public function getColumnType() {
return $this->columnType;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class GaDataProfileInfo extends apiModel {
public $webPropertyId;
public $internalWebPropertyId;
public $tableId;
public $profileId;
public $profileName;
public $accountId;
public function setWebPropertyId($webPropertyId) {
$this->webPropertyId = $webPropertyId;
}
public function getWebPropertyId() {
return $this->webPropertyId;
}
public function setInternalWebPropertyId($internalWebPropertyId) {
$this->internalWebPropertyId = $internalWebPropertyId;
}
public function getInternalWebPropertyId() {
return $this->internalWebPropertyId;
}
public function setTableId($tableId) {
$this->tableId = $tableId;
}
public function getTableId() {
return $this->tableId;
}
public function setProfileId($profileId) {
$this->profileId = $profileId;
}
public function getProfileId() {
return $this->profileId;
}
public function setProfileName($profileName) {
$this->profileName = $profileName;
}
public function getProfileName() {
return $this->profileName;
}
public function setAccountId($accountId) {
$this->accountId = $accountId;
}
public function getAccountId() {
return $this->accountId;
}
}
class GaDataQuery extends apiModel {
public $max_results;
public $sort;
public $dimensions;
public $start_date;
public $start_index;
public $segment;
public $ids;
public $metrics;
public $filters;
public $end_date;
public function setMax_results($max_results) {
$this->max_results = $max_results;
}
public function getMax_results() {
return $this->max_results;
}
public function setSort(/* array(string) */ $sort) {
$this->assertIsArray($sort, 'string', __METHOD__);
$this->sort = $sort;
}
public function getSort() {
return $this->sort;
}
public function setDimensions($dimensions) {
$this->dimensions = $dimensions;
}
public function getDimensions() {
return $this->dimensions;
}
public function setStart_date($start_date) {
$this->start_date = $start_date;
}
public function getStart_date() {
return $this->start_date;
}
public function setStart_index($start_index) {
$this->start_index = $start_index;
}
public function getStart_index() {
return $this->start_index;
}
public function setSegment($segment) {
$this->segment = $segment;
}
public function getSegment() {
return $this->segment;
}
public function setIds($ids) {
$this->ids = $ids;
}
public function getIds() {
return $this->ids;
}
public function setMetrics(/* array(string) */ $metrics) {
$this->assertIsArray($metrics, 'string', __METHOD__);
$this->metrics = $metrics;
}
public function getMetrics() {
return $this->metrics;
}
public function setFilters($filters) {
$this->filters = $filters;
}
public function getFilters() {
return $this->filters;
}
public function setEnd_date($end_date) {
$this->end_date = $end_date;
}
public function getEnd_date() {
return $this->end_date;
}
}
class Goal extends apiModel {
public $kind;
protected $__visitTimeOnSiteDetailsType = 'GoalVisitTimeOnSiteDetails';
protected $__visitTimeOnSiteDetailsDataType = '';
public $visitTimeOnSiteDetails;
public $name;
public $created;
protected $__urlDestinationDetailsType = 'GoalUrlDestinationDetails';
protected $__urlDestinationDetailsDataType = '';
public $urlDestinationDetails;
public $updated;
public $value;
protected $__visitNumPagesDetailsType = 'GoalVisitNumPagesDetails';
protected $__visitNumPagesDetailsDataType = '';
public $visitNumPagesDetails;
public $internalWebPropertyId;
protected $__eventDetailsType = 'GoalEventDetails';
protected $__eventDetailsDataType = '';
public $eventDetails;
public $webPropertyId;
public $active;
public $profileId;
protected $__parentLinkType = 'GoalParentLink';
protected $__parentLinkDataType = '';
public $parentLink;
public $type;
public $id;
public $selfLink;
public $accountId;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setVisitTimeOnSiteDetails(GoalVisitTimeOnSiteDetails $visitTimeOnSiteDetails) {
$this->visitTimeOnSiteDetails = $visitTimeOnSiteDetails;
}
public function getVisitTimeOnSiteDetails() {
return $this->visitTimeOnSiteDetails;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setUrlDestinationDetails(GoalUrlDestinationDetails $urlDestinationDetails) {
$this->urlDestinationDetails = $urlDestinationDetails;
}
public function getUrlDestinationDetails() {
return $this->urlDestinationDetails;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function setVisitNumPagesDetails(GoalVisitNumPagesDetails $visitNumPagesDetails) {
$this->visitNumPagesDetails = $visitNumPagesDetails;
}
public function getVisitNumPagesDetails() {
return $this->visitNumPagesDetails;
}
public function setInternalWebPropertyId($internalWebPropertyId) {
$this->internalWebPropertyId = $internalWebPropertyId;
}
public function getInternalWebPropertyId() {
return $this->internalWebPropertyId;
}
public function setEventDetails(GoalEventDetails $eventDetails) {
$this->eventDetails = $eventDetails;
}
public function getEventDetails() {
return $this->eventDetails;
}
public function setWebPropertyId($webPropertyId) {
$this->webPropertyId = $webPropertyId;
}
public function getWebPropertyId() {
return $this->webPropertyId;
}
public function setActive($active) {
$this->active = $active;
}
public function getActive() {
return $this->active;
}
public function setProfileId($profileId) {
$this->profileId = $profileId;
}
public function getProfileId() {
return $this->profileId;
}
public function setParentLink(GoalParentLink $parentLink) {
$this->parentLink = $parentLink;
}
public function getParentLink() {
return $this->parentLink;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setAccountId($accountId) {
$this->accountId = $accountId;
}
public function getAccountId() {
return $this->accountId;
}
}
class GoalEventDetails extends apiModel {
protected $__eventConditionsType = 'GoalEventDetailsEventConditions';
protected $__eventConditionsDataType = 'array';
public $eventConditions;
public $useEventValue;
public function setEventConditions(/* array(GoalEventDetailsEventConditions) */ $eventConditions) {
$this->assertIsArray($eventConditions, 'GoalEventDetailsEventConditions', __METHOD__);
$this->eventConditions = $eventConditions;
}
public function getEventConditions() {
return $this->eventConditions;
}
public function setUseEventValue($useEventValue) {
$this->useEventValue = $useEventValue;
}
public function getUseEventValue() {
return $this->useEventValue;
}
}
class GoalEventDetailsEventConditions extends apiModel {
public $type;
public $matchType;
public $expression;
public $comparisonType;
public $comparisonValue;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setMatchType($matchType) {
$this->matchType = $matchType;
}
public function getMatchType() {
return $this->matchType;
}
public function setExpression($expression) {
$this->expression = $expression;
}
public function getExpression() {
return $this->expression;
}
public function setComparisonType($comparisonType) {
$this->comparisonType = $comparisonType;
}
public function getComparisonType() {
return $this->comparisonType;
}
public function setComparisonValue($comparisonValue) {
$this->comparisonValue = $comparisonValue;
}
public function getComparisonValue() {
return $this->comparisonValue;
}
}
class GoalParentLink extends apiModel {
public $href;
public $type;
public function setHref($href) {
$this->href = $href;
}
public function getHref() {
return $this->href;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class GoalUrlDestinationDetails extends apiModel {
public $url;
public $caseSensitive;
public $matchType;
protected $__stepsType = 'GoalUrlDestinationDetailsSteps';
protected $__stepsDataType = 'array';
public $steps;
public $firstStepRequired;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setCaseSensitive($caseSensitive) {
$this->caseSensitive = $caseSensitive;
}
public function getCaseSensitive() {
return $this->caseSensitive;
}
public function setMatchType($matchType) {
$this->matchType = $matchType;
}
public function getMatchType() {
return $this->matchType;
}
public function setSteps(/* array(GoalUrlDestinationDetailsSteps) */ $steps) {
$this->assertIsArray($steps, 'GoalUrlDestinationDetailsSteps', __METHOD__);
$this->steps = $steps;
}
public function getSteps() {
return $this->steps;
}
public function setFirstStepRequired($firstStepRequired) {
$this->firstStepRequired = $firstStepRequired;
}
public function getFirstStepRequired() {
return $this->firstStepRequired;
}
}
class GoalUrlDestinationDetailsSteps extends apiModel {
public $url;
public $name;
public $number;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setNumber($number) {
$this->number = $number;
}
public function getNumber() {
return $this->number;
}
}
class GoalVisitNumPagesDetails extends apiModel {
public $comparisonType;
public $comparisonValue;
public function setComparisonType($comparisonType) {
$this->comparisonType = $comparisonType;
}
public function getComparisonType() {
return $this->comparisonType;
}
public function setComparisonValue($comparisonValue) {
$this->comparisonValue = $comparisonValue;
}
public function getComparisonValue() {
return $this->comparisonValue;
}
}
class GoalVisitTimeOnSiteDetails extends apiModel {
public $comparisonType;
public $comparisonValue;
public function setComparisonType($comparisonType) {
$this->comparisonType = $comparisonType;
}
public function getComparisonType() {
return $this->comparisonType;
}
public function setComparisonValue($comparisonValue) {
$this->comparisonValue = $comparisonValue;
}
public function getComparisonValue() {
return $this->comparisonValue;
}
}
class Goals extends apiModel {
public $username;
public $kind;
protected $__itemsType = 'Goal';
protected $__itemsDataType = 'array';
public $items;
public $itemsPerPage;
public $previousLink;
public $startIndex;
public $nextLink;
public $totalResults;
public function setUsername($username) {
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(Goal) */ $items) {
$this->assertIsArray($items, 'Goal', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setItemsPerPage($itemsPerPage) {
$this->itemsPerPage = $itemsPerPage;
}
public function getItemsPerPage() {
return $this->itemsPerPage;
}
public function setPreviousLink($previousLink) {
$this->previousLink = $previousLink;
}
public function getPreviousLink() {
return $this->previousLink;
}
public function setStartIndex($startIndex) {
$this->startIndex = $startIndex;
}
public function getStartIndex() {
return $this->startIndex;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setTotalResults($totalResults) {
$this->totalResults = $totalResults;
}
public function getTotalResults() {
return $this->totalResults;
}
}
class Profile extends apiModel {
public $defaultPage;
public $kind;
public $excludeQueryParameters;
public $name;
public $created;
public $webPropertyId;
public $updated;
public $siteSearchQueryParameters;
public $currency;
public $internalWebPropertyId;
protected $__childLinkType = 'ProfileChildLink';
protected $__childLinkDataType = '';
public $childLink;
public $timezone;
public $siteSearchCategoryParameters;
protected $__parentLinkType = 'ProfileParentLink';
protected $__parentLinkDataType = '';
public $parentLink;
public $id;
public $selfLink;
public $accountId;
public function setDefaultPage($defaultPage) {
$this->defaultPage = $defaultPage;
}
public function getDefaultPage() {
return $this->defaultPage;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setExcludeQueryParameters($excludeQueryParameters) {
$this->excludeQueryParameters = $excludeQueryParameters;
}
public function getExcludeQueryParameters() {
return $this->excludeQueryParameters;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setWebPropertyId($webPropertyId) {
$this->webPropertyId = $webPropertyId;
}
public function getWebPropertyId() {
return $this->webPropertyId;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setSiteSearchQueryParameters($siteSearchQueryParameters) {
$this->siteSearchQueryParameters = $siteSearchQueryParameters;
}
public function getSiteSearchQueryParameters() {
return $this->siteSearchQueryParameters;
}
public function setCurrency($currency) {
$this->currency = $currency;
}
public function getCurrency() {
return $this->currency;
}
public function setInternalWebPropertyId($internalWebPropertyId) {
$this->internalWebPropertyId = $internalWebPropertyId;
}
public function getInternalWebPropertyId() {
return $this->internalWebPropertyId;
}
public function setChildLink(ProfileChildLink $childLink) {
$this->childLink = $childLink;
}
public function getChildLink() {
return $this->childLink;
}
public function setTimezone($timezone) {
$this->timezone = $timezone;
}
public function getTimezone() {
return $this->timezone;
}
public function setSiteSearchCategoryParameters($siteSearchCategoryParameters) {
$this->siteSearchCategoryParameters = $siteSearchCategoryParameters;
}
public function getSiteSearchCategoryParameters() {
return $this->siteSearchCategoryParameters;
}
public function setParentLink(ProfileParentLink $parentLink) {
$this->parentLink = $parentLink;
}
public function getParentLink() {
return $this->parentLink;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setAccountId($accountId) {
$this->accountId = $accountId;
}
public function getAccountId() {
return $this->accountId;
}
}
class ProfileChildLink extends apiModel {
public $href;
public $type;
public function setHref($href) {
$this->href = $href;
}
public function getHref() {
return $this->href;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class ProfileParentLink extends apiModel {
public $href;
public $type;
public function setHref($href) {
$this->href = $href;
}
public function getHref() {
return $this->href;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class Profiles extends apiModel {
public $username;
public $kind;
protected $__itemsType = 'Profile';
protected $__itemsDataType = 'array';
public $items;
public $itemsPerPage;
public $previousLink;
public $startIndex;
public $nextLink;
public $totalResults;
public function setUsername($username) {
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(Profile) */ $items) {
$this->assertIsArray($items, 'Profile', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setItemsPerPage($itemsPerPage) {
$this->itemsPerPage = $itemsPerPage;
}
public function getItemsPerPage() {
return $this->itemsPerPage;
}
public function setPreviousLink($previousLink) {
$this->previousLink = $previousLink;
}
public function getPreviousLink() {
return $this->previousLink;
}
public function setStartIndex($startIndex) {
$this->startIndex = $startIndex;
}
public function getStartIndex() {
return $this->startIndex;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setTotalResults($totalResults) {
$this->totalResults = $totalResults;
}
public function getTotalResults() {
return $this->totalResults;
}
}
class Segment extends apiModel {
public $definition;
public $kind;
public $segmentId;
public $created;
public $updated;
public $id;
public $selfLink;
public $name;
public function setDefinition($definition) {
$this->definition = $definition;
}
public function getDefinition() {
return $this->definition;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setSegmentId($segmentId) {
$this->segmentId = $segmentId;
}
public function getSegmentId() {
return $this->segmentId;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class Segments extends apiModel {
public $username;
public $kind;
protected $__itemsType = 'Segment';
protected $__itemsDataType = 'array';
public $items;
public $itemsPerPage;
public $previousLink;
public $startIndex;
public $nextLink;
public $totalResults;
public function setUsername($username) {
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(Segment) */ $items) {
$this->assertIsArray($items, 'Segment', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setItemsPerPage($itemsPerPage) {
$this->itemsPerPage = $itemsPerPage;
}
public function getItemsPerPage() {
return $this->itemsPerPage;
}
public function setPreviousLink($previousLink) {
$this->previousLink = $previousLink;
}
public function getPreviousLink() {
return $this->previousLink;
}
public function setStartIndex($startIndex) {
$this->startIndex = $startIndex;
}
public function getStartIndex() {
return $this->startIndex;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setTotalResults($totalResults) {
$this->totalResults = $totalResults;
}
public function getTotalResults() {
return $this->totalResults;
}
}
class Webproperties extends apiModel {
public $username;
public $kind;
protected $__itemsType = 'Webproperty';
protected $__itemsDataType = 'array';
public $items;
public $itemsPerPage;
public $previousLink;
public $startIndex;
public $nextLink;
public $totalResults;
public function setUsername($username) {
$this->username = $username;
}
public function getUsername() {
return $this->username;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(Webproperty) */ $items) {
$this->assertIsArray($items, 'Webproperty', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setItemsPerPage($itemsPerPage) {
$this->itemsPerPage = $itemsPerPage;
}
public function getItemsPerPage() {
return $this->itemsPerPage;
}
public function setPreviousLink($previousLink) {
$this->previousLink = $previousLink;
}
public function getPreviousLink() {
return $this->previousLink;
}
public function setStartIndex($startIndex) {
$this->startIndex = $startIndex;
}
public function getStartIndex() {
return $this->startIndex;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setTotalResults($totalResults) {
$this->totalResults = $totalResults;
}
public function getTotalResults() {
return $this->totalResults;
}
}
class Webproperty extends apiModel {
public $kind;
public $name;
public $created;
public $updated;
public $websiteUrl;
public $internalWebPropertyId;
protected $__childLinkType = 'WebpropertyChildLink';
protected $__childLinkDataType = '';
public $childLink;
protected $__parentLinkType = 'WebpropertyParentLink';
protected $__parentLinkDataType = '';
public $parentLink;
public $id;
public $selfLink;
public $accountId;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setWebsiteUrl($websiteUrl) {
$this->websiteUrl = $websiteUrl;
}
public function getWebsiteUrl() {
return $this->websiteUrl;
}
public function setInternalWebPropertyId($internalWebPropertyId) {
$this->internalWebPropertyId = $internalWebPropertyId;
}
public function getInternalWebPropertyId() {
return $this->internalWebPropertyId;
}
public function setChildLink(WebpropertyChildLink $childLink) {
$this->childLink = $childLink;
}
public function getChildLink() {
return $this->childLink;
}
public function setParentLink(WebpropertyParentLink $parentLink) {
$this->parentLink = $parentLink;
}
public function getParentLink() {
return $this->parentLink;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setAccountId($accountId) {
$this->accountId = $accountId;
}
public function getAccountId() {
return $this->accountId;
}
}
class WebpropertyChildLink extends apiModel {
public $href;
public $type;
public function setHref($href) {
$this->href = $href;
}
public function getHref() {
return $this->href;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class WebpropertyParentLink extends apiModel {
public $href;
public $type;
public function setHref($href) {
$this->href = $href;
}
public function getHref() {
return $this->href;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiAnalyticsService.php | PHP | asf20 | 47,940 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "products" collection of methods.
* Typical usage is:
* <code>
* $shoppingService = new apiShoppingService(...);
* $products = $shoppingService->products;
* </code>
*/
class ProductsServiceResource extends apiServiceResource {
/**
* Returns a list of products and content modules (products.list)
*
* @param string $source Query source
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool sayt.useGcsConfig Google Internal
* @opt_param string rankBy Ranking specification
* @opt_param bool debug.enableLogging Google Internal
* @opt_param bool facets.enabled Whether to return facet information
* @opt_param bool relatedQueries.useGcsConfig This parameter is currently ignored
* @opt_param bool promotions.enabled Whether to return promotion information
* @opt_param bool debug.enabled Google Internal
* @opt_param string facets.include Facets to include (applies when useGcsConfig == false)
* @opt_param string productFields Google Internal
* @opt_param string channels Channels specification
* @opt_param string currency Currency restriction (ISO 4217)
* @opt_param string startIndex Index (1-based) of first product to return
* @opt_param string facets.discover Facets to discover
* @opt_param bool debug.searchResponse Google Internal
* @opt_param string crowdBy Crowding specification
* @opt_param bool spelling.enabled Whether to return spelling suggestions
* @opt_param string taxonomy Taxonomy name
* @opt_param bool debug.geocodeRequest Google Internal
* @opt_param bool spelling.useGcsConfig This parameter is currently ignored
* @opt_param string useCase One of CommerceSearchUseCase, ShoppingApiUseCase
* @opt_param string location Location used to determine tax and shipping
* @opt_param string maxVariants Maximum number of variant results to return per result
* @opt_param bool debug.rdcRequest Google Internal
* @opt_param string categories.include Category specification
* @opt_param string boostBy Boosting specification
* @opt_param bool redirects.useGcsConfig Whether to return redirect information as configured in the GCS account
* @opt_param bool safe Whether safe search is enabled. Default: true
* @opt_param bool categories.useGcsConfig This parameter is currently ignored
* @opt_param string maxResults Maximum number of results to return
* @opt_param bool facets.useGcsConfig Whether to return facet information as configured in the GCS account
* @opt_param bool categories.enabled Whether to return category information
* @opt_param string attributeFilter Comma separated list of attributes to return
* @opt_param bool sayt.enabled Google Internal
* @opt_param bool promotions.useGcsConfig Whether to return promotion information as configured in the GCS account
* @opt_param string thumbnails Image thumbnails specification
* @opt_param string language Language restriction (BCP 47)
* @opt_param string country Country restriction (ISO 3166)
* @opt_param bool debug.geocodeResponse Google Internal
* @opt_param string restrictBy Restriction specification
* @opt_param bool debug.rdcResponse Google Internal
* @opt_param string q Search query
* @opt_param bool redirects.enabled Whether to return redirect information
* @opt_param bool debug.searchRequest Google Internal
* @opt_param bool relatedQueries.enabled Whether to return related queries
* @opt_param string minAvailability
* @opt_param string plusOne +1 rendering specification.
* @return Products
*/
public function listProducts($source, $optParams = array()) {
$params = array('source' => $source);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Products($data);
} else {
return $data;
}
}
/**
* Returns a single product (products.get)
*
* @param string $source Query source
* @param string $accountId Merchant center account id
* @param string $productIdType Type of productId
* @param string $productId Id of product
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string categories.include Category specification
* @opt_param bool recommendations.enabled Whether to return recommendation information
* @opt_param bool debug.enableLogging Google Internal
* @opt_param string taxonomy Merchant taxonomy
* @opt_param bool categories.useGcsConfig This parameter is currently ignored
* @opt_param bool debug.searchResponse Google Internal
* @opt_param bool debug.enabled Google Internal
* @opt_param string recommendations.include Recommendation specification
* @opt_param bool categories.enabled Whether to return category information
* @opt_param string productFields Google Internal
* @opt_param string location Location used to determine tax and shipping
* @opt_param bool debug.searchRequest Google Internal
* @opt_param string attributeFilter Comma separated list of attributes to return
* @opt_param bool recommendations.useGcsConfig This parameter is currently ignored
* @opt_param string plusOne +1 rendering specification.
* @opt_param string thumbnails Thumbnail specification
* @return Product
*/
public function get($source, $accountId, $productIdType, $productId, $optParams = array()) {
$params = array('source' => $source, 'accountId' => $accountId, 'productIdType' => $productIdType, 'productId' => $productId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Product($data);
} else {
return $data;
}
}
}
/**
* Service definition for Shopping (v1).
*
* <p>
* Lets you search over product data
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/shopping/search/v1/getting_started.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiShoppingService extends apiService {
public $products;
/**
* Constructs the internal representation of the Shopping service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/shopping/search/v1/';
$this->version = 'v1';
$this->serviceName = 'shopping';
$apiClient->addService($this->serviceName, $this->version);
$this->products = new ProductsServiceResource($this, $this->serviceName, 'products', json_decode('{"methods": {"list": {"parameters": {"sayt.useGcsConfig": {"type": "boolean", "location": "query"}, "debug.geocodeResponse": {"type": "boolean", "location": "query"}, "debug.enableLogging": {"type": "boolean", "location": "query"}, "facets.enabled": {"type": "boolean", "location": "query"}, "relatedQueries.useGcsConfig": {"type": "boolean", "location": "query"}, "promotions.enabled": {"type": "boolean", "location": "query"}, "debug.enabled": {"type": "boolean", "location": "query"}, "facets.include": {"type": "string", "location": "query"}, "productFields": {"type": "string", "location": "query"}, "channels": {"type": "string", "location": "query"}, "currency": {"type": "string", "location": "query"}, "startIndex": {"format": "uint32", "type": "integer", "location": "query"}, "facets.discover": {"type": "string", "location": "query"}, "debug.searchResponse": {"type": "boolean", "location": "query"}, "crowdBy": {"type": "string", "location": "query"}, "spelling.enabled": {"type": "boolean", "location": "query"}, "debug.geocodeRequest": {"type": "boolean", "location": "query"}, "source": {"required": true, "type": "string", "location": "path"}, "spelling.useGcsConfig": {"type": "boolean", "location": "query"}, "useCase": {"type": "string", "location": "query"}, "location": {"type": "string", "location": "query"}, "taxonomy": {"type": "string", "location": "query"}, "debug.rdcRequest": {"type": "boolean", "location": "query"}, "categories.include": {"type": "string", "location": "query"}, "debug.searchRequest": {"type": "boolean", "location": "query"}, "safe": {"type": "boolean", "location": "query"}, "boostBy": {"type": "string", "location": "query"}, "maxVariants": {"format": "uint32", "type": "integer", "location": "query"}, "categories.useGcsConfig": {"type": "boolean", "location": "query"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}, "facets.useGcsConfig": {"type": "boolean", "location": "query"}, "categories.enabled": {"type": "boolean", "location": "query"}, "attributeFilter": {"type": "string", "location": "query"}, "sayt.enabled": {"type": "boolean", "location": "query"}, "plusOne": {"type": "string", "location": "query"}, "thumbnails": {"type": "string", "location": "query"}, "language": {"type": "string", "location": "query"}, "redirects.useGcsConfig": {"type": "boolean", "location": "query"}, "rankBy": {"type": "string", "location": "query"}, "restrictBy": {"type": "string", "location": "query"}, "debug.rdcResponse": {"type": "boolean", "location": "query"}, "q": {"type": "string", "location": "query"}, "redirects.enabled": {"type": "boolean", "location": "query"}, "country": {"type": "string", "location": "query"}, "relatedQueries.enabled": {"type": "boolean", "location": "query"}, "minAvailability": {"enum": ["inStock", "limited", "outOfStock", "unknown"], "type": "string", "location": "query"}, "promotions.useGcsConfig": {"type": "boolean", "location": "query"}}, "id": "shopping.products.list", "httpMethod": "GET", "path": "{source}/products", "response": {"$ref": "Products"}}, "get": {"parameters": {"categories.include": {"type": "string", "location": "query"}, "recommendations.enabled": {"type": "boolean", "location": "query"}, "plusOne": {"type": "string", "location": "query"}, "debug.enableLogging": {"type": "boolean", "location": "query"}, "thumbnails": {"type": "string", "location": "query"}, "recommendations.include": {"type": "string", "location": "query"}, "taxonomy": {"type": "string", "location": "query"}, "productIdType": {"required": true, "type": "string", "location": "path"}, "categories.useGcsConfig": {"type": "boolean", "location": "query"}, "attributeFilter": {"type": "string", "location": "query"}, "debug.enabled": {"type": "boolean", "location": "query"}, "source": {"required": true, "type": "string", "location": "path"}, "categories.enabled": {"type": "boolean", "location": "query"}, "location": {"type": "string", "location": "query"}, "debug.searchRequest": {"type": "boolean", "location": "query"}, "debug.searchResponse": {"type": "boolean", "location": "query"}, "recommendations.useGcsConfig": {"type": "boolean", "location": "query"}, "productFields": {"type": "string", "location": "query"}, "accountId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "productId": {"required": true, "type": "string", "location": "path"}}, "id": "shopping.products.get", "httpMethod": "GET", "path": "{source}/products/{accountId}/{productIdType}/{productId}", "response": {"$ref": "Product"}}}}', true));
}
}
class Product extends apiModel {
public $selfLink;
public $kind;
protected $__productType = 'ShoppingModelProductJsonV1';
protected $__productDataType = '';
public $product;
public $requestId;
protected $__recommendationsType = 'ProductRecommendations';
protected $__recommendationsDataType = 'array';
public $recommendations;
protected $__debugType = 'ShoppingModelDebugJsonV1';
protected $__debugDataType = '';
public $debug;
public $id;
protected $__categoriesType = 'ShoppingModelCategoryJsonV1';
protected $__categoriesDataType = 'array';
public $categories;
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setProduct(ShoppingModelProductJsonV1 $product) {
$this->product = $product;
}
public function getProduct() {
return $this->product;
}
public function setRequestId($requestId) {
$this->requestId = $requestId;
}
public function getRequestId() {
return $this->requestId;
}
public function setRecommendations(/* array(ProductRecommendations) */ $recommendations) {
$this->assertIsArray($recommendations, 'ProductRecommendations', __METHOD__);
$this->recommendations = $recommendations;
}
public function getRecommendations() {
return $this->recommendations;
}
public function setDebug(ShoppingModelDebugJsonV1 $debug) {
$this->debug = $debug;
}
public function getDebug() {
return $this->debug;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setCategories(/* array(ShoppingModelCategoryJsonV1) */ $categories) {
$this->assertIsArray($categories, 'ShoppingModelCategoryJsonV1', __METHOD__);
$this->categories = $categories;
}
public function getCategories() {
return $this->categories;
}
}
class ProductRecommendations extends apiModel {
protected $__recommendationListType = 'ProductRecommendationsRecommendationList';
protected $__recommendationListDataType = 'array';
public $recommendationList;
public $type;
public function setRecommendationList(/* array(ProductRecommendationsRecommendationList) */ $recommendationList) {
$this->assertIsArray($recommendationList, 'ProductRecommendationsRecommendationList', __METHOD__);
$this->recommendationList = $recommendationList;
}
public function getRecommendationList() {
return $this->recommendationList;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class ProductRecommendationsRecommendationList extends apiModel {
protected $__productType = 'ShoppingModelProductJsonV1';
protected $__productDataType = '';
public $product;
public function setProduct(ShoppingModelProductJsonV1 $product) {
$this->product = $product;
}
public function getProduct() {
return $this->product;
}
}
class Products extends apiModel {
protected $__promotionsType = 'ProductsPromotions';
protected $__promotionsDataType = 'array';
public $promotions;
public $selfLink;
public $kind;
protected $__storesType = 'ProductsStores';
protected $__storesDataType = 'array';
public $stores;
public $currentItemCount;
protected $__itemsType = 'Product';
protected $__itemsDataType = 'array';
public $items;
protected $__facetsType = 'ProductsFacets';
protected $__facetsDataType = 'array';
public $facets;
public $itemsPerPage;
public $redirects;
public $nextLink;
protected $__shelfSpaceAdsType = 'ProductsShelfSpaceAds';
protected $__shelfSpaceAdsDataType = 'array';
public $shelfSpaceAds;
public $startIndex;
public $etag;
public $requestId;
public $relatedQueries;
protected $__debugType = 'ShoppingModelDebugJsonV1';
protected $__debugDataType = '';
public $debug;
protected $__spellingType = 'ProductsSpelling';
protected $__spellingDataType = '';
public $spelling;
public $previousLink;
public $totalItems;
public $id;
protected $__categoriesType = 'ShoppingModelCategoryJsonV1';
protected $__categoriesDataType = 'array';
public $categories;
public function setPromotions(/* array(ProductsPromotions) */ $promotions) {
$this->assertIsArray($promotions, 'ProductsPromotions', __METHOD__);
$this->promotions = $promotions;
}
public function getPromotions() {
return $this->promotions;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setStores(/* array(ProductsStores) */ $stores) {
$this->assertIsArray($stores, 'ProductsStores', __METHOD__);
$this->stores = $stores;
}
public function getStores() {
return $this->stores;
}
public function setCurrentItemCount($currentItemCount) {
$this->currentItemCount = $currentItemCount;
}
public function getCurrentItemCount() {
return $this->currentItemCount;
}
public function setItems(/* array(Product) */ $items) {
$this->assertIsArray($items, 'Product', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setFacets(/* array(ProductsFacets) */ $facets) {
$this->assertIsArray($facets, 'ProductsFacets', __METHOD__);
$this->facets = $facets;
}
public function getFacets() {
return $this->facets;
}
public function setItemsPerPage($itemsPerPage) {
$this->itemsPerPage = $itemsPerPage;
}
public function getItemsPerPage() {
return $this->itemsPerPage;
}
public function setRedirects(/* array(string) */ $redirects) {
$this->assertIsArray($redirects, 'string', __METHOD__);
$this->redirects = $redirects;
}
public function getRedirects() {
return $this->redirects;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setShelfSpaceAds(/* array(ProductsShelfSpaceAds) */ $shelfSpaceAds) {
$this->assertIsArray($shelfSpaceAds, 'ProductsShelfSpaceAds', __METHOD__);
$this->shelfSpaceAds = $shelfSpaceAds;
}
public function getShelfSpaceAds() {
return $this->shelfSpaceAds;
}
public function setStartIndex($startIndex) {
$this->startIndex = $startIndex;
}
public function getStartIndex() {
return $this->startIndex;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setRequestId($requestId) {
$this->requestId = $requestId;
}
public function getRequestId() {
return $this->requestId;
}
public function setRelatedQueries(/* array(string) */ $relatedQueries) {
$this->assertIsArray($relatedQueries, 'string', __METHOD__);
$this->relatedQueries = $relatedQueries;
}
public function getRelatedQueries() {
return $this->relatedQueries;
}
public function setDebug(ShoppingModelDebugJsonV1 $debug) {
$this->debug = $debug;
}
public function getDebug() {
return $this->debug;
}
public function setSpelling(ProductsSpelling $spelling) {
$this->spelling = $spelling;
}
public function getSpelling() {
return $this->spelling;
}
public function setPreviousLink($previousLink) {
$this->previousLink = $previousLink;
}
public function getPreviousLink() {
return $this->previousLink;
}
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setCategories(/* array(ShoppingModelCategoryJsonV1) */ $categories) {
$this->assertIsArray($categories, 'ShoppingModelCategoryJsonV1', __METHOD__);
$this->categories = $categories;
}
public function getCategories() {
return $this->categories;
}
}
class ProductsFacets extends apiModel {
public $count;
public $displayName;
public $name;
protected $__bucketsType = 'ProductsFacetsBuckets';
protected $__bucketsDataType = 'array';
public $buckets;
public $property;
public $type;
public $unit;
public function setCount($count) {
$this->count = $count;
}
public function getCount() {
return $this->count;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setBuckets(/* array(ProductsFacetsBuckets) */ $buckets) {
$this->assertIsArray($buckets, 'ProductsFacetsBuckets', __METHOD__);
$this->buckets = $buckets;
}
public function getBuckets() {
return $this->buckets;
}
public function setProperty($property) {
$this->property = $property;
}
public function getProperty() {
return $this->property;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setUnit($unit) {
$this->unit = $unit;
}
public function getUnit() {
return $this->unit;
}
}
class ProductsFacetsBuckets extends apiModel {
public $count;
public $minExclusive;
public $min;
public $max;
public $value;
public $maxExclusive;
public function setCount($count) {
$this->count = $count;
}
public function getCount() {
return $this->count;
}
public function setMinExclusive($minExclusive) {
$this->minExclusive = $minExclusive;
}
public function getMinExclusive() {
return $this->minExclusive;
}
public function setMin($min) {
$this->min = $min;
}
public function getMin() {
return $this->min;
}
public function setMax($max) {
$this->max = $max;
}
public function getMax() {
return $this->max;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function setMaxExclusive($maxExclusive) {
$this->maxExclusive = $maxExclusive;
}
public function getMaxExclusive() {
return $this->maxExclusive;
}
}
class ProductsPromotions extends apiModel {
protected $__productType = 'ShoppingModelProductJsonV1';
protected $__productDataType = '';
public $product;
public $description;
public $imageLink;
public $destLink;
public $customHtml;
public $link;
protected $__customFieldsType = 'ProductsPromotionsCustomFields';
protected $__customFieldsDataType = 'array';
public $customFields;
public $type;
public $name;
public function setProduct(ShoppingModelProductJsonV1 $product) {
$this->product = $product;
}
public function getProduct() {
return $this->product;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setImageLink($imageLink) {
$this->imageLink = $imageLink;
}
public function getImageLink() {
return $this->imageLink;
}
public function setDestLink($destLink) {
$this->destLink = $destLink;
}
public function getDestLink() {
return $this->destLink;
}
public function setCustomHtml($customHtml) {
$this->customHtml = $customHtml;
}
public function getCustomHtml() {
return $this->customHtml;
}
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setCustomFields(/* array(ProductsPromotionsCustomFields) */ $customFields) {
$this->assertIsArray($customFields, 'ProductsPromotionsCustomFields', __METHOD__);
$this->customFields = $customFields;
}
public function getCustomFields() {
return $this->customFields;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class ProductsPromotionsCustomFields extends apiModel {
public $name;
public $value;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class ProductsShelfSpaceAds extends apiModel {
protected $__productType = 'ShoppingModelProductJsonV1';
protected $__productDataType = '';
public $product;
public function setProduct(ShoppingModelProductJsonV1 $product) {
$this->product = $product;
}
public function getProduct() {
return $this->product;
}
}
class ProductsSpelling extends apiModel {
public $suggestion;
public function setSuggestion($suggestion) {
$this->suggestion = $suggestion;
}
public function getSuggestion() {
return $this->suggestion;
}
}
class ProductsStores extends apiModel {
public $storeCode;
public $name;
public $storeId;
public $telephone;
public $location;
public $address;
public function setStoreCode($storeCode) {
$this->storeCode = $storeCode;
}
public function getStoreCode() {
return $this->storeCode;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setStoreId($storeId) {
$this->storeId = $storeId;
}
public function getStoreId() {
return $this->storeId;
}
public function setTelephone($telephone) {
$this->telephone = $telephone;
}
public function getTelephone() {
return $this->telephone;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setAddress($address) {
$this->address = $address;
}
public function getAddress() {
return $this->address;
}
}
class ShoppingModelCategoryJsonV1 extends apiModel {
public $url;
public $shortName;
public $parents;
public $id;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setShortName($shortName) {
$this->shortName = $shortName;
}
public function getShortName() {
return $this->shortName;
}
public function setParents(/* array(string) */ $parents) {
$this->assertIsArray($parents, 'string', __METHOD__);
$this->parents = $parents;
}
public function getParents() {
return $this->parents;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class ShoppingModelDebugJsonV1 extends apiModel {
public $searchResponse;
public $searchRequest;
public $rdcResponse;
protected $__backendTimesType = 'ShoppingModelDebugJsonV1BackendTimes';
protected $__backendTimesDataType = 'array';
public $backendTimes;
public $elapsedMillis;
public function setSearchResponse($searchResponse) {
$this->searchResponse = $searchResponse;
}
public function getSearchResponse() {
return $this->searchResponse;
}
public function setSearchRequest($searchRequest) {
$this->searchRequest = $searchRequest;
}
public function getSearchRequest() {
return $this->searchRequest;
}
public function setRdcResponse($rdcResponse) {
$this->rdcResponse = $rdcResponse;
}
public function getRdcResponse() {
return $this->rdcResponse;
}
public function setBackendTimes(/* array(ShoppingModelDebugJsonV1BackendTimes) */ $backendTimes) {
$this->assertIsArray($backendTimes, 'ShoppingModelDebugJsonV1BackendTimes', __METHOD__);
$this->backendTimes = $backendTimes;
}
public function getBackendTimes() {
return $this->backendTimes;
}
public function setElapsedMillis($elapsedMillis) {
$this->elapsedMillis = $elapsedMillis;
}
public function getElapsedMillis() {
return $this->elapsedMillis;
}
}
class ShoppingModelDebugJsonV1BackendTimes extends apiModel {
public $serverMillis;
public $hostName;
public $name;
public $elapsedMillis;
public function setServerMillis($serverMillis) {
$this->serverMillis = $serverMillis;
}
public function getServerMillis() {
return $this->serverMillis;
}
public function setHostName($hostName) {
$this->hostName = $hostName;
}
public function getHostName() {
return $this->hostName;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setElapsedMillis($elapsedMillis) {
$this->elapsedMillis = $elapsedMillis;
}
public function getElapsedMillis() {
return $this->elapsedMillis;
}
}
class ShoppingModelProductJsonV1 extends apiModel {
public $queryMatched;
public $gtin;
protected $__imagesType = 'ShoppingModelProductJsonV1Images';
protected $__imagesDataType = 'array';
public $images;
protected $__inventoriesType = 'ShoppingModelProductJsonV1Inventories';
protected $__inventoriesDataType = 'array';
public $inventories;
protected $__authorType = 'ShoppingModelProductJsonV1Author';
protected $__authorDataType = '';
public $author;
public $condition;
public $providedId;
public $internal8;
public $description;
public $gtins;
public $internal1;
public $brand;
public $internal3;
protected $__internal4Type = 'ShoppingModelProductJsonV1Internal4';
protected $__internal4DataType = 'array';
public $internal4;
public $internal6;
public $internal7;
public $link;
protected $__attributesType = 'ShoppingModelProductJsonV1Attributes';
protected $__attributesDataType = 'array';
public $attributes;
public $totalMatchingVariants;
protected $__variantsType = 'ShoppingModelProductJsonV1Variants';
protected $__variantsDataType = 'array';
public $variants;
public $modificationTime;
public $categories;
public $language;
public $country;
public $title;
public $creationTime;
public $internal14;
public $internal12;
public $internal13;
public $internal10;
public $plusOne;
public $googleId;
public $internal15;
public function setQueryMatched($queryMatched) {
$this->queryMatched = $queryMatched;
}
public function getQueryMatched() {
return $this->queryMatched;
}
public function setGtin($gtin) {
$this->gtin = $gtin;
}
public function getGtin() {
return $this->gtin;
}
public function setImages(/* array(ShoppingModelProductJsonV1Images) */ $images) {
$this->assertIsArray($images, 'ShoppingModelProductJsonV1Images', __METHOD__);
$this->images = $images;
}
public function getImages() {
return $this->images;
}
public function setInventories(/* array(ShoppingModelProductJsonV1Inventories) */ $inventories) {
$this->assertIsArray($inventories, 'ShoppingModelProductJsonV1Inventories', __METHOD__);
$this->inventories = $inventories;
}
public function getInventories() {
return $this->inventories;
}
public function setAuthor(ShoppingModelProductJsonV1Author $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setCondition($condition) {
$this->condition = $condition;
}
public function getCondition() {
return $this->condition;
}
public function setProvidedId($providedId) {
$this->providedId = $providedId;
}
public function getProvidedId() {
return $this->providedId;
}
public function setInternal8(/* array(string) */ $internal8) {
$this->assertIsArray($internal8, 'string', __METHOD__);
$this->internal8 = $internal8;
}
public function getInternal8() {
return $this->internal8;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setGtins(/* array(string) */ $gtins) {
$this->assertIsArray($gtins, 'string', __METHOD__);
$this->gtins = $gtins;
}
public function getGtins() {
return $this->gtins;
}
public function setInternal1(/* array(string) */ $internal1) {
$this->assertIsArray($internal1, 'string', __METHOD__);
$this->internal1 = $internal1;
}
public function getInternal1() {
return $this->internal1;
}
public function setBrand($brand) {
$this->brand = $brand;
}
public function getBrand() {
return $this->brand;
}
public function setInternal3($internal3) {
$this->internal3 = $internal3;
}
public function getInternal3() {
return $this->internal3;
}
public function setInternal4(/* array(ShoppingModelProductJsonV1Internal4) */ $internal4) {
$this->assertIsArray($internal4, 'ShoppingModelProductJsonV1Internal4', __METHOD__);
$this->internal4 = $internal4;
}
public function getInternal4() {
return $this->internal4;
}
public function setInternal6($internal6) {
$this->internal6 = $internal6;
}
public function getInternal6() {
return $this->internal6;
}
public function setInternal7($internal7) {
$this->internal7 = $internal7;
}
public function getInternal7() {
return $this->internal7;
}
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setAttributes(/* array(ShoppingModelProductJsonV1Attributes) */ $attributes) {
$this->assertIsArray($attributes, 'ShoppingModelProductJsonV1Attributes', __METHOD__);
$this->attributes = $attributes;
}
public function getAttributes() {
return $this->attributes;
}
public function setTotalMatchingVariants($totalMatchingVariants) {
$this->totalMatchingVariants = $totalMatchingVariants;
}
public function getTotalMatchingVariants() {
return $this->totalMatchingVariants;
}
public function setVariants(/* array(ShoppingModelProductJsonV1Variants) */ $variants) {
$this->assertIsArray($variants, 'ShoppingModelProductJsonV1Variants', __METHOD__);
$this->variants = $variants;
}
public function getVariants() {
return $this->variants;
}
public function setModificationTime($modificationTime) {
$this->modificationTime = $modificationTime;
}
public function getModificationTime() {
return $this->modificationTime;
}
public function setCategories(/* array(string) */ $categories) {
$this->assertIsArray($categories, 'string', __METHOD__);
$this->categories = $categories;
}
public function getCategories() {
return $this->categories;
}
public function setLanguage($language) {
$this->language = $language;
}
public function getLanguage() {
return $this->language;
}
public function setCountry($country) {
$this->country = $country;
}
public function getCountry() {
return $this->country;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setCreationTime($creationTime) {
$this->creationTime = $creationTime;
}
public function getCreationTime() {
return $this->creationTime;
}
public function setInternal14($internal14) {
$this->internal14 = $internal14;
}
public function getInternal14() {
return $this->internal14;
}
public function setInternal12($internal12) {
$this->internal12 = $internal12;
}
public function getInternal12() {
return $this->internal12;
}
public function setInternal13($internal13) {
$this->internal13 = $internal13;
}
public function getInternal13() {
return $this->internal13;
}
public function setInternal10(/* array(string) */ $internal10) {
$this->assertIsArray($internal10, 'string', __METHOD__);
$this->internal10 = $internal10;
}
public function getInternal10() {
return $this->internal10;
}
public function setPlusOne($plusOne) {
$this->plusOne = $plusOne;
}
public function getPlusOne() {
return $this->plusOne;
}
public function setGoogleId($googleId) {
$this->googleId = $googleId;
}
public function getGoogleId() {
return $this->googleId;
}
public function setInternal15($internal15) {
$this->internal15 = $internal15;
}
public function getInternal15() {
return $this->internal15;
}
}
class ShoppingModelProductJsonV1Attributes extends apiModel {
public $type;
public $value;
public $displayName;
public $name;
public $unit;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setUnit($unit) {
$this->unit = $unit;
}
public function getUnit() {
return $this->unit;
}
}
class ShoppingModelProductJsonV1Author extends apiModel {
public $name;
public $accountId;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setAccountId($accountId) {
$this->accountId = $accountId;
}
public function getAccountId() {
return $this->accountId;
}
}
class ShoppingModelProductJsonV1Images extends apiModel {
public $link;
protected $__thumbnailsType = 'ShoppingModelProductJsonV1ImagesThumbnails';
protected $__thumbnailsDataType = 'array';
public $thumbnails;
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setThumbnails(/* array(ShoppingModelProductJsonV1ImagesThumbnails) */ $thumbnails) {
$this->assertIsArray($thumbnails, 'ShoppingModelProductJsonV1ImagesThumbnails', __METHOD__);
$this->thumbnails = $thumbnails;
}
public function getThumbnails() {
return $this->thumbnails;
}
}
class ShoppingModelProductJsonV1ImagesThumbnails extends apiModel {
public $content;
public $width;
public $link;
public $height;
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setWidth($width) {
$this->width = $width;
}
public function getWidth() {
return $this->width;
}
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setHeight($height) {
$this->height = $height;
}
public function getHeight() {
return $this->height;
}
}
class ShoppingModelProductJsonV1Internal4 extends apiModel {
public $node;
public $confidence;
public function setNode($node) {
$this->node = $node;
}
public function getNode() {
return $this->node;
}
public function setConfidence($confidence) {
$this->confidence = $confidence;
}
public function getConfidence() {
return $this->confidence;
}
}
class ShoppingModelProductJsonV1Inventories extends apiModel {
public $distance;
public $price;
public $storeId;
public $tax;
public $shipping;
public $currency;
public $distanceUnit;
public $availability;
public $channel;
public function setDistance($distance) {
$this->distance = $distance;
}
public function getDistance() {
return $this->distance;
}
public function setPrice($price) {
$this->price = $price;
}
public function getPrice() {
return $this->price;
}
public function setStoreId($storeId) {
$this->storeId = $storeId;
}
public function getStoreId() {
return $this->storeId;
}
public function setTax($tax) {
$this->tax = $tax;
}
public function getTax() {
return $this->tax;
}
public function setShipping($shipping) {
$this->shipping = $shipping;
}
public function getShipping() {
return $this->shipping;
}
public function setCurrency($currency) {
$this->currency = $currency;
}
public function getCurrency() {
return $this->currency;
}
public function setDistanceUnit($distanceUnit) {
$this->distanceUnit = $distanceUnit;
}
public function getDistanceUnit() {
return $this->distanceUnit;
}
public function setAvailability($availability) {
$this->availability = $availability;
}
public function getAvailability() {
return $this->availability;
}
public function setChannel($channel) {
$this->channel = $channel;
}
public function getChannel() {
return $this->channel;
}
}
class ShoppingModelProductJsonV1Variants extends apiModel {
protected $__variantType = 'ShoppingModelProductJsonV1';
protected $__variantDataType = '';
public $variant;
public function setVariant(ShoppingModelProductJsonV1 $variant) {
$this->variant = $variant;
}
public function getVariant() {
return $this->variant;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiShoppingService.php | PHP | asf20 | 41,742 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "languages" collection of methods.
* Typical usage is:
* <code>
* $translateService = new apiTranslateService(...);
* $languages = $translateService->languages;
* </code>
*/
class LanguagesServiceResource extends apiServiceResource {
/**
* List the source/target languages supported by the API (languages.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string target the language and collation in which the localized results should be returned
* @return LanguagesListResponse
*/
public function listLanguages($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new LanguagesListResponse($data);
} else {
return $data;
}
}
}
/**
* The "detections" collection of methods.
* Typical usage is:
* <code>
* $translateService = new apiTranslateService(...);
* $detections = $translateService->detections;
* </code>
*/
class DetectionsServiceResource extends apiServiceResource {
/**
* Detect the language of text. (detections.list)
*
* @param string $q The text to detect
* @return DetectionsListResponse
*/
public function listDetections($q, $optParams = array()) {
$params = array('q' => $q);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new DetectionsListResponse($data);
} else {
return $data;
}
}
}
/**
* The "translations" collection of methods.
* Typical usage is:
* <code>
* $translateService = new apiTranslateService(...);
* $translations = $translateService->translations;
* </code>
*/
class TranslationsServiceResource extends apiServiceResource {
/**
* Returns text translations from one language to another. (translations.list)
*
* @param string $q The text to translate
* @param string $target The target language into which the text should be translated
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string source The source language of the text
* @opt_param string format The format of the text
* @opt_param string cid The customization id for translate
* @return TranslationsListResponse
*/
public function listTranslations($q, $target, $optParams = array()) {
$params = array('q' => $q, 'target' => $target);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new TranslationsListResponse($data);
} else {
return $data;
}
}
}
/**
* Service definition for Translate (v2).
*
* <p>
* Lets you translate text from one language to another
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/language/translate/v2/using_rest.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiTranslateService extends apiService {
public $languages;
public $detections;
public $translations;
/**
* Constructs the internal representation of the Translate service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/language/translate/';
$this->version = 'v2';
$this->serviceName = 'translate';
$apiClient->addService($this->serviceName, $this->version);
$this->languages = new LanguagesServiceResource($this, $this->serviceName, 'languages', json_decode('{"methods": {"list": {"parameters": {"target": {"type": "string", "location": "query"}}, "id": "language.languages.list", "httpMethod": "GET", "path": "v2/languages", "response": {"$ref": "LanguagesListResponse"}}}}', true));
$this->detections = new DetectionsServiceResource($this, $this->serviceName, 'detections', json_decode('{"methods": {"list": {"parameters": {"q": {"repeated": true, "required": true, "type": "string", "location": "query"}}, "id": "language.detections.list", "httpMethod": "GET", "path": "v2/detect", "response": {"$ref": "DetectionsListResponse"}}}}', true));
$this->translations = new TranslationsServiceResource($this, $this->serviceName, 'translations', json_decode('{"methods": {"list": {"parameters": {"q": {"repeated": true, "required": true, "type": "string", "location": "query"}, "source": {"type": "string", "location": "query"}, "cid": {"repeated": true, "type": "string", "location": "query"}, "target": {"required": true, "type": "string", "location": "query"}, "format": {"enum": ["html", "text"], "type": "string", "location": "query"}}, "id": "language.translations.list", "httpMethod": "GET", "path": "v2", "response": {"$ref": "TranslationsListResponse"}}}}', true));
}
}
class DetectionsListResponse extends apiModel {
protected $__detectionsType = 'DetectionsResourceItems';
protected $__detectionsDataType = 'array';
public $detections;
public function setDetections(/* array(DetectionsResourceItems) */ $detections) {
$this->assertIsArray($detections, 'DetectionsResourceItems', __METHOD__);
$this->detections = $detections;
}
public function getDetections() {
return $this->detections;
}
}
class DetectionsResource extends apiModel {
}
class DetectionsResourceItems extends apiModel {
public $isReliable;
public $confidence;
public $language;
public function setIsReliable($isReliable) {
$this->isReliable = $isReliable;
}
public function getIsReliable() {
return $this->isReliable;
}
public function setConfidence($confidence) {
$this->confidence = $confidence;
}
public function getConfidence() {
return $this->confidence;
}
public function setLanguage($language) {
$this->language = $language;
}
public function getLanguage() {
return $this->language;
}
}
class LanguagesListResponse extends apiModel {
protected $__languagesType = 'LanguagesResource';
protected $__languagesDataType = 'array';
public $languages;
public function setLanguages(/* array(LanguagesResource) */ $languages) {
$this->assertIsArray($languages, 'LanguagesResource', __METHOD__);
$this->languages = $languages;
}
public function getLanguages() {
return $this->languages;
}
}
class LanguagesResource extends apiModel {
public $name;
public $language;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setLanguage($language) {
$this->language = $language;
}
public function getLanguage() {
return $this->language;
}
}
class TranslationsListResponse extends apiModel {
protected $__translationsType = 'TranslationsResource';
protected $__translationsDataType = 'array';
public $translations;
public function setTranslations(/* array(TranslationsResource) */ $translations) {
$this->assertIsArray($translations, 'TranslationsResource', __METHOD__);
$this->translations = $translations;
}
public function getTranslations() {
return $this->translations;
}
}
class TranslationsResource extends apiModel {
public $detectedSourceLanguage;
public $translatedText;
public function setDetectedSourceLanguage($detectedSourceLanguage) {
$this->detectedSourceLanguage = $detectedSourceLanguage;
}
public function getDetectedSourceLanguage() {
return $this->detectedSourceLanguage;
}
public function setTranslatedText($translatedText) {
$this->translatedText = $translatedText;
}
public function getTranslatedText() {
return $this->translatedText;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiTranslateService.php | PHP | asf20 | 8,682 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "votes" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $votes = $moderatorService->votes;
* </code>
*/
class VotesServiceResource extends apiServiceResource {
/**
* Inserts a new vote by the authenticated user for the specified submission within the specified
* series. (votes.insert)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @param Vote $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string unauthToken User identifier for unauthenticated usage mode
* @return Vote
*/
public function insert($seriesId, $submissionId, Vote $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Vote($data);
} else {
return $data;
}
}
/**
* Updates the votes by the authenticated user for the specified submission within the specified
* series. This method supports patch semantics. (votes.patch)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @param Vote $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string userId
* @opt_param string unauthToken User identifier for unauthenticated usage mode
* @return Vote
*/
public function patch($seriesId, $submissionId, Vote $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Vote($data);
} else {
return $data;
}
}
/**
* Lists the votes by the authenticated user for the given series. (votes.list)
*
* @param string $seriesId The decimal ID of the Series.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string max-results Maximum number of results to return.
* @opt_param string start-index Index of the first result to be retrieved.
* @return VoteList
*/
public function listVotes($seriesId, $optParams = array()) {
$params = array('seriesId' => $seriesId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new VoteList($data);
} else {
return $data;
}
}
/**
* Updates the votes by the authenticated user for the specified submission within the specified
* series. (votes.update)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @param Vote $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string userId
* @opt_param string unauthToken User identifier for unauthenticated usage mode
* @return Vote
*/
public function update($seriesId, $submissionId, Vote $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Vote($data);
} else {
return $data;
}
}
/**
* Returns the votes by the authenticated user for the specified submission within the specified
* series. (votes.get)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string userId
* @opt_param string unauthToken User identifier for unauthenticated usage mode
* @return Vote
*/
public function get($seriesId, $submissionId, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Vote($data);
} else {
return $data;
}
}
}
/**
* The "responses" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $responses = $moderatorService->responses;
* </code>
*/
class ResponsesServiceResource extends apiServiceResource {
/**
* Inserts a response for the specified submission in the specified topic within the specified
* series. (responses.insert)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $topicId The decimal ID of the Topic within the Series.
* @param string $parentSubmissionId The decimal ID of the parent Submission within the Series.
* @param Submission $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string unauthToken User identifier for unauthenticated usage mode
* @opt_param bool anonymous Set to true to mark the new submission as anonymous.
* @return Submission
*/
public function insert($seriesId, $topicId, $parentSubmissionId, Submission $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'topicId' => $topicId, 'parentSubmissionId' => $parentSubmissionId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Submission($data);
} else {
return $data;
}
}
/**
* Lists or searches the responses for the specified submission within the specified series and
* returns the search results. (responses.list)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string max-results Maximum number of results to return.
* @opt_param string sort Sort order.
* @opt_param string author Restricts the results to submissions by a specific author.
* @opt_param string start-index Index of the first result to be retrieved.
* @opt_param string q Search query.
* @opt_param bool hasAttachedVideo Specifies whether to restrict to submissions that have videos attached.
* @return SubmissionList
*/
public function listResponses($seriesId, $submissionId, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SubmissionList($data);
} else {
return $data;
}
}
}
/**
* The "tags" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $tags = $moderatorService->tags;
* </code>
*/
class TagsServiceResource extends apiServiceResource {
/**
* Inserts a new tag for the specified submission within the specified series. (tags.insert)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @param Tag $postBody
* @return Tag
*/
public function insert($seriesId, $submissionId, Tag $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Tag($data);
} else {
return $data;
}
}
/**
* Lists all tags for the specified submission within the specified series. (tags.list)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @return TagList
*/
public function listTags($seriesId, $submissionId, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new TagList($data);
} else {
return $data;
}
}
/**
* Deletes the specified tag from the specified submission within the specified series.
* (tags.delete)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @param string $tagId
*/
public function delete($seriesId, $submissionId, $tagId, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId, 'tagId' => $tagId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "series" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $series = $moderatorService->series;
* </code>
*/
class SeriesServiceResource extends apiServiceResource {
/**
* Inserts a new series. (series.insert)
*
* @param Series $postBody
* @return Series
*/
public function insert(Series $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Series($data);
} else {
return $data;
}
}
/**
* Updates the specified series. This method supports patch semantics. (series.patch)
*
* @param string $seriesId The decimal ID of the Series.
* @param Series $postBody
* @return Series
*/
public function patch($seriesId, Series $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Series($data);
} else {
return $data;
}
}
/**
* Searches the series and returns the search results. (series.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string max-results Maximum number of results to return.
* @opt_param string q Search query.
* @opt_param string start-index Index of the first result to be retrieved.
* @return SeriesList
*/
public function listSeries($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SeriesList($data);
} else {
return $data;
}
}
/**
* Updates the specified series. (series.update)
*
* @param string $seriesId The decimal ID of the Series.
* @param Series $postBody
* @return Series
*/
public function update($seriesId, Series $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Series($data);
} else {
return $data;
}
}
/**
* Returns the specified series. (series.get)
*
* @param string $seriesId The decimal ID of the Series.
* @return Series
*/
public function get($seriesId, $optParams = array()) {
$params = array('seriesId' => $seriesId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Series($data);
} else {
return $data;
}
}
}
/**
* The "submissions" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $submissions = $moderatorService->submissions;
* </code>
*/
class SeriesSubmissionsServiceResource extends apiServiceResource {
/**
* Searches the submissions for the specified series and returns the search results.
* (submissions.list)
*
* @param string $seriesId The decimal ID of the Series.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string lang The language code for the language the client prefers resuls in.
* @opt_param string max-results Maximum number of results to return.
* @opt_param bool includeVotes Specifies whether to include the current user's vote
* @opt_param string start-index Index of the first result to be retrieved.
* @opt_param string author Restricts the results to submissions by a specific author.
* @opt_param string sort Sort order.
* @opt_param string q Search query.
* @opt_param bool hasAttachedVideo Specifies whether to restrict to submissions that have videos attached.
* @return SubmissionList
*/
public function listSeriesSubmissions($seriesId, $optParams = array()) {
$params = array('seriesId' => $seriesId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SubmissionList($data);
} else {
return $data;
}
}
}
/**
* The "responses" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $responses = $moderatorService->responses;
* </code>
*/
class SeriesResponsesServiceResource extends apiServiceResource {
/**
* Searches the responses for the specified series and returns the search results. (responses.list)
*
* @param string $seriesId The decimal ID of the Series.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string max-results Maximum number of results to return.
* @opt_param string sort Sort order.
* @opt_param string author Restricts the results to submissions by a specific author.
* @opt_param string start-index Index of the first result to be retrieved.
* @opt_param string q Search query.
* @opt_param bool hasAttachedVideo Specifies whether to restrict to submissions that have videos attached.
* @return SeriesList
*/
public function listSeriesResponses($seriesId, $optParams = array()) {
$params = array('seriesId' => $seriesId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SeriesList($data);
} else {
return $data;
}
}
}
/**
* The "topics" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $topics = $moderatorService->topics;
* </code>
*/
class TopicsServiceResource extends apiServiceResource {
/**
* Inserts a new topic into the specified series. (topics.insert)
*
* @param string $seriesId The decimal ID of the Series.
* @param Topic $postBody
* @return Topic
*/
public function insert($seriesId, Topic $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Topic($data);
} else {
return $data;
}
}
/**
* Searches the topics within the specified series and returns the search results. (topics.list)
*
* @param string $seriesId The decimal ID of the Series.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string max-results Maximum number of results to return.
* @opt_param string q Search query.
* @opt_param string start-index Index of the first result to be retrieved.
* @opt_param string mode
* @return TopicList
*/
public function listTopics($seriesId, $optParams = array()) {
$params = array('seriesId' => $seriesId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new TopicList($data);
} else {
return $data;
}
}
/**
* Updates the specified topic within the specified series. (topics.update)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $topicId The decimal ID of the Topic within the Series.
* @param Topic $postBody
* @return Topic
*/
public function update($seriesId, $topicId, Topic $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'topicId' => $topicId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Topic($data);
} else {
return $data;
}
}
/**
* Returns the specified topic from the specified series. (topics.get)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $topicId The decimal ID of the Topic within the Series.
* @return Topic
*/
public function get($seriesId, $topicId, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'topicId' => $topicId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Topic($data);
} else {
return $data;
}
}
}
/**
* The "submissions" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $submissions = $moderatorService->submissions;
* </code>
*/
class TopicsSubmissionsServiceResource extends apiServiceResource {
/**
* Searches the submissions for the specified topic within the specified series and returns the
* search results. (submissions.list)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $topicId The decimal ID of the Topic within the Series.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string max-results Maximum number of results to return.
* @opt_param bool includeVotes Specifies whether to include the current user's vote
* @opt_param string start-index Index of the first result to be retrieved.
* @opt_param string author Restricts the results to submissions by a specific author.
* @opt_param string sort Sort order.
* @opt_param string q Search query.
* @opt_param bool hasAttachedVideo Specifies whether to restrict to submissions that have videos attached.
* @return SubmissionList
*/
public function listTopicsSubmissions($seriesId, $topicId, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'topicId' => $topicId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SubmissionList($data);
} else {
return $data;
}
}
}
/**
* The "global" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $global = $moderatorService->global;
* </code>
*/
class ModeratorGlobalServiceResource extends apiServiceResource {
}
/**
* The "series" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $series = $moderatorService->series;
* </code>
*/
class ModeratorGlobalSeriesServiceResource extends apiServiceResource {
/**
* Searches the public series and returns the search results. (series.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string max-results Maximum number of results to return.
* @opt_param string q Search query.
* @opt_param string start-index Index of the first result to be retrieved.
* @return SeriesList
*/
public function listModeratorGlobalSeries($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SeriesList($data);
} else {
return $data;
}
}
}
/**
* The "profiles" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $profiles = $moderatorService->profiles;
* </code>
*/
class ProfilesServiceResource extends apiServiceResource {
/**
* Updates the profile information for the authenticated user. This method supports patch semantics.
* (profiles.patch)
*
* @param Profile $postBody
* @return Profile
*/
public function patch(Profile $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Profile($data);
} else {
return $data;
}
}
/**
* Updates the profile information for the authenticated user. (profiles.update)
*
* @param Profile $postBody
* @return Profile
*/
public function update(Profile $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Profile($data);
} else {
return $data;
}
}
/**
* Returns the profile information for the authenticated user. (profiles.get)
*
* @return Profile
*/
public function get($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Profile($data);
} else {
return $data;
}
}
}
/**
* The "featured" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $featured = $moderatorService->featured;
* </code>
*/
class FeaturedServiceResource extends apiServiceResource {
}
/**
* The "series" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $series = $moderatorService->series;
* </code>
*/
class FeaturedSeriesServiceResource extends apiServiceResource {
/**
* Lists the featured series. (series.list)
*
* @return SeriesList
*/
public function listFeaturedSeries($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SeriesList($data);
} else {
return $data;
}
}
}
/**
* The "myrecent" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $myrecent = $moderatorService->myrecent;
* </code>
*/
class MyrecentServiceResource extends apiServiceResource {
}
/**
* The "series" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $series = $moderatorService->series;
* </code>
*/
class MyrecentSeriesServiceResource extends apiServiceResource {
/**
* Lists the series the authenticated user has visited. (series.list)
*
* @return SeriesList
*/
public function listMyrecentSeries($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SeriesList($data);
} else {
return $data;
}
}
}
/**
* The "my" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $my = $moderatorService->my;
* </code>
*/
class MyServiceResource extends apiServiceResource {
}
/**
* The "series" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $series = $moderatorService->series;
* </code>
*/
class MySeriesServiceResource extends apiServiceResource {
/**
* Lists all series created by the authenticated user. (series.list)
*
* @return SeriesList
*/
public function listMySeries($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SeriesList($data);
} else {
return $data;
}
}
}
/**
* The "submissions" collection of methods.
* Typical usage is:
* <code>
* $moderatorService = new apiModeratorService(...);
* $submissions = $moderatorService->submissions;
* </code>
*/
class SubmissionsServiceResource extends apiServiceResource {
/**
* Inserts a new submission in the specified topic within the specified series. (submissions.insert)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $topicId The decimal ID of the Topic within the Series.
* @param Submission $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string unauthToken User identifier for unauthenticated usage mode
* @opt_param bool anonymous Set to true to mark the new submission as anonymous.
* @return Submission
*/
public function insert($seriesId, $topicId, Submission $postBody, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'topicId' => $topicId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Submission($data);
} else {
return $data;
}
}
/**
* Returns the specified submission within the specified series. (submissions.get)
*
* @param string $seriesId The decimal ID of the Series.
* @param string $submissionId The decimal ID of the Submission within the Series.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string lang The language code for the language the client prefers resuls in.
* @opt_param bool includeVotes Specifies whether to include the current user's vote
* @return Submission
*/
public function get($seriesId, $submissionId, $optParams = array()) {
$params = array('seriesId' => $seriesId, 'submissionId' => $submissionId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Submission($data);
} else {
return $data;
}
}
}
/**
* Service definition for Moderator (v1).
*
* <p>
* Moderator API
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/moderator/v1/using_rest.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiModeratorService extends apiService {
public $votes;
public $responses;
public $tags;
public $series;
public $series_submissions;
public $series_submissions_submissions;
public $series_submissions_responses;
public $series_responses;
public $series_responses_submissions;
public $series_responses_responses;
public $topics;
public $topics_submissions;
public $topics_submissions_submissions;
public $global;
public $global_series;
public $global_series_series;
public $profiles;
public $featured;
public $featured_series;
public $featured_series_series;
public $myrecent;
public $myrecent_series;
public $myrecent_series_series;
public $my;
public $my_series;
public $my_series_series;
public $submissions;
/**
* Constructs the internal representation of the Moderator service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/moderator/v1/';
$this->version = 'v1';
$this->serviceName = 'moderator';
$apiClient->addService($this->serviceName, $this->version);
$this->votes = new VotesServiceResource($this, $this->serviceName, 'votes', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "unauthToken": {"type": "string", "location": "query"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Vote"}, "id": "moderator.votes.insert", "httpMethod": "POST", "path": "series/{seriesId}/submissions/{submissionId}/votes/@me", "response": {"$ref": "Vote"}}, "get": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "userId": {"type": "string", "location": "query"}, "unauthToken": {"type": "string", "location": "query"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "id": "moderator.votes.get", "httpMethod": "GET", "path": "series/{seriesId}/submissions/{submissionId}/votes/@me", "response": {"$ref": "Vote"}}, "list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"max-results": {"format": "uint32", "type": "integer", "location": "query"}, "seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "start-index": {"format": "uint32", "type": "integer", "location": "query"}}, "id": "moderator.votes.list", "httpMethod": "GET", "path": "series/{seriesId}/votes/@me", "response": {"$ref": "VoteList"}}, "update": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "userId": {"type": "string", "location": "query"}, "unauthToken": {"type": "string", "location": "query"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Vote"}, "id": "moderator.votes.update", "httpMethod": "PUT", "path": "series/{seriesId}/submissions/{submissionId}/votes/@me", "response": {"$ref": "Vote"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "userId": {"type": "string", "location": "query"}, "unauthToken": {"type": "string", "location": "query"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Vote"}, "id": "moderator.votes.patch", "httpMethod": "PATCH", "path": "series/{seriesId}/submissions/{submissionId}/votes/@me", "response": {"$ref": "Vote"}}}}', true));
$this->responses = new ResponsesServiceResource($this, $this->serviceName, 'responses', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "parentSubmissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "unauthToken": {"type": "string", "location": "query"}, "anonymous": {"type": "boolean", "location": "query"}, "topicId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Submission"}, "id": "moderator.responses.insert", "httpMethod": "POST", "path": "series/{seriesId}/topics/{topicId}/submissions/{parentSubmissionId}/responses", "response": {"$ref": "Submission"}}, "list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"max-results": {"format": "uint32", "type": "integer", "location": "query"}, "sort": {"type": "string", "location": "query"}, "seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "author": {"type": "string", "location": "query"}, "start-index": {"format": "uint32", "type": "integer", "location": "query"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "q": {"type": "string", "location": "query"}, "hasAttachedVideo": {"type": "boolean", "location": "query"}}, "id": "moderator.responses.list", "httpMethod": "GET", "path": "series/{seriesId}/submissions/{submissionId}/responses", "response": {"$ref": "SubmissionList"}}}}', true));
$this->tags = new TagsServiceResource($this, $this->serviceName, 'tags', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Tag"}, "id": "moderator.tags.insert", "httpMethod": "POST", "path": "series/{seriesId}/submissions/{submissionId}/tags", "response": {"$ref": "Tag"}}, "list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "id": "moderator.tags.list", "httpMethod": "GET", "path": "series/{seriesId}/submissions/{submissionId}/tags", "response": {"$ref": "TagList"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "tagId": {"required": true, "type": "string", "location": "path"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "httpMethod": "DELETE", "path": "series/{seriesId}/submissions/{submissionId}/tags/{tagId}", "id": "moderator.tags.delete"}}}', true));
$this->series = new SeriesServiceResource($this, $this->serviceName, 'series', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/moderator"], "request": {"$ref": "Series"}, "response": {"$ref": "Series"}, "httpMethod": "POST", "path": "series", "id": "moderator.series.insert"}, "get": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "id": "moderator.series.get", "httpMethod": "GET", "path": "series/{seriesId}", "response": {"$ref": "Series"}}, "list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"max-results": {"format": "uint32", "type": "integer", "location": "query"}, "q": {"type": "string", "location": "query"}, "start-index": {"format": "uint32", "type": "integer", "location": "query"}}, "response": {"$ref": "SeriesList"}, "httpMethod": "GET", "path": "series", "id": "moderator.series.list"}, "update": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Series"}, "id": "moderator.series.update", "httpMethod": "PUT", "path": "series/{seriesId}", "response": {"$ref": "Series"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Series"}, "id": "moderator.series.patch", "httpMethod": "PATCH", "path": "series/{seriesId}", "response": {"$ref": "Series"}}}}', true));
$this->series_submissions = new SeriesSubmissionsServiceResource($this, $this->serviceName, 'submissions', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"lang": {"type": "string", "location": "query"}, "max-results": {"format": "uint32", "type": "integer", "location": "query"}, "seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "author": {"type": "string", "location": "query"}, "start-index": {"format": "uint32", "type": "integer", "location": "query"}, "includeVotes": {"type": "boolean", "location": "query"}, "sort": {"type": "string", "location": "query"}, "q": {"type": "string", "location": "query"}, "hasAttachedVideo": {"type": "boolean", "location": "query"}}, "id": "moderator.series.submissions.list", "httpMethod": "GET", "path": "series/{seriesId}/submissions", "response": {"$ref": "SubmissionList"}}}}', true));
$this->series_responses = new SeriesResponsesServiceResource($this, $this->serviceName, 'responses', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"max-results": {"format": "uint32", "type": "integer", "location": "query"}, "sort": {"type": "string", "location": "query"}, "seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "author": {"type": "string", "location": "query"}, "start-index": {"format": "uint32", "type": "integer", "location": "query"}, "q": {"type": "string", "location": "query"}, "hasAttachedVideo": {"type": "boolean", "location": "query"}}, "id": "moderator.series.responses.list", "httpMethod": "GET", "path": "series/{seriesId}/responses", "response": {"$ref": "SeriesList"}}}}', true));
$this->topics = new TopicsServiceResource($this, $this->serviceName, 'topics', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Topic"}, "id": "moderator.topics.insert", "httpMethod": "POST", "path": "series/{seriesId}/topics", "response": {"$ref": "Topic"}}, "list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"max-results": {"format": "uint32", "type": "integer", "location": "query"}, "q": {"type": "string", "location": "query"}, "start-index": {"format": "uint32", "type": "integer", "location": "query"}, "mode": {"type": "string", "location": "query"}, "seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "id": "moderator.topics.list", "httpMethod": "GET", "path": "series/{seriesId}/topics", "response": {"$ref": "TopicList"}}, "update": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "topicId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "Topic"}, "id": "moderator.topics.update", "httpMethod": "PUT", "path": "series/{seriesId}/topics/{topicId}", "response": {"$ref": "Topic"}}, "get": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "topicId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "id": "moderator.topics.get", "httpMethod": "GET", "path": "series/{seriesId}/topics/{topicId}", "response": {"$ref": "Topic"}}}}', true));
$this->topics_submissions = new TopicsSubmissionsServiceResource($this, $this->serviceName, 'submissions', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"max-results": {"format": "uint32", "type": "integer", "location": "query"}, "seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "includeVotes": {"type": "boolean", "location": "query"}, "topicId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "start-index": {"format": "uint32", "type": "integer", "location": "query"}, "author": {"type": "string", "location": "query"}, "sort": {"type": "string", "location": "query"}, "q": {"type": "string", "location": "query"}, "hasAttachedVideo": {"type": "boolean", "location": "query"}}, "id": "moderator.topics.submissions.list", "httpMethod": "GET", "path": "series/{seriesId}/topics/{topicId}/submissions", "response": {"$ref": "SubmissionList"}}}}', true));
$this->global = new ModeratorGlobalServiceResource($this, $this->serviceName, 'global', json_decode('{}', true));
$this->global_series = new ModeratorGlobalSeriesServiceResource($this, $this->serviceName, 'series', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"max-results": {"format": "uint32", "type": "integer", "location": "query"}, "q": {"type": "string", "location": "query"}, "start-index": {"format": "uint32", "type": "integer", "location": "query"}}, "response": {"$ref": "SeriesList"}, "httpMethod": "GET", "path": "search", "id": "moderator.global.series.list"}}}', true));
$this->profiles = new ProfilesServiceResource($this, $this->serviceName, 'profiles', json_decode('{"methods": {"get": {"scopes": ["https://www.googleapis.com/auth/moderator"], "id": "moderator.profiles.get", "httpMethod": "GET", "path": "profiles/@me", "response": {"$ref": "Profile"}}, "update": {"scopes": ["https://www.googleapis.com/auth/moderator"], "request": {"$ref": "Profile"}, "response": {"$ref": "Profile"}, "httpMethod": "PUT", "path": "profiles/@me", "id": "moderator.profiles.update"}, "patch": {"scopes": ["https://www.googleapis.com/auth/moderator"], "request": {"$ref": "Profile"}, "response": {"$ref": "Profile"}, "httpMethod": "PATCH", "path": "profiles/@me", "id": "moderator.profiles.patch"}}}', true));
$this->featured = new FeaturedServiceResource($this, $this->serviceName, 'featured', json_decode('{}', true));
$this->featured_series = new FeaturedSeriesServiceResource($this, $this->serviceName, 'series', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "id": "moderator.featured.series.list", "httpMethod": "GET", "path": "series/featured", "response": {"$ref": "SeriesList"}}}}', true));
$this->myrecent = new MyrecentServiceResource($this, $this->serviceName, 'myrecent', json_decode('{}', true));
$this->myrecent_series = new MyrecentSeriesServiceResource($this, $this->serviceName, 'series', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "id": "moderator.myrecent.series.list", "httpMethod": "GET", "path": "series/@me/recent", "response": {"$ref": "SeriesList"}}}}', true));
$this->my = new MyServiceResource($this, $this->serviceName, 'my', json_decode('{}', true));
$this->my_series = new MySeriesServiceResource($this, $this->serviceName, 'series', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/moderator"], "id": "moderator.my.series.list", "httpMethod": "GET", "path": "series/@me/mine", "response": {"$ref": "SeriesList"}}}}', true));
$this->submissions = new SubmissionsServiceResource($this, $this->serviceName, 'submissions', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "topicId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "unauthToken": {"type": "string", "location": "query"}, "anonymous": {"type": "boolean", "location": "query"}}, "request": {"$ref": "Submission"}, "id": "moderator.submissions.insert", "httpMethod": "POST", "path": "series/{seriesId}/topics/{topicId}/submissions", "response": {"$ref": "Submission"}}, "get": {"scopes": ["https://www.googleapis.com/auth/moderator"], "parameters": {"lang": {"type": "string", "location": "query"}, "seriesId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}, "includeVotes": {"type": "boolean", "location": "query"}, "submissionId": {"format": "uint32", "required": true, "type": "integer", "location": "path"}}, "id": "moderator.submissions.get", "httpMethod": "GET", "path": "series/{seriesId}/submissions/{submissionId}", "response": {"$ref": "Submission"}}}}', true));
}
}
class ModeratorTopicsResourcePartial extends apiModel {
protected $__idType = 'ModeratorTopicsResourcePartialId';
protected $__idDataType = '';
public $id;
public function setId(ModeratorTopicsResourcePartialId $id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class ModeratorTopicsResourcePartialId extends apiModel {
public $seriesId;
public $topicId;
public function setSeriesId($seriesId) {
$this->seriesId = $seriesId;
}
public function getSeriesId() {
return $this->seriesId;
}
public function setTopicId($topicId) {
$this->topicId = $topicId;
}
public function getTopicId() {
return $this->topicId;
}
}
class ModeratorVotesResourcePartial extends apiModel {
public $vote;
public $flag;
public function setVote($vote) {
$this->vote = $vote;
}
public function getVote() {
return $this->vote;
}
public function setFlag($flag) {
$this->flag = $flag;
}
public function getFlag() {
return $this->flag;
}
}
class Profile extends apiModel {
public $kind;
protected $__attributionType = 'ProfileAttribution';
protected $__attributionDataType = '';
public $attribution;
protected $__idType = 'ProfileId';
protected $__idDataType = '';
public $id;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAttribution(ProfileAttribution $attribution) {
$this->attribution = $attribution;
}
public function getAttribution() {
return $this->attribution;
}
public function setId(ProfileId $id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class ProfileAttribution extends apiModel {
protected $__geoType = 'ProfileAttributionGeo';
protected $__geoDataType = '';
public $geo;
public $displayName;
public $location;
public $avatarUrl;
public function setGeo(ProfileAttributionGeo $geo) {
$this->geo = $geo;
}
public function getGeo() {
return $this->geo;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setAvatarUrl($avatarUrl) {
$this->avatarUrl = $avatarUrl;
}
public function getAvatarUrl() {
return $this->avatarUrl;
}
}
class ProfileAttributionGeo extends apiModel {
public $latitude;
public $location;
public $longitude;
public function setLatitude($latitude) {
$this->latitude = $latitude;
}
public function getLatitude() {
return $this->latitude;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setLongitude($longitude) {
$this->longitude = $longitude;
}
public function getLongitude() {
return $this->longitude;
}
}
class ProfileId extends apiModel {
public $user;
public function setUser($user) {
$this->user = $user;
}
public function getUser() {
return $this->user;
}
}
class Series extends apiModel {
public $kind;
public $description;
protected $__rulesType = 'SeriesRules';
protected $__rulesDataType = '';
public $rules;
public $unauthVotingAllowed;
public $videoSubmissionAllowed;
public $name;
public $numTopics;
public $anonymousSubmissionAllowed;
public $unauthSubmissionAllowed;
protected $__idType = 'SeriesId';
protected $__idDataType = '';
public $id;
protected $__countersType = 'SeriesCounters';
protected $__countersDataType = '';
public $counters;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setRules(SeriesRules $rules) {
$this->rules = $rules;
}
public function getRules() {
return $this->rules;
}
public function setUnauthVotingAllowed($unauthVotingAllowed) {
$this->unauthVotingAllowed = $unauthVotingAllowed;
}
public function getUnauthVotingAllowed() {
return $this->unauthVotingAllowed;
}
public function setVideoSubmissionAllowed($videoSubmissionAllowed) {
$this->videoSubmissionAllowed = $videoSubmissionAllowed;
}
public function getVideoSubmissionAllowed() {
return $this->videoSubmissionAllowed;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setNumTopics($numTopics) {
$this->numTopics = $numTopics;
}
public function getNumTopics() {
return $this->numTopics;
}
public function setAnonymousSubmissionAllowed($anonymousSubmissionAllowed) {
$this->anonymousSubmissionAllowed = $anonymousSubmissionAllowed;
}
public function getAnonymousSubmissionAllowed() {
return $this->anonymousSubmissionAllowed;
}
public function setUnauthSubmissionAllowed($unauthSubmissionAllowed) {
$this->unauthSubmissionAllowed = $unauthSubmissionAllowed;
}
public function getUnauthSubmissionAllowed() {
return $this->unauthSubmissionAllowed;
}
public function setId(SeriesId $id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setCounters(SeriesCounters $counters) {
$this->counters = $counters;
}
public function getCounters() {
return $this->counters;
}
}
class SeriesCounters extends apiModel {
public $users;
public $noneVotes;
public $videoSubmissions;
public $minusVotes;
public $anonymousSubmissions;
public $submissions;
public $plusVotes;
public function setUsers($users) {
$this->users = $users;
}
public function getUsers() {
return $this->users;
}
public function setNoneVotes($noneVotes) {
$this->noneVotes = $noneVotes;
}
public function getNoneVotes() {
return $this->noneVotes;
}
public function setVideoSubmissions($videoSubmissions) {
$this->videoSubmissions = $videoSubmissions;
}
public function getVideoSubmissions() {
return $this->videoSubmissions;
}
public function setMinusVotes($minusVotes) {
$this->minusVotes = $minusVotes;
}
public function getMinusVotes() {
return $this->minusVotes;
}
public function setAnonymousSubmissions($anonymousSubmissions) {
$this->anonymousSubmissions = $anonymousSubmissions;
}
public function getAnonymousSubmissions() {
return $this->anonymousSubmissions;
}
public function setSubmissions($submissions) {
$this->submissions = $submissions;
}
public function getSubmissions() {
return $this->submissions;
}
public function setPlusVotes($plusVotes) {
$this->plusVotes = $plusVotes;
}
public function getPlusVotes() {
return $this->plusVotes;
}
}
class SeriesId extends apiModel {
public $seriesId;
public function setSeriesId($seriesId) {
$this->seriesId = $seriesId;
}
public function getSeriesId() {
return $this->seriesId;
}
}
class SeriesList extends apiModel {
protected $__itemsType = 'Series';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Series) */ $items) {
$this->assertIsArray($items, 'Series', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class SeriesRules extends apiModel {
protected $__votesType = 'SeriesRulesVotes';
protected $__votesDataType = '';
public $votes;
protected $__submissionsType = 'SeriesRulesSubmissions';
protected $__submissionsDataType = '';
public $submissions;
public function setVotes(SeriesRulesVotes $votes) {
$this->votes = $votes;
}
public function getVotes() {
return $this->votes;
}
public function setSubmissions(SeriesRulesSubmissions $submissions) {
$this->submissions = $submissions;
}
public function getSubmissions() {
return $this->submissions;
}
}
class SeriesRulesSubmissions extends apiModel {
public $close;
public $open;
public function setClose($close) {
$this->close = $close;
}
public function getClose() {
return $this->close;
}
public function setOpen($open) {
$this->open = $open;
}
public function getOpen() {
return $this->open;
}
}
class SeriesRulesVotes extends apiModel {
public $close;
public $open;
public function setClose($close) {
$this->close = $close;
}
public function getClose() {
return $this->close;
}
public function setOpen($open) {
$this->open = $open;
}
public function getOpen() {
return $this->open;
}
}
class Submission extends apiModel {
public $kind;
protected $__attributionType = 'SubmissionAttribution';
protected $__attributionDataType = '';
public $attribution;
public $created;
public $text;
protected $__topicsType = 'ModeratorTopicsResourcePartial';
protected $__topicsDataType = 'array';
public $topics;
public $author;
protected $__translationsType = 'SubmissionTranslations';
protected $__translationsDataType = 'array';
public $translations;
protected $__parentSubmissionIdType = 'SubmissionParentSubmissionId';
protected $__parentSubmissionIdDataType = '';
public $parentSubmissionId;
protected $__voteType = 'ModeratorVotesResourcePartial';
protected $__voteDataType = '';
public $vote;
public $attachmentUrl;
protected $__geoType = 'SubmissionGeo';
protected $__geoDataType = '';
public $geo;
protected $__idType = 'SubmissionId';
protected $__idDataType = '';
public $id;
protected $__countersType = 'SubmissionCounters';
protected $__countersDataType = '';
public $counters;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAttribution(SubmissionAttribution $attribution) {
$this->attribution = $attribution;
}
public function getAttribution() {
return $this->attribution;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setText($text) {
$this->text = $text;
}
public function getText() {
return $this->text;
}
public function setTopics(/* array(ModeratorTopicsResourcePartial) */ $topics) {
$this->assertIsArray($topics, 'ModeratorTopicsResourcePartial', __METHOD__);
$this->topics = $topics;
}
public function getTopics() {
return $this->topics;
}
public function setAuthor($author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setTranslations(/* array(SubmissionTranslations) */ $translations) {
$this->assertIsArray($translations, 'SubmissionTranslations', __METHOD__);
$this->translations = $translations;
}
public function getTranslations() {
return $this->translations;
}
public function setParentSubmissionId(SubmissionParentSubmissionId $parentSubmissionId) {
$this->parentSubmissionId = $parentSubmissionId;
}
public function getParentSubmissionId() {
return $this->parentSubmissionId;
}
public function setVote(ModeratorVotesResourcePartial $vote) {
$this->vote = $vote;
}
public function getVote() {
return $this->vote;
}
public function setAttachmentUrl($attachmentUrl) {
$this->attachmentUrl = $attachmentUrl;
}
public function getAttachmentUrl() {
return $this->attachmentUrl;
}
public function setGeo(SubmissionGeo $geo) {
$this->geo = $geo;
}
public function getGeo() {
return $this->geo;
}
public function setId(SubmissionId $id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setCounters(SubmissionCounters $counters) {
$this->counters = $counters;
}
public function getCounters() {
return $this->counters;
}
}
class SubmissionAttribution extends apiModel {
public $displayName;
public $location;
public $avatarUrl;
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setAvatarUrl($avatarUrl) {
$this->avatarUrl = $avatarUrl;
}
public function getAvatarUrl() {
return $this->avatarUrl;
}
}
class SubmissionCounters extends apiModel {
public $noneVotes;
public $minusVotes;
public $plusVotes;
public function setNoneVotes($noneVotes) {
$this->noneVotes = $noneVotes;
}
public function getNoneVotes() {
return $this->noneVotes;
}
public function setMinusVotes($minusVotes) {
$this->minusVotes = $minusVotes;
}
public function getMinusVotes() {
return $this->minusVotes;
}
public function setPlusVotes($plusVotes) {
$this->plusVotes = $plusVotes;
}
public function getPlusVotes() {
return $this->plusVotes;
}
}
class SubmissionGeo extends apiModel {
public $latitude;
public $location;
public $longitude;
public function setLatitude($latitude) {
$this->latitude = $latitude;
}
public function getLatitude() {
return $this->latitude;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setLongitude($longitude) {
$this->longitude = $longitude;
}
public function getLongitude() {
return $this->longitude;
}
}
class SubmissionId extends apiModel {
public $seriesId;
public $submissionId;
public function setSeriesId($seriesId) {
$this->seriesId = $seriesId;
}
public function getSeriesId() {
return $this->seriesId;
}
public function setSubmissionId($submissionId) {
$this->submissionId = $submissionId;
}
public function getSubmissionId() {
return $this->submissionId;
}
}
class SubmissionList extends apiModel {
protected $__itemsType = 'Submission';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Submission) */ $items) {
$this->assertIsArray($items, 'Submission', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class SubmissionParentSubmissionId extends apiModel {
public $seriesId;
public $submissionId;
public function setSeriesId($seriesId) {
$this->seriesId = $seriesId;
}
public function getSeriesId() {
return $this->seriesId;
}
public function setSubmissionId($submissionId) {
$this->submissionId = $submissionId;
}
public function getSubmissionId() {
return $this->submissionId;
}
}
class SubmissionTranslations extends apiModel {
public $lang;
public $text;
public function setLang($lang) {
$this->lang = $lang;
}
public function getLang() {
return $this->lang;
}
public function setText($text) {
$this->text = $text;
}
public function getText() {
return $this->text;
}
}
class Tag extends apiModel {
public $text;
public $kind;
protected $__idType = 'TagId';
protected $__idDataType = '';
public $id;
public function setText($text) {
$this->text = $text;
}
public function getText() {
return $this->text;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setId(TagId $id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class TagId extends apiModel {
public $seriesId;
public $tagId;
public $submissionId;
public function setSeriesId($seriesId) {
$this->seriesId = $seriesId;
}
public function getSeriesId() {
return $this->seriesId;
}
public function setTagId($tagId) {
$this->tagId = $tagId;
}
public function getTagId() {
return $this->tagId;
}
public function setSubmissionId($submissionId) {
$this->submissionId = $submissionId;
}
public function getSubmissionId() {
return $this->submissionId;
}
}
class TagList extends apiModel {
protected $__itemsType = 'Tag';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Tag) */ $items) {
$this->assertIsArray($items, 'Tag', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class Topic extends apiModel {
public $kind;
public $description;
protected $__rulesType = 'TopicRules';
protected $__rulesDataType = '';
public $rules;
protected $__featuredSubmissionType = 'Submission';
protected $__featuredSubmissionDataType = '';
public $featuredSubmission;
public $presenter;
protected $__countersType = 'TopicCounters';
protected $__countersDataType = '';
public $counters;
protected $__idType = 'TopicId';
protected $__idDataType = '';
public $id;
public $name;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setRules(TopicRules $rules) {
$this->rules = $rules;
}
public function getRules() {
return $this->rules;
}
public function setFeaturedSubmission(Submission $featuredSubmission) {
$this->featuredSubmission = $featuredSubmission;
}
public function getFeaturedSubmission() {
return $this->featuredSubmission;
}
public function setPresenter($presenter) {
$this->presenter = $presenter;
}
public function getPresenter() {
return $this->presenter;
}
public function setCounters(TopicCounters $counters) {
$this->counters = $counters;
}
public function getCounters() {
return $this->counters;
}
public function setId(TopicId $id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class TopicCounters extends apiModel {
public $users;
public $noneVotes;
public $videoSubmissions;
public $minusVotes;
public $submissions;
public $plusVotes;
public function setUsers($users) {
$this->users = $users;
}
public function getUsers() {
return $this->users;
}
public function setNoneVotes($noneVotes) {
$this->noneVotes = $noneVotes;
}
public function getNoneVotes() {
return $this->noneVotes;
}
public function setVideoSubmissions($videoSubmissions) {
$this->videoSubmissions = $videoSubmissions;
}
public function getVideoSubmissions() {
return $this->videoSubmissions;
}
public function setMinusVotes($minusVotes) {
$this->minusVotes = $minusVotes;
}
public function getMinusVotes() {
return $this->minusVotes;
}
public function setSubmissions($submissions) {
$this->submissions = $submissions;
}
public function getSubmissions() {
return $this->submissions;
}
public function setPlusVotes($plusVotes) {
$this->plusVotes = $plusVotes;
}
public function getPlusVotes() {
return $this->plusVotes;
}
}
class TopicId extends apiModel {
public $seriesId;
public $topicId;
public function setSeriesId($seriesId) {
$this->seriesId = $seriesId;
}
public function getSeriesId() {
return $this->seriesId;
}
public function setTopicId($topicId) {
$this->topicId = $topicId;
}
public function getTopicId() {
return $this->topicId;
}
}
class TopicList extends apiModel {
protected $__itemsType = 'Topic';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Topic) */ $items) {
$this->assertIsArray($items, 'Topic', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class TopicRules extends apiModel {
protected $__votesType = 'TopicRulesVotes';
protected $__votesDataType = '';
public $votes;
protected $__submissionsType = 'TopicRulesSubmissions';
protected $__submissionsDataType = '';
public $submissions;
public function setVotes(TopicRulesVotes $votes) {
$this->votes = $votes;
}
public function getVotes() {
return $this->votes;
}
public function setSubmissions(TopicRulesSubmissions $submissions) {
$this->submissions = $submissions;
}
public function getSubmissions() {
return $this->submissions;
}
}
class TopicRulesSubmissions extends apiModel {
public $close;
public $open;
public function setClose($close) {
$this->close = $close;
}
public function getClose() {
return $this->close;
}
public function setOpen($open) {
$this->open = $open;
}
public function getOpen() {
return $this->open;
}
}
class TopicRulesVotes extends apiModel {
public $close;
public $open;
public function setClose($close) {
$this->close = $close;
}
public function getClose() {
return $this->close;
}
public function setOpen($open) {
$this->open = $open;
}
public function getOpen() {
return $this->open;
}
}
class Vote extends apiModel {
public $vote;
public $flag;
protected $__idType = 'VoteId';
protected $__idDataType = '';
public $id;
public $kind;
public function setVote($vote) {
$this->vote = $vote;
}
public function getVote() {
return $this->vote;
}
public function setFlag($flag) {
$this->flag = $flag;
}
public function getFlag() {
return $this->flag;
}
public function setId(VoteId $id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class VoteId extends apiModel {
public $seriesId;
public $submissionId;
public function setSeriesId($seriesId) {
$this->seriesId = $seriesId;
}
public function getSeriesId() {
return $this->seriesId;
}
public function setSubmissionId($submissionId) {
$this->submissionId = $submissionId;
}
public function getSubmissionId() {
return $this->submissionId;
}
}
class VoteList extends apiModel {
protected $__itemsType = 'Vote';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Vote) */ $items) {
$this->assertIsArray($items, 'Vote', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiModeratorService.php | PHP | asf20 | 70,611 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "userinfo" collection of methods.
* Typical usage is:
* <code>
* $oauth2Service = new apiOauth2Service(...);
* $userinfo = $oauth2Service->userinfo;
* </code>
*/
class UserinfoServiceResource extends apiServiceResource {
/**
* (userinfo.get)
*
* @return Userinfo
*/
public function get($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Userinfo($data);
} else {
return $data;
}
}
}
/**
* The "v2" collection of methods.
* Typical usage is:
* <code>
* $oauth2Service = new apiOauth2Service(...);
* $v2 = $oauth2Service->v2;
* </code>
*/
class UserinfoV2ServiceResource extends apiServiceResource {
}
/**
* The "me" collection of methods.
* Typical usage is:
* <code>
* $oauth2Service = new apiOauth2Service(...);
* $me = $oauth2Service->me;
* </code>
*/
class UserinfoV2MeServiceResource extends apiServiceResource {
/**
* (me.get)
*
* @return Userinfo
*/
public function get($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Userinfo($data);
} else {
return $data;
}
}
}
/**
* The "tokeninfo" collection of methods.
* Typical usage is:
* <code>
* $oauth2Service = new apiOauth2Service(...);
* $tokeninfo = $oauth2Service->tokeninfo;
* </code>
*/
class TokeninfoServiceResource extends apiServiceResource {
/**
* (tokeninfo.tokeninfo)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string access_token
* @opt_param string id_token
* @return Tokeninfo
*/
public function tokeninfo($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('tokeninfo', array($params));
if ($this->useObjects()) {
return new Tokeninfo($data);
} else {
return $data;
}
}
}
/**
* Service definition for Oauth2 (v2).
*
* <p>
* OAuth2 API
* </p>
*
* <p>
* For more information about this service, see the
* <a href="" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiOauth2Service extends apiService {
public $tokeninfo;
public $userinfo;
public $userinfo_v2;
/**
* Constructs the internal representation of the Oauth2 service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/';
$this->version = 'v2';
$this->serviceName = 'oauth2';
$apiClient->addService($this->serviceName, $this->version);
$this->userinfo = new UserinfoServiceResource($this, $this->serviceName, 'userinfo', json_decode('{"methods": {"get": {"path": "oauth2/v2/userinfo", "response": {"$ref": "Userinfo"}, "httpMethod": "GET", "id": "oauth2.userinfo.get"}}}', true));
$this->userinfo_v2 = new UserinfoV2ServiceResource($this, $this->serviceName, 'v2', json_decode('{}', true));
$this->tokeninfo = new TokeninfoServiceResource($this, $this->serviceName, 'tokeninfo', json_decode('{"id": "oauth2.tokeninfo", "path": "oauth2/v2/tokeninfo", "response": {"$ref": "Tokeninfo"}, "parameters": {"access_token": {"type": "string", "location": "query"}, "id_token": {"type": "string", "location": "query"}}, "httpMethod": "GET"}', true));
}
}
class Tokeninfo extends apiModel {
public $issued_to;
public $user_id;
public $expires_in;
public $access_type;
public $audience;
public $scope;
public $email;
public $verified_email;
public function setIssued_to($issued_to) {
$this->issued_to = $issued_to;
}
public function getIssued_to() {
return $this->issued_to;
}
public function setUser_id($user_id) {
$this->user_id = $user_id;
}
public function getUser_id() {
return $this->user_id;
}
public function setExpires_in($expires_in) {
$this->expires_in = $expires_in;
}
public function getExpires_in() {
return $this->expires_in;
}
public function setAccess_type($access_type) {
$this->access_type = $access_type;
}
public function getAccess_type() {
return $this->access_type;
}
public function setAudience($audience) {
$this->audience = $audience;
}
public function getAudience() {
return $this->audience;
}
public function setScope($scope) {
$this->scope = $scope;
}
public function getScope() {
return $this->scope;
}
public function setEmail($email) {
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
public function setVerified_email($verified_email) {
$this->verified_email = $verified_email;
}
public function getVerified_email() {
return $this->verified_email;
}
}
class Userinfo extends apiModel {
public $family_name;
public $name;
public $picture;
public $locale;
public $gender;
public $email;
public $birthday;
public $link;
public $given_name;
public $timezone;
public $id;
public $verified_email;
public function setFamily_name($family_name) {
$this->family_name = $family_name;
}
public function getFamily_name() {
return $this->family_name;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setPicture($picture) {
$this->picture = $picture;
}
public function getPicture() {
return $this->picture;
}
public function setLocale($locale) {
$this->locale = $locale;
}
public function getLocale() {
return $this->locale;
}
public function setGender($gender) {
$this->gender = $gender;
}
public function getGender() {
return $this->gender;
}
public function setEmail($email) {
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
public function setBirthday($birthday) {
$this->birthday = $birthday;
}
public function getBirthday() {
return $this->birthday;
}
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setGiven_name($given_name) {
$this->given_name = $given_name;
}
public function getGiven_name() {
return $this->given_name;
}
public function setTimezone($timezone) {
$this->timezone = $timezone;
}
public function getTimezone() {
return $this->timezone;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setVerified_email($verified_email) {
$this->verified_email = $verified_email;
}
public function getVerified_email() {
return $this->verified_email;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiOauth2Service.php | PHP | asf20 | 7,831 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "activities" collection of methods.
* Typical usage is:
* <code>
* $plusService = new apiPlusService(...);
* $activities = $plusService->activities;
* </code>
*/
class ActivitiesServiceResource extends apiServiceResource {
/**
* Search public activities. (activities.search)
*
* @param string $query Full-text search query string.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string orderBy Specifies how to order search results.
* @opt_param string pageToken The continuation token, used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. This token may be of any length.
* @opt_param string maxResults The maximum number of activities to include in the response, used for paging. For any response, the actual number returned may be less than the specified maxResults.
* @opt_param string language Specify the preferred language to search with. See search language codes for available values.
* @return ActivityFeed
*/
public function search($query, $optParams = array()) {
$params = array('query' => $query);
$params = array_merge($params, $optParams);
$data = $this->__call('search', array($params));
if ($this->useObjects()) {
return new ActivityFeed($data);
} else {
return $data;
}
}
/**
* List all of the activities in the specified collection for a particular user. (activities.list)
*
* @param string $userId The ID of the user to get activities for. The special value "me" can be used to indicate the authenticated user.
* @param string $collection The collection of activities to list.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken The continuation token, used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param string maxResults The maximum number of activities to include in the response, used for paging. For any response, the actual number returned may be less than the specified maxResults.
* @return ActivityFeed
*/
public function listActivities($userId, $collection, $optParams = array()) {
$params = array('userId' => $userId, 'collection' => $collection);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new ActivityFeed($data);
} else {
return $data;
}
}
/**
* Get an activity. (activities.get)
*
* @param string $activityId The ID of the activity to get.
* @return Activity
*/
public function get($activityId, $optParams = array()) {
$params = array('activityId' => $activityId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Activity($data);
} else {
return $data;
}
}
}
/**
* The "comments" collection of methods.
* Typical usage is:
* <code>
* $plusService = new apiPlusService(...);
* $comments = $plusService->comments;
* </code>
*/
class CommentsServiceResource extends apiServiceResource {
/**
* List all of the comments for an activity. (comments.list)
*
* @param string $activityId The ID of the activity to get comments for.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken The continuation token, used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param string maxResults The maximum number of comments to include in the response, used for paging. For any response, the actual number returned may be less than the specified maxResults.
* @return CommentFeed
*/
public function listComments($activityId, $optParams = array()) {
$params = array('activityId' => $activityId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommentFeed($data);
} else {
return $data;
}
}
/**
* Get a comment. (comments.get)
*
* @param string $commentId The ID of the comment to get.
* @return Comment
*/
public function get($commentId, $optParams = array()) {
$params = array('commentId' => $commentId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Comment($data);
} else {
return $data;
}
}
}
/**
* The "people" collection of methods.
* Typical usage is:
* <code>
* $plusService = new apiPlusService(...);
* $people = $plusService->people;
* </code>
*/
class PeopleServiceResource extends apiServiceResource {
/**
* List all of the people in the specified collection for a particular activity.
* (people.listByActivity)
*
* @param string $activityId The ID of the activity to get the list of people for.
* @param string $collection The collection of people to list.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken The continuation token, used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response.
* @opt_param string maxResults The maximum number of people to include in the response, used for paging. For any response, the actual number returned may be less than the specified maxResults.
* @return PeopleFeed
*/
public function listByActivity($activityId, $collection, $optParams = array()) {
$params = array('activityId' => $activityId, 'collection' => $collection);
$params = array_merge($params, $optParams);
$data = $this->__call('listByActivity', array($params));
if ($this->useObjects()) {
return new PeopleFeed($data);
} else {
return $data;
}
}
/**
* Search all public profiles. (people.search)
*
* @param string $query Full-text search query string.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken The continuation token, used to page through large result sets. To get the next page of results, set this parameter to the value of "nextPageToken" from the previous response. This token may be of any length.
* @opt_param string maxResults The maximum number of people to include in the response, used for paging. For any response, the actual number returned may be less than the specified maxResults.
* @opt_param string language Specify the preferred language to search with. See search language codes for available values.
* @return PeopleFeed
*/
public function search($query, $optParams = array()) {
$params = array('query' => $query);
$params = array_merge($params, $optParams);
$data = $this->__call('search', array($params));
if ($this->useObjects()) {
return new PeopleFeed($data);
} else {
return $data;
}
}
/**
* Get a person's profile. (people.get)
*
* @param string $userId The ID of the person to get the profile for. The special value "me" can be used to indicate the authenticated user.
* @return Person
*/
public function get($userId, $optParams = array()) {
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Person($data);
} else {
return $data;
}
}
}
/**
* Service definition for Plus (v1).
*
* <p>
* The Google+ API enables developers to build on top of the Google+ platform.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://developers.google.com/+/api/" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiPlusService extends apiService {
public $activities;
public $comments;
public $people;
/**
* Constructs the internal representation of the Plus service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/plus/v1/';
$this->version = 'v1';
$this->serviceName = 'plus';
$apiClient->addService($this->serviceName, $this->version);
$this->activities = new ActivitiesServiceResource($this, $this->serviceName, 'activities', json_decode('{"methods": {"search": {"scopes": ["https://www.googleapis.com/auth/plus.me"], "parameters": {"orderBy": {"default": "recent", "enum": ["best", "recent"], "location": "query", "type": "string"}, "pageToken": {"type": "string", "location": "query"}, "language": {"default": "", "type": "string", "location": "query"}, "maxResults": {"format": "uint32", "default": "10", "maximum": "20", "minimum": "1", "location": "query", "type": "integer"}, "query": {"required": true, "type": "string", "location": "query"}}, "id": "plus.activities.search", "httpMethod": "GET", "path": "activities", "response": {"$ref": "ActivityFeed"}}, "list": {"scopes": ["https://www.googleapis.com/auth/plus.me"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "alt": {"default": "json", "enum": ["json"], "location": "query", "type": "string"}, "userId": {"required": true, "type": "string", "location": "path"}, "collection": {"required": true, "enum": ["public"], "location": "path", "type": "string"}, "maxResults": {"format": "uint32", "default": "20", "maximum": "100", "minimum": "1", "location": "query", "type": "integer"}}, "id": "plus.activities.list", "httpMethod": "GET", "path": "people/{userId}/activities/{collection}", "response": {"$ref": "ActivityFeed"}}, "get": {"scopes": ["https://www.googleapis.com/auth/plus.me"], "parameters": {"activityId": {"required": true, "type": "string", "location": "path"}, "alt": {"default": "json", "enum": ["json"], "location": "query", "type": "string"}}, "id": "plus.activities.get", "httpMethod": "GET", "path": "activities/{activityId}", "response": {"$ref": "Activity"}}}}', true));
$this->comments = new CommentsServiceResource($this, $this->serviceName, 'comments', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/plus.me"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "activityId": {"required": true, "type": "string", "location": "path"}, "alt": {"default": "json", "enum": ["json"], "location": "query", "type": "string"}, "maxResults": {"format": "uint32", "default": "20", "maximum": "100", "minimum": "0", "location": "query", "type": "integer"}}, "id": "plus.comments.list", "httpMethod": "GET", "path": "activities/{activityId}/comments", "response": {"$ref": "CommentFeed"}}, "get": {"scopes": ["https://www.googleapis.com/auth/plus.me"], "parameters": {"commentId": {"required": true, "type": "string", "location": "path"}}, "id": "plus.comments.get", "httpMethod": "GET", "path": "comments/{commentId}", "response": {"$ref": "Comment"}}}}', true));
$this->people = new PeopleServiceResource($this, $this->serviceName, 'people', json_decode('{"methods": {"listByActivity": {"scopes": ["https://www.googleapis.com/auth/plus.me"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "activityId": {"required": true, "type": "string", "location": "path"}, "collection": {"required": true, "enum": ["plusoners", "resharers"], "location": "path", "type": "string"}, "maxResults": {"format": "uint32", "default": "20", "maximum": "100", "minimum": "1", "location": "query", "type": "integer"}}, "id": "plus.people.listByActivity", "httpMethod": "GET", "path": "activities/{activityId}/people/{collection}", "response": {"$ref": "PeopleFeed"}}, "search": {"scopes": ["https://www.googleapis.com/auth/plus.me"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "language": {"default": "", "type": "string", "location": "query"}, "maxResults": {"format": "uint32", "default": "10", "maximum": "20", "minimum": "1", "location": "query", "type": "integer"}, "query": {"required": true, "type": "string", "location": "query"}}, "id": "plus.people.search", "httpMethod": "GET", "path": "people", "response": {"$ref": "PeopleFeed"}}, "get": {"scopes": ["https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email"], "parameters": {"userId": {"required": true, "type": "string", "location": "path"}}, "id": "plus.people.get", "httpMethod": "GET", "path": "people/{userId}", "response": {"$ref": "Person"}}}}', true));
}
}
class Acl extends apiModel {
protected $__itemsType = 'PlusAclentryResource';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $description;
public function setItems(/* array(PlusAclentryResource) */ $items) {
$this->assertIsArray($items, 'PlusAclentryResource', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
}
class Activity extends apiModel {
public $placeName;
public $kind;
public $updated;
protected $__providerType = 'ActivityProvider';
protected $__providerDataType = '';
public $provider;
public $title;
public $url;
public $geocode;
protected $__objectType = 'ActivityObject';
protected $__objectDataType = '';
public $object;
public $placeId;
protected $__actorType = 'ActivityActor';
protected $__actorDataType = '';
public $actor;
public $id;
protected $__accessType = 'Acl';
protected $__accessDataType = '';
public $access;
public $verb;
public $etag;
public $radius;
public $address;
public $crosspostSource;
public $placeholder;
public $annotation;
public $published;
public function setPlaceName($placeName) {
$this->placeName = $placeName;
}
public function getPlaceName() {
return $this->placeName;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setProvider(ActivityProvider $provider) {
$this->provider = $provider;
}
public function getProvider() {
return $this->provider;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setGeocode($geocode) {
$this->geocode = $geocode;
}
public function getGeocode() {
return $this->geocode;
}
public function setObject(ActivityObject $object) {
$this->object = $object;
}
public function getObject() {
return $this->object;
}
public function setPlaceId($placeId) {
$this->placeId = $placeId;
}
public function getPlaceId() {
return $this->placeId;
}
public function setActor(ActivityActor $actor) {
$this->actor = $actor;
}
public function getActor() {
return $this->actor;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setAccess(Acl $access) {
$this->access = $access;
}
public function getAccess() {
return $this->access;
}
public function setVerb($verb) {
$this->verb = $verb;
}
public function getVerb() {
return $this->verb;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setRadius($radius) {
$this->radius = $radius;
}
public function getRadius() {
return $this->radius;
}
public function setAddress($address) {
$this->address = $address;
}
public function getAddress() {
return $this->address;
}
public function setCrosspostSource($crosspostSource) {
$this->crosspostSource = $crosspostSource;
}
public function getCrosspostSource() {
return $this->crosspostSource;
}
public function setPlaceholder($placeholder) {
$this->placeholder = $placeholder;
}
public function getPlaceholder() {
return $this->placeholder;
}
public function setAnnotation($annotation) {
$this->annotation = $annotation;
}
public function getAnnotation() {
return $this->annotation;
}
public function setPublished($published) {
$this->published = $published;
}
public function getPublished() {
return $this->published;
}
}
class ActivityActor extends apiModel {
public $displayName;
public $url;
protected $__imageType = 'ActivityActorImage';
protected $__imageDataType = '';
public $image;
public $familyName;
public $givenName;
public $id;
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setImage(ActivityActorImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setFamilyName($familyName) {
$this->familyName = $familyName;
}
public function getFamilyName() {
return $this->familyName;
}
public function setGivenName($givenName) {
$this->givenName = $givenName;
}
public function getGivenName() {
return $this->givenName;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class ActivityActorImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class ActivityFeed extends apiModel {
public $nextPageToken;
public $kind;
public $title;
protected $__itemsType = 'Activity';
protected $__itemsDataType = 'array';
public $items;
public $updated;
public $nextLink;
public $etag;
public $id;
public $selfLink;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setItems(/* array(Activity) */ $items) {
$this->assertIsArray($items, 'Activity', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class ActivityObject extends apiModel {
protected $__resharersType = 'ActivityObjectResharers';
protected $__resharersDataType = '';
public $resharers;
protected $__attachmentsType = 'ActivityObjectAttachments';
protected $__attachmentsDataType = 'array';
public $attachments;
public $originalContent;
protected $__plusonersType = 'ActivityObjectPlusoners';
protected $__plusonersDataType = '';
public $plusoners;
protected $__actorType = 'ActivityObjectActor';
protected $__actorDataType = '';
public $actor;
public $content;
public $url;
protected $__repliesType = 'ActivityObjectReplies';
protected $__repliesDataType = '';
public $replies;
public $id;
public $objectType;
public function setResharers(ActivityObjectResharers $resharers) {
$this->resharers = $resharers;
}
public function getResharers() {
return $this->resharers;
}
public function setAttachments(/* array(ActivityObjectAttachments) */ $attachments) {
$this->assertIsArray($attachments, 'ActivityObjectAttachments', __METHOD__);
$this->attachments = $attachments;
}
public function getAttachments() {
return $this->attachments;
}
public function setOriginalContent($originalContent) {
$this->originalContent = $originalContent;
}
public function getOriginalContent() {
return $this->originalContent;
}
public function setPlusoners(ActivityObjectPlusoners $plusoners) {
$this->plusoners = $plusoners;
}
public function getPlusoners() {
return $this->plusoners;
}
public function setActor(ActivityObjectActor $actor) {
$this->actor = $actor;
}
public function getActor() {
return $this->actor;
}
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setReplies(ActivityObjectReplies $replies) {
$this->replies = $replies;
}
public function getReplies() {
return $this->replies;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setObjectType($objectType) {
$this->objectType = $objectType;
}
public function getObjectType() {
return $this->objectType;
}
}
class ActivityObjectActor extends apiModel {
public $url;
protected $__imageType = 'ActivityObjectActorImage';
protected $__imageDataType = '';
public $image;
public $displayName;
public $id;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setImage(ActivityObjectActorImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class ActivityObjectActorImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class ActivityObjectAttachments extends apiModel {
public $displayName;
protected $__fullImageType = 'ActivityObjectAttachmentsFullImage';
protected $__fullImageDataType = '';
public $fullImage;
public $url;
protected $__imageType = 'ActivityObjectAttachmentsImage';
protected $__imageDataType = '';
public $image;
public $content;
protected $__embedType = 'ActivityObjectAttachmentsEmbed';
protected $__embedDataType = '';
public $embed;
public $id;
public $objectType;
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setFullImage(ActivityObjectAttachmentsFullImage $fullImage) {
$this->fullImage = $fullImage;
}
public function getFullImage() {
return $this->fullImage;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setImage(ActivityObjectAttachmentsImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setEmbed(ActivityObjectAttachmentsEmbed $embed) {
$this->embed = $embed;
}
public function getEmbed() {
return $this->embed;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setObjectType($objectType) {
$this->objectType = $objectType;
}
public function getObjectType() {
return $this->objectType;
}
}
class ActivityObjectAttachmentsEmbed extends apiModel {
public $url;
public $type;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class ActivityObjectAttachmentsFullImage extends apiModel {
public $url;
public $width;
public $type;
public $height;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setWidth($width) {
$this->width = $width;
}
public function getWidth() {
return $this->width;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setHeight($height) {
$this->height = $height;
}
public function getHeight() {
return $this->height;
}
}
class ActivityObjectAttachmentsImage extends apiModel {
public $url;
public $width;
public $type;
public $height;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setWidth($width) {
$this->width = $width;
}
public function getWidth() {
return $this->width;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setHeight($height) {
$this->height = $height;
}
public function getHeight() {
return $this->height;
}
}
class ActivityObjectPlusoners extends apiModel {
public $totalItems;
public $selfLink;
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class ActivityObjectReplies extends apiModel {
public $totalItems;
public $selfLink;
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class ActivityObjectResharers extends apiModel {
public $totalItems;
public $selfLink;
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class ActivityProvider extends apiModel {
public $title;
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
}
class Comment extends apiModel {
protected $__inReplyToType = 'CommentInReplyTo';
protected $__inReplyToDataType = 'array';
public $inReplyTo;
public $kind;
protected $__objectType = 'CommentObject';
protected $__objectDataType = '';
public $object;
public $updated;
protected $__actorType = 'CommentActor';
protected $__actorDataType = '';
public $actor;
public $verb;
public $etag;
public $published;
public $id;
public $selfLink;
public function setInReplyTo(/* array(CommentInReplyTo) */ $inReplyTo) {
$this->assertIsArray($inReplyTo, 'CommentInReplyTo', __METHOD__);
$this->inReplyTo = $inReplyTo;
}
public function getInReplyTo() {
return $this->inReplyTo;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setObject(CommentObject $object) {
$this->object = $object;
}
public function getObject() {
return $this->object;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setActor(CommentActor $actor) {
$this->actor = $actor;
}
public function getActor() {
return $this->actor;
}
public function setVerb($verb) {
$this->verb = $verb;
}
public function getVerb() {
return $this->verb;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setPublished($published) {
$this->published = $published;
}
public function getPublished() {
return $this->published;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class CommentActor extends apiModel {
public $url;
protected $__imageType = 'CommentActorImage';
protected $__imageDataType = '';
public $image;
public $displayName;
public $id;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setImage(CommentActorImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class CommentActorImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class CommentFeed extends apiModel {
public $nextPageToken;
public $kind;
public $title;
protected $__itemsType = 'Comment';
protected $__itemsDataType = 'array';
public $items;
public $updated;
public $nextLink;
public $etag;
public $id;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setItems(/* array(Comment) */ $items) {
$this->assertIsArray($items, 'Comment', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setNextLink($nextLink) {
$this->nextLink = $nextLink;
}
public function getNextLink() {
return $this->nextLink;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class CommentInReplyTo extends apiModel {
public $url;
public $id;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class CommentObject extends apiModel {
public $content;
public $objectType;
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setObjectType($objectType) {
$this->objectType = $objectType;
}
public function getObjectType() {
return $this->objectType;
}
}
class PeopleFeed extends apiModel {
public $nextPageToken;
public $kind;
public $title;
protected $__itemsType = 'Person';
protected $__itemsDataType = 'array';
public $items;
public $etag;
public $selfLink;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setItems(/* array(Person) */ $items) {
$this->assertIsArray($items, 'Person', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class Person extends apiModel {
public $relationshipStatus;
protected $__organizationsType = 'PersonOrganizations';
protected $__organizationsDataType = 'array';
public $organizations;
public $kind;
public $displayName;
protected $__nameType = 'PersonName';
protected $__nameDataType = '';
public $name;
public $url;
public $gender;
public $aboutMe;
public $tagline;
protected $__urlsType = 'PersonUrls';
protected $__urlsDataType = 'array';
public $urls;
protected $__placesLivedType = 'PersonPlacesLived';
protected $__placesLivedDataType = 'array';
public $placesLived;
protected $__emailsType = 'PersonEmails';
protected $__emailsDataType = 'array';
public $emails;
public $nickname;
public $birthday;
public $etag;
protected $__imageType = 'PersonImage';
protected $__imageDataType = '';
public $image;
public $hasApp;
public $id;
public $languagesSpoken;
public $currentLocation;
public $objectType;
public function setRelationshipStatus($relationshipStatus) {
$this->relationshipStatus = $relationshipStatus;
}
public function getRelationshipStatus() {
return $this->relationshipStatus;
}
public function setOrganizations(/* array(PersonOrganizations) */ $organizations) {
$this->assertIsArray($organizations, 'PersonOrganizations', __METHOD__);
$this->organizations = $organizations;
}
public function getOrganizations() {
return $this->organizations;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setName(PersonName $name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setGender($gender) {
$this->gender = $gender;
}
public function getGender() {
return $this->gender;
}
public function setAboutMe($aboutMe) {
$this->aboutMe = $aboutMe;
}
public function getAboutMe() {
return $this->aboutMe;
}
public function setTagline($tagline) {
$this->tagline = $tagline;
}
public function getTagline() {
return $this->tagline;
}
public function setUrls(/* array(PersonUrls) */ $urls) {
$this->assertIsArray($urls, 'PersonUrls', __METHOD__);
$this->urls = $urls;
}
public function getUrls() {
return $this->urls;
}
public function setPlacesLived(/* array(PersonPlacesLived) */ $placesLived) {
$this->assertIsArray($placesLived, 'PersonPlacesLived', __METHOD__);
$this->placesLived = $placesLived;
}
public function getPlacesLived() {
return $this->placesLived;
}
public function setEmails(/* array(PersonEmails) */ $emails) {
$this->assertIsArray($emails, 'PersonEmails', __METHOD__);
$this->emails = $emails;
}
public function getEmails() {
return $this->emails;
}
public function setNickname($nickname) {
$this->nickname = $nickname;
}
public function getNickname() {
return $this->nickname;
}
public function setBirthday($birthday) {
$this->birthday = $birthday;
}
public function getBirthday() {
return $this->birthday;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setImage(PersonImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setHasApp($hasApp) {
$this->hasApp = $hasApp;
}
public function getHasApp() {
return $this->hasApp;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setLanguagesSpoken(/* array(string) */ $languagesSpoken) {
$this->assertIsArray($languagesSpoken, 'string', __METHOD__);
$this->languagesSpoken = $languagesSpoken;
}
public function getLanguagesSpoken() {
return $this->languagesSpoken;
}
public function setCurrentLocation($currentLocation) {
$this->currentLocation = $currentLocation;
}
public function getCurrentLocation() {
return $this->currentLocation;
}
public function setObjectType($objectType) {
$this->objectType = $objectType;
}
public function getObjectType() {
return $this->objectType;
}
}
class PersonEmails extends apiModel {
public $type;
public $primary;
public $value;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setPrimary($primary) {
$this->primary = $primary;
}
public function getPrimary() {
return $this->primary;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class PersonImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class PersonName extends apiModel {
public $honorificPrefix;
public $middleName;
public $familyName;
public $formatted;
public $givenName;
public $honorificSuffix;
public function setHonorificPrefix($honorificPrefix) {
$this->honorificPrefix = $honorificPrefix;
}
public function getHonorificPrefix() {
return $this->honorificPrefix;
}
public function setMiddleName($middleName) {
$this->middleName = $middleName;
}
public function getMiddleName() {
return $this->middleName;
}
public function setFamilyName($familyName) {
$this->familyName = $familyName;
}
public function getFamilyName() {
return $this->familyName;
}
public function setFormatted($formatted) {
$this->formatted = $formatted;
}
public function getFormatted() {
return $this->formatted;
}
public function setGivenName($givenName) {
$this->givenName = $givenName;
}
public function getGivenName() {
return $this->givenName;
}
public function setHonorificSuffix($honorificSuffix) {
$this->honorificSuffix = $honorificSuffix;
}
public function getHonorificSuffix() {
return $this->honorificSuffix;
}
}
class PersonOrganizations extends apiModel {
public $startDate;
public $endDate;
public $description;
public $title;
public $primary;
public $location;
public $department;
public $type;
public $name;
public function setStartDate($startDate) {
$this->startDate = $startDate;
}
public function getStartDate() {
return $this->startDate;
}
public function setEndDate($endDate) {
$this->endDate = $endDate;
}
public function getEndDate() {
return $this->endDate;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setPrimary($primary) {
$this->primary = $primary;
}
public function getPrimary() {
return $this->primary;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setDepartment($department) {
$this->department = $department;
}
public function getDepartment() {
return $this->department;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class PersonPlacesLived extends apiModel {
public $primary;
public $value;
public function setPrimary($primary) {
$this->primary = $primary;
}
public function getPrimary() {
return $this->primary;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class PersonUrls extends apiModel {
public $type;
public $primary;
public $value;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setPrimary($primary) {
$this->primary = $primary;
}
public function getPrimary() {
return $this->primary;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class PlusAclentryResource extends apiModel {
public $type;
public $id;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiPlusService.php | PHP | asf20 | 44,101 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "cse" collection of methods.
* Typical usage is:
* <code>
* $customsearchService = new apiCustomsearchService(...);
* $cse = $customsearchService->cse;
* </code>
*/
class CseServiceResource extends apiServiceResource {
/**
* Returns metadata about the search performed, metadata about the custom search engine used for the
* search, and the search results. (cse.list)
*
* @param string $q Query
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string sort The sort expression to apply to the results
* @opt_param string num Number of search results to return
* @opt_param string googlehost The local Google domain to use to perform the search.
* @opt_param string safe Search safety level
* @opt_param string filter Controls turning on or off the duplicate content filter.
* @opt_param string start The index of the first result to return
* @opt_param string cx The custom search engine ID to scope this search query
* @opt_param string lr The language restriction for the search results
* @opt_param string cr Country restrict(s).
* @opt_param string gl Geolocation of end user.
* @opt_param string cref The URL of a linked custom search engine
* @return Search
*/
public function listCse($q, $optParams = array()) {
$params = array('q' => $q);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Search($data);
} else {
return $data;
}
}
}
/**
* Service definition for Customsearch (v1).
*
* <p>
* Lets you search over a website or collection of websites
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/customsearch/v1/using_rest.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiCustomsearchService extends apiService {
public $cse;
/**
* Constructs the internal representation of the Customsearch service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/customsearch/';
$this->version = 'v1';
$this->serviceName = 'customsearch';
$apiClient->addService($this->serviceName, $this->version);
$this->cse = new CseServiceResource($this, $this->serviceName, 'cse', json_decode('{"methods": {"list": {"parameters": {"sort": {"type": "string", "location": "query"}, "filter": {"enum": ["0", "1"], "type": "string", "location": "query"}, "cx": {"type": "string", "location": "query"}, "googlehost": {"type": "string", "location": "query"}, "safe": {"default": "off", "enum": ["high", "medium", "off"], "location": "query", "type": "string"}, "q": {"required": true, "type": "string", "location": "query"}, "start": {"type": "string", "location": "query"}, "num": {"default": "10", "type": "string", "location": "query"}, "lr": {"enum": ["lang_ar", "lang_bg", "lang_ca", "lang_cs", "lang_da", "lang_de", "lang_el", "lang_en", "lang_es", "lang_et", "lang_fi", "lang_fr", "lang_hr", "lang_hu", "lang_id", "lang_is", "lang_it", "lang_iw", "lang_ja", "lang_ko", "lang_lt", "lang_lv", "lang_nl", "lang_no", "lang_pl", "lang_pt", "lang_ro", "lang_ru", "lang_sk", "lang_sl", "lang_sr", "lang_sv", "lang_tr", "lang_zh-CN", "lang_zh-TW"], "type": "string", "location": "query"}, "cr": {"type": "string", "location": "query"}, "gl": {"type": "string", "location": "query"}, "cref": {"type": "string", "location": "query"}}, "id": "search.cse.list", "httpMethod": "GET", "path": "v1", "response": {"$ref": "Search"}}}}', true));
}
}
class Context extends apiModel {
protected $__facetsType = 'ContextFacets';
protected $__facetsDataType = 'array';
public $facets;
public $title;
public function setFacets(/* array(ContextFacets) */ $facets) {
$this->assertIsArray($facets, 'ContextFacets', __METHOD__);
$this->facets = $facets;
}
public function getFacets() {
return $this->facets;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
}
class ContextFacets extends apiModel {
public $anchor;
public $label;
public function setAnchor($anchor) {
$this->anchor = $anchor;
}
public function getAnchor() {
return $this->anchor;
}
public function setLabel($label) {
$this->label = $label;
}
public function getLabel() {
return $this->label;
}
}
class Promotion extends apiModel {
public $link;
public $displayLink;
protected $__imageType = 'PromotionImage';
protected $__imageDataType = '';
public $image;
protected $__bodyLinesType = 'PromotionBodyLines';
protected $__bodyLinesDataType = 'array';
public $bodyLines;
public $title;
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setDisplayLink($displayLink) {
$this->displayLink = $displayLink;
}
public function getDisplayLink() {
return $this->displayLink;
}
public function setImage(PromotionImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setBodyLines(/* array(PromotionBodyLines) */ $bodyLines) {
$this->assertIsArray($bodyLines, 'PromotionBodyLines', __METHOD__);
$this->bodyLines = $bodyLines;
}
public function getBodyLines() {
return $this->bodyLines;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
}
class PromotionBodyLines extends apiModel {
public $url;
public $link;
public $title;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
}
class PromotionImage extends apiModel {
public $source;
public $width;
public $height;
public function setSource($source) {
$this->source = $source;
}
public function getSource() {
return $this->source;
}
public function setWidth($width) {
$this->width = $width;
}
public function getWidth() {
return $this->width;
}
public function setHeight($height) {
$this->height = $height;
}
public function getHeight() {
return $this->height;
}
}
class Query extends apiModel {
public $count;
public $sort;
public $outputEncoding;
public $language;
public $title;
public $googleHost;
public $safe;
public $searchTerms;
public $filter;
public $startIndex;
public $cx;
public $startPage;
public $inputEncoding;
public $cr;
public $gl;
public $totalResults;
public $cref;
public function setCount($count) {
$this->count = $count;
}
public function getCount() {
return $this->count;
}
public function setSort($sort) {
$this->sort = $sort;
}
public function getSort() {
return $this->sort;
}
public function setOutputEncoding($outputEncoding) {
$this->outputEncoding = $outputEncoding;
}
public function getOutputEncoding() {
return $this->outputEncoding;
}
public function setLanguage($language) {
$this->language = $language;
}
public function getLanguage() {
return $this->language;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setGoogleHost($googleHost) {
$this->googleHost = $googleHost;
}
public function getGoogleHost() {
return $this->googleHost;
}
public function setSafe($safe) {
$this->safe = $safe;
}
public function getSafe() {
return $this->safe;
}
public function setSearchTerms($searchTerms) {
$this->searchTerms = $searchTerms;
}
public function getSearchTerms() {
return $this->searchTerms;
}
public function setFilter($filter) {
$this->filter = $filter;
}
public function getFilter() {
return $this->filter;
}
public function setStartIndex($startIndex) {
$this->startIndex = $startIndex;
}
public function getStartIndex() {
return $this->startIndex;
}
public function setCx($cx) {
$this->cx = $cx;
}
public function getCx() {
return $this->cx;
}
public function setStartPage($startPage) {
$this->startPage = $startPage;
}
public function getStartPage() {
return $this->startPage;
}
public function setInputEncoding($inputEncoding) {
$this->inputEncoding = $inputEncoding;
}
public function getInputEncoding() {
return $this->inputEncoding;
}
public function setCr($cr) {
$this->cr = $cr;
}
public function getCr() {
return $this->cr;
}
public function setGl($gl) {
$this->gl = $gl;
}
public function getGl() {
return $this->gl;
}
public function setTotalResults($totalResults) {
$this->totalResults = $totalResults;
}
public function getTotalResults() {
return $this->totalResults;
}
public function setCref($cref) {
$this->cref = $cref;
}
public function getCref() {
return $this->cref;
}
}
class Result extends apiModel {
public $kind;
public $title;
public $displayLink;
public $cacheId;
public $pagemap;
public $snippet;
public $htmlSnippet;
public $link;
public $htmlTitle;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setDisplayLink($displayLink) {
$this->displayLink = $displayLink;
}
public function getDisplayLink() {
return $this->displayLink;
}
public function setCacheId($cacheId) {
$this->cacheId = $cacheId;
}
public function getCacheId() {
return $this->cacheId;
}
public function setPagemap($pagemap) {
$this->pagemap = $pagemap;
}
public function getPagemap() {
return $this->pagemap;
}
public function setSnippet($snippet) {
$this->snippet = $snippet;
}
public function getSnippet() {
return $this->snippet;
}
public function setHtmlSnippet($htmlSnippet) {
$this->htmlSnippet = $htmlSnippet;
}
public function getHtmlSnippet() {
return $this->htmlSnippet;
}
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setHtmlTitle($htmlTitle) {
$this->htmlTitle = $htmlTitle;
}
public function getHtmlTitle() {
return $this->htmlTitle;
}
}
class Search extends apiModel {
protected $__promotionsType = 'Promotion';
protected $__promotionsDataType = 'array';
public $promotions;
public $kind;
protected $__urlType = 'SearchUrl';
protected $__urlDataType = '';
public $url;
protected $__itemsType = 'Result';
protected $__itemsDataType = 'array';
public $items;
protected $__contextType = 'Context';
protected $__contextDataType = '';
public $context;
protected $__queriesType = 'Query';
protected $__queriesDataType = 'map';
public $queries;
public function setPromotions(/* array(Promotion) */ $promotions) {
$this->assertIsArray($promotions, 'Promotion', __METHOD__);
$this->promotions = $promotions;
}
public function getPromotions() {
return $this->promotions;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setUrl(SearchUrl $url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setItems(/* array(Result) */ $items) {
$this->assertIsArray($items, 'Result', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setContext(Context $context) {
$this->context = $context;
}
public function getContext() {
return $this->context;
}
public function setQueries(Query $queries) {
$this->queries = $queries;
}
public function getQueries() {
return $this->queries;
}
}
class SearchUrl extends apiModel {
public $type;
public $template;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setTemplate($template) {
$this->template = $template;
}
public function getTemplate() {
return $this->template;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiCustomsearchService.php | PHP | asf20 | 13,548 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "trainedmodels" collection of methods.
* Typical usage is:
* <code>
* $predictionService = new apiPredictionService(...);
* $trainedmodels = $predictionService->trainedmodels;
* </code>
*/
class TrainedmodelsServiceResource extends apiServiceResource {
/**
* Submit model id and request a prediction (trainedmodels.predict)
*
* @param string $id The unique name for the predictive model.
* @param Input $postBody
* @return Output
*/
public function predict($id, Input $postBody, $optParams = array()) {
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('predict', array($params));
if ($this->useObjects()) {
return new Output($data);
} else {
return $data;
}
}
/**
* Begin training your model. (trainedmodels.insert)
*
* @param Training $postBody
* @return Training
*/
public function insert(Training $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Training($data);
} else {
return $data;
}
}
/**
* Check training status of your model. (trainedmodels.get)
*
* @param string $id The unique name for the predictive model.
* @return Training
*/
public function get($id, $optParams = array()) {
$params = array('id' => $id);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Training($data);
} else {
return $data;
}
}
/**
* Add new data to a trained model. (trainedmodels.update)
*
* @param string $id The unique name for the predictive model.
* @param Update $postBody
* @return Training
*/
public function update($id, Update $postBody, $optParams = array()) {
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Training($data);
} else {
return $data;
}
}
/**
* Delete a trained model. (trainedmodels.delete)
*
* @param string $id The unique name for the predictive model.
*/
public function delete($id, $optParams = array()) {
$params = array('id' => $id);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "hostedmodels" collection of methods.
* Typical usage is:
* <code>
* $predictionService = new apiPredictionService(...);
* $hostedmodels = $predictionService->hostedmodels;
* </code>
*/
class HostedmodelsServiceResource extends apiServiceResource {
/**
* Submit input and request an output against a hosted model. (hostedmodels.predict)
*
* @param string $hostedModelName The name of a hosted model.
* @param Input $postBody
* @return Output
*/
public function predict($hostedModelName, Input $postBody, $optParams = array()) {
$params = array('hostedModelName' => $hostedModelName, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('predict', array($params));
if ($this->useObjects()) {
return new Output($data);
} else {
return $data;
}
}
}
/**
* Service definition for Prediction (v1.4).
*
* <p>
* Lets you access a cloud hosted machine learning service that makes it easy to build smart apps
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/predict/docs/developer-guide.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiPredictionService extends apiService {
public $trainedmodels;
public $hostedmodels;
/**
* Constructs the internal representation of the Prediction service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/prediction/v1.4/';
$this->version = 'v1.4';
$this->serviceName = 'prediction';
$apiClient->addService($this->serviceName, $this->version);
$this->trainedmodels = new TrainedmodelsServiceResource($this, $this->serviceName, 'trainedmodels', json_decode('{"methods": {"predict": {"scopes": ["https://www.googleapis.com/auth/prediction"], "parameters": {"id": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Input"}, "id": "prediction.trainedmodels.predict", "httpMethod": "POST", "path": "trainedmodels/{id}/predict", "response": {"$ref": "Output"}}, "insert": {"scopes": ["https://www.googleapis.com/auth/prediction"], "request": {"$ref": "Training"}, "response": {"$ref": "Training"}, "httpMethod": "POST", "path": "trainedmodels", "id": "prediction.trainedmodels.insert"}, "delete": {"scopes": ["https://www.googleapis.com/auth/prediction"], "parameters": {"id": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "trainedmodels/{id}", "id": "prediction.trainedmodels.delete"}, "update": {"scopes": ["https://www.googleapis.com/auth/prediction"], "parameters": {"id": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Update"}, "id": "prediction.trainedmodels.update", "httpMethod": "PUT", "path": "trainedmodels/{id}", "response": {"$ref": "Training"}}, "get": {"scopes": ["https://www.googleapis.com/auth/prediction"], "parameters": {"id": {"required": true, "type": "string", "location": "path"}}, "id": "prediction.trainedmodels.get", "httpMethod": "GET", "path": "trainedmodels/{id}", "response": {"$ref": "Training"}}}}', true));
$this->hostedmodels = new HostedmodelsServiceResource($this, $this->serviceName, 'hostedmodels', json_decode('{"methods": {"predict": {"scopes": ["https://www.googleapis.com/auth/prediction"], "parameters": {"hostedModelName": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Input"}, "id": "prediction.hostedmodels.predict", "httpMethod": "POST", "path": "hostedmodels/{hostedModelName}/predict", "response": {"$ref": "Output"}}}}', true));
}
}
class Input extends apiModel {
protected $__inputType = 'InputInput';
protected $__inputDataType = '';
public $input;
public function setInput(InputInput $input) {
$this->input = $input;
}
public function getInput() {
return $this->input;
}
}
class InputInput extends apiModel {
public $csvInstance;
public function setCsvInstance(/* array(object) */ $csvInstance) {
$this->assertIsArray($csvInstance, 'object', __METHOD__);
$this->csvInstance = $csvInstance;
}
public function getCsvInstance() {
return $this->csvInstance;
}
}
class Output extends apiModel {
public $kind;
public $outputLabel;
public $id;
protected $__outputMultiType = 'OutputOutputMulti';
protected $__outputMultiDataType = 'array';
public $outputMulti;
public $outputValue;
public $selfLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setOutputLabel($outputLabel) {
$this->outputLabel = $outputLabel;
}
public function getOutputLabel() {
return $this->outputLabel;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setOutputMulti(/* array(OutputOutputMulti) */ $outputMulti) {
$this->assertIsArray($outputMulti, 'OutputOutputMulti', __METHOD__);
$this->outputMulti = $outputMulti;
}
public function getOutputMulti() {
return $this->outputMulti;
}
public function setOutputValue($outputValue) {
$this->outputValue = $outputValue;
}
public function getOutputValue() {
return $this->outputValue;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class OutputOutputMulti extends apiModel {
public $score;
public $label;
public function setScore($score) {
$this->score = $score;
}
public function getScore() {
return $this->score;
}
public function setLabel($label) {
$this->label = $label;
}
public function getLabel() {
return $this->label;
}
}
class Training extends apiModel {
public $kind;
public $storageDataLocation;
public $storagePMMLModelLocation;
protected $__dataAnalysisType = 'TrainingDataAnalysis';
protected $__dataAnalysisDataType = '';
public $dataAnalysis;
public $trainingStatus;
protected $__modelInfoType = 'TrainingModelInfo';
protected $__modelInfoDataType = '';
public $modelInfo;
public $storagePMMLLocation;
public $id;
public $selfLink;
public $utility;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setStorageDataLocation($storageDataLocation) {
$this->storageDataLocation = $storageDataLocation;
}
public function getStorageDataLocation() {
return $this->storageDataLocation;
}
public function setStoragePMMLModelLocation($storagePMMLModelLocation) {
$this->storagePMMLModelLocation = $storagePMMLModelLocation;
}
public function getStoragePMMLModelLocation() {
return $this->storagePMMLModelLocation;
}
public function setDataAnalysis(TrainingDataAnalysis $dataAnalysis) {
$this->dataAnalysis = $dataAnalysis;
}
public function getDataAnalysis() {
return $this->dataAnalysis;
}
public function setTrainingStatus($trainingStatus) {
$this->trainingStatus = $trainingStatus;
}
public function getTrainingStatus() {
return $this->trainingStatus;
}
public function setModelInfo(TrainingModelInfo $modelInfo) {
$this->modelInfo = $modelInfo;
}
public function getModelInfo() {
return $this->modelInfo;
}
public function setStoragePMMLLocation($storagePMMLLocation) {
$this->storagePMMLLocation = $storagePMMLLocation;
}
public function getStoragePMMLLocation() {
return $this->storagePMMLLocation;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setUtility(/* array(double) */ $utility) {
$this->assertIsArray($utility, 'double', __METHOD__);
$this->utility = $utility;
}
public function getUtility() {
return $this->utility;
}
}
class TrainingDataAnalysis extends apiModel {
public $warnings;
public function setWarnings(/* array(string) */ $warnings) {
$this->assertIsArray($warnings, 'string', __METHOD__);
$this->warnings = $warnings;
}
public function getWarnings() {
return $this->warnings;
}
}
class TrainingModelInfo extends apiModel {
public $confusionMatrixRowTotals;
public $numberLabels;
public $confusionMatrix;
public $meanSquaredError;
public $modelType;
public $numberInstances;
public $classWeightedAccuracy;
public $classificationAccuracy;
public function setConfusionMatrixRowTotals($confusionMatrixRowTotals) {
$this->confusionMatrixRowTotals = $confusionMatrixRowTotals;
}
public function getConfusionMatrixRowTotals() {
return $this->confusionMatrixRowTotals;
}
public function setNumberLabels($numberLabels) {
$this->numberLabels = $numberLabels;
}
public function getNumberLabels() {
return $this->numberLabels;
}
public function setConfusionMatrix($confusionMatrix) {
$this->confusionMatrix = $confusionMatrix;
}
public function getConfusionMatrix() {
return $this->confusionMatrix;
}
public function setMeanSquaredError($meanSquaredError) {
$this->meanSquaredError = $meanSquaredError;
}
public function getMeanSquaredError() {
return $this->meanSquaredError;
}
public function setModelType($modelType) {
$this->modelType = $modelType;
}
public function getModelType() {
return $this->modelType;
}
public function setNumberInstances($numberInstances) {
$this->numberInstances = $numberInstances;
}
public function getNumberInstances() {
return $this->numberInstances;
}
public function setClassWeightedAccuracy($classWeightedAccuracy) {
$this->classWeightedAccuracy = $classWeightedAccuracy;
}
public function getClassWeightedAccuracy() {
return $this->classWeightedAccuracy;
}
public function setClassificationAccuracy($classificationAccuracy) {
$this->classificationAccuracy = $classificationAccuracy;
}
public function getClassificationAccuracy() {
return $this->classificationAccuracy;
}
}
class Update extends apiModel {
public $csvInstance;
public $label;
public function setCsvInstance(/* array(object) */ $csvInstance) {
$this->assertIsArray($csvInstance, 'object', __METHOD__);
$this->csvInstance = $csvInstance;
}
public function getCsvInstance() {
return $this->csvInstance;
}
public function setLabel($label) {
$this->label = $label;
}
public function getLabel() {
return $this->label;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiPredictionService.php | PHP | asf20 | 14,293 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "webResource" collection of methods.
* Typical usage is:
* <code>
* $siteVerificationService = new apiSiteVerificationService(...);
* $webResource = $siteVerificationService->webResource;
* </code>
*/
class WebResourceServiceResource extends apiServiceResource {
/**
* Attempt verification of a website or domain. (webResource.insert)
*
* @param string $verificationMethod The method to use for verifying a site or domain.
* @param SiteVerificationWebResourceResource $postBody
* @return SiteVerificationWebResourceResource
*/
public function insert($verificationMethod, SiteVerificationWebResourceResource $postBody, $optParams = array()) {
$params = array('verificationMethod' => $verificationMethod, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new SiteVerificationWebResourceResource($data);
} else {
return $data;
}
}
/**
* Get the most current data for a website or domain. (webResource.get)
*
* @param string $id The id of a verified site or domain.
* @return SiteVerificationWebResourceResource
*/
public function get($id, $optParams = array()) {
$params = array('id' => $id);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new SiteVerificationWebResourceResource($data);
} else {
return $data;
}
}
/**
* Get the list of your verified websites and domains. (webResource.list)
*
* @return SiteVerificationWebResourceListResponse
*/
public function listWebResource($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new SiteVerificationWebResourceListResponse($data);
} else {
return $data;
}
}
/**
* Modify the list of owners for your website or domain. (webResource.update)
*
* @param string $id The id of a verified site or domain.
* @param SiteVerificationWebResourceResource $postBody
* @return SiteVerificationWebResourceResource
*/
public function update($id, SiteVerificationWebResourceResource $postBody, $optParams = array()) {
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new SiteVerificationWebResourceResource($data);
} else {
return $data;
}
}
/**
* Modify the list of owners for your website or domain. This method supports patch semantics.
* (webResource.patch)
*
* @param string $id The id of a verified site or domain.
* @param SiteVerificationWebResourceResource $postBody
* @return SiteVerificationWebResourceResource
*/
public function patch($id, SiteVerificationWebResourceResource $postBody, $optParams = array()) {
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new SiteVerificationWebResourceResource($data);
} else {
return $data;
}
}
/**
* Get a verification token for placing on a website or domain. (webResource.getToken)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string verificationMethod The method to use for verifying a site or domain.
* @opt_param string identifier The URL or domain to verify.
* @opt_param string type Type of resource to verify. Can be 'site' (URL) or 'inet_domain' (domain name).
* @return SiteVerificationWebResourceGettokenResponse
*/
public function getToken($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('getToken', array($params));
if ($this->useObjects()) {
return new SiteVerificationWebResourceGettokenResponse($data);
} else {
return $data;
}
}
/**
* Relinquish ownership of a website or domain. (webResource.delete)
*
* @param string $id The id of a verified site or domain.
*/
public function delete($id, $optParams = array()) {
$params = array('id' => $id);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* Service definition for SiteVerification (v1).
*
* <p>
* Lets you programatically verify ownership of websites or domains with Google.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/siteverification/" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiSiteVerificationService extends apiService {
public $webResource;
/**
* Constructs the internal representation of the SiteVerification service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/siteVerification/v1/';
$this->version = 'v1';
$this->serviceName = 'siteVerification';
$apiClient->addService($this->serviceName, $this->version);
$this->webResource = new WebResourceServiceResource($this, $this->serviceName, 'webResource', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/siteverification"], "parameters": {"verificationMethod": {"required": true, "type": "string", "location": "query"}}, "request": {"$ref": "SiteVerificationWebResourceResource"}, "id": "siteVerification.webResource.insert", "httpMethod": "POST", "path": "webResource", "response": {"$ref": "SiteVerificationWebResourceResource"}}, "get": {"scopes": ["https://www.googleapis.com/auth/siteverification"], "parameters": {"id": {"required": true, "type": "string", "location": "path"}}, "id": "siteVerification.webResource.get", "httpMethod": "GET", "path": "webResource/{id}", "response": {"$ref": "SiteVerificationWebResourceResource"}}, "list": {"scopes": ["https://www.googleapis.com/auth/siteverification"], "id": "siteVerification.webResource.list", "httpMethod": "GET", "path": "webResource", "response": {"$ref": "SiteVerificationWebResourceListResponse"}}, "update": {"scopes": ["https://www.googleapis.com/auth/siteverification"], "parameters": {"id": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "SiteVerificationWebResourceResource"}, "id": "siteVerification.webResource.update", "httpMethod": "PUT", "path": "webResource/{id}", "response": {"$ref": "SiteVerificationWebResourceResource"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/siteverification"], "parameters": {"id": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "SiteVerificationWebResourceResource"}, "id": "siteVerification.webResource.patch", "httpMethod": "PATCH", "path": "webResource/{id}", "response": {"$ref": "SiteVerificationWebResourceResource"}}, "getToken": {"scopes": ["https://www.googleapis.com/auth/siteverification"], "parameters": {"type": {"type": "string", "location": "query"}, "identifier": {"type": "string", "location": "query"}, "verificationMethod": {"type": "string", "location": "query"}}, "response": {"$ref": "SiteVerificationWebResourceGettokenResponse"}, "httpMethod": "GET", "path": "token", "id": "siteVerification.webResource.getToken"}, "delete": {"scopes": ["https://www.googleapis.com/auth/siteverification"], "parameters": {"id": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "webResource/{id}", "id": "siteVerification.webResource.delete"}}}', true));
}
}
class SiteVerificationWebResourceGettokenRequest extends apiModel {
public $verificationMethod;
protected $__siteType = 'SiteVerificationWebResourceGettokenRequestSite';
protected $__siteDataType = '';
public $site;
public function setVerificationMethod($verificationMethod) {
$this->verificationMethod = $verificationMethod;
}
public function getVerificationMethod() {
return $this->verificationMethod;
}
public function setSite(SiteVerificationWebResourceGettokenRequestSite $site) {
$this->site = $site;
}
public function getSite() {
return $this->site;
}
}
class SiteVerificationWebResourceGettokenRequestSite extends apiModel {
public $identifier;
public $type;
public function setIdentifier($identifier) {
$this->identifier = $identifier;
}
public function getIdentifier() {
return $this->identifier;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
class SiteVerificationWebResourceGettokenResponse extends apiModel {
public $token;
public $method;
public function setToken($token) {
$this->token = $token;
}
public function getToken() {
return $this->token;
}
public function setMethod($method) {
$this->method = $method;
}
public function getMethod() {
return $this->method;
}
}
class SiteVerificationWebResourceListResponse extends apiModel {
protected $__itemsType = 'SiteVerificationWebResourceResource';
protected $__itemsDataType = 'array';
public $items;
public function setItems(/* array(SiteVerificationWebResourceResource) */ $items) {
$this->assertIsArray($items, 'SiteVerificationWebResourceResource', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
}
class SiteVerificationWebResourceResource extends apiModel {
public $owners;
public $id;
protected $__siteType = 'SiteVerificationWebResourceResourceSite';
protected $__siteDataType = '';
public $site;
public function setOwners(/* array(string) */ $owners) {
$this->assertIsArray($owners, 'string', __METHOD__);
$this->owners = $owners;
}
public function getOwners() {
return $this->owners;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSite(SiteVerificationWebResourceResourceSite $site) {
$this->site = $site;
}
public function getSite() {
return $this->site;
}
}
class SiteVerificationWebResourceResourceSite extends apiModel {
public $identifier;
public $type;
public function setIdentifier($identifier) {
$this->identifier = $identifier;
}
public function getIdentifier() {
return $this->identifier;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiSiteVerificationService.php | PHP | asf20 | 11,733 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "communityMembers" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communityMembers = $orkutService->communityMembers;
* </code>
*/
class CommunityMembersServiceResource extends apiServiceResource {
/**
* Makes the user join a community. (communityMembers.insert)
*
* @param int $communityId ID of the community.
* @param string $userId ID of the user.
* @return CommunityMembers
*/
public function insert($communityId, $userId, $optParams = array()) {
$params = array('communityId' => $communityId, 'userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new CommunityMembers($data);
} else {
return $data;
}
}
/**
* Retrieves the relationship between a user and a community. (communityMembers.get)
*
* @param int $communityId ID of the community.
* @param string $userId ID of the user.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityMembers
*/
public function get($communityId, $userId, $optParams = array()) {
$params = array('communityId' => $communityId, 'userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new CommunityMembers($data);
} else {
return $data;
}
}
/**
* Lists members of a community. (communityMembers.list)
*
* @param int $communityId The ID of the community whose members will be listed.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token that allows pagination.
* @opt_param bool friendsOnly Whether to list only community members who are friends of the user.
* @opt_param string maxResults The maximum number of members to include in the response.
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityMembersList
*/
public function listCommunityMembers($communityId, $optParams = array()) {
$params = array('communityId' => $communityId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommunityMembersList($data);
} else {
return $data;
}
}
/**
* Makes the user leave a community. (communityMembers.delete)
*
* @param int $communityId ID of the community.
* @param string $userId ID of the user.
*/
public function delete($communityId, $userId, $optParams = array()) {
$params = array('communityId' => $communityId, 'userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "activities" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $activities = $orkutService->activities;
* </code>
*/
class ActivitiesServiceResource extends apiServiceResource {
/**
* Retrieves a list of activities. (activities.list)
*
* @param string $userId The ID of the user whose activities will be listed. Can be me to refer to the viewer (i.e. the authenticated user).
* @param string $collection The collection of activities to list.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token that allows pagination.
* @opt_param string maxResults The maximum number of activities to include in the response.
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return ActivityList
*/
public function listActivities($userId, $collection, $optParams = array()) {
$params = array('userId' => $userId, 'collection' => $collection);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new ActivityList($data);
} else {
return $data;
}
}
/**
* Deletes an existing activity, if the access controls allow it. (activities.delete)
*
* @param string $activityId ID of the activity to remove.
*/
public function delete($activityId, $optParams = array()) {
$params = array('activityId' => $activityId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "communityPollComments" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communityPollComments = $orkutService->communityPollComments;
* </code>
*/
class CommunityPollCommentsServiceResource extends apiServiceResource {
/**
* Adds a comment on a community poll. (communityPollComments.insert)
*
* @param int $communityId The ID of the community whose poll is being commented.
* @param string $pollId The ID of the poll being commented.
* @param CommunityPollComment $postBody
* @return CommunityPollComment
*/
public function insert($communityId, $pollId, CommunityPollComment $postBody, $optParams = array()) {
$params = array('communityId' => $communityId, 'pollId' => $pollId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new CommunityPollComment($data);
} else {
return $data;
}
}
/**
* Retrieves the comments of a community poll. (communityPollComments.list)
*
* @param int $communityId The ID of the community whose poll is having its comments listed.
* @param string $pollId The ID of the community whose polls will be listed.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token that allows pagination.
* @opt_param string maxResults The maximum number of comments to include in the response.
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityPollCommentList
*/
public function listCommunityPollComments($communityId, $pollId, $optParams = array()) {
$params = array('communityId' => $communityId, 'pollId' => $pollId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommunityPollCommentList($data);
} else {
return $data;
}
}
}
/**
* The "communityPolls" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communityPolls = $orkutService->communityPolls;
* </code>
*/
class CommunityPollsServiceResource extends apiServiceResource {
/**
* Retrieves the polls of a community. (communityPolls.list)
*
* @param string $communityId The ID of the community which polls will be listed.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token that allows pagination.
* @opt_param string maxResults The maximum number of polls to include in the response.
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityPollList
*/
public function listCommunityPolls($communityId, $optParams = array()) {
$params = array('communityId' => $communityId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommunityPollList($data);
} else {
return $data;
}
}
/**
* Retrieves one specific poll of a community. (communityPolls.get)
*
* @param int $communityId The ID of the community for whose poll will be retrieved.
* @param string $pollId The ID of the poll to get.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityPoll
*/
public function get($communityId, $pollId, $optParams = array()) {
$params = array('communityId' => $communityId, 'pollId' => $pollId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new CommunityPoll($data);
} else {
return $data;
}
}
}
/**
* The "communityMessages" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communityMessages = $orkutService->communityMessages;
* </code>
*/
class CommunityMessagesServiceResource extends apiServiceResource {
/**
* Adds a message to a given community topic. (communityMessages.insert)
*
* @param int $communityId The ID of the community the message should be added to.
* @param string $topicId The ID of the topic the message should be added to.
* @param CommunityMessage $postBody
* @return CommunityMessage
*/
public function insert($communityId, $topicId, CommunityMessage $postBody, $optParams = array()) {
$params = array('communityId' => $communityId, 'topicId' => $topicId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new CommunityMessage($data);
} else {
return $data;
}
}
/**
* Retrieves the messages of a topic of a community. (communityMessages.list)
*
* @param int $communityId The ID of the community which messages will be listed.
* @param string $topicId The ID of the topic which messages will be listed.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token that allows pagination.
* @opt_param string maxResults The maximum number of messages to include in the response.
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityMessageList
*/
public function listCommunityMessages($communityId, $topicId, $optParams = array()) {
$params = array('communityId' => $communityId, 'topicId' => $topicId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommunityMessageList($data);
} else {
return $data;
}
}
/**
* Moves a message of the community to the trash folder. (communityMessages.delete)
*
* @param int $communityId The ID of the community whose message will be moved to the trash folder.
* @param string $topicId The ID of the topic whose message will be moved to the trash folder.
* @param string $messageId The ID of the message to be moved to the trash folder.
*/
public function delete($communityId, $topicId, $messageId, $optParams = array()) {
$params = array('communityId' => $communityId, 'topicId' => $topicId, 'messageId' => $messageId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "communityTopics" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communityTopics = $orkutService->communityTopics;
* </code>
*/
class CommunityTopicsServiceResource extends apiServiceResource {
/**
* Adds a topic to a given community. (communityTopics.insert)
*
* @param int $communityId The ID of the community the topic should be added to.
* @param CommunityTopic $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool isShout Whether this topic is a shout.
* @return CommunityTopic
*/
public function insert($communityId, CommunityTopic $postBody, $optParams = array()) {
$params = array('communityId' => $communityId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new CommunityTopic($data);
} else {
return $data;
}
}
/**
* Retrieves a topic of a community. (communityTopics.get)
*
* @param int $communityId The ID of the community whose topic will be retrieved.
* @param string $topicId The ID of the topic to get.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityTopic
*/
public function get($communityId, $topicId, $optParams = array()) {
$params = array('communityId' => $communityId, 'topicId' => $topicId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new CommunityTopic($data);
} else {
return $data;
}
}
/**
* Retrieves the topics of a community. (communityTopics.list)
*
* @param int $communityId The ID of the community which topics will be listed.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken A continuation token that allows pagination.
* @opt_param string maxResults The maximum number of topics to include in the response.
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityTopicList
*/
public function listCommunityTopics($communityId, $optParams = array()) {
$params = array('communityId' => $communityId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommunityTopicList($data);
} else {
return $data;
}
}
/**
* Moves a topic of the community to the trash folder. (communityTopics.delete)
*
* @param int $communityId The ID of the community whose topic will be moved to the trash folder.
* @param string $topicId The ID of the topic to be moved to the trash folder.
*/
public function delete($communityId, $topicId, $optParams = array()) {
$params = array('communityId' => $communityId, 'topicId' => $topicId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "comments" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $comments = $orkutService->comments;
* </code>
*/
class CommentsServiceResource extends apiServiceResource {
/**
* Inserts a new comment to an activity. (comments.insert)
*
* @param string $activityId The ID of the activity to contain the new comment.
* @param Comment $postBody
* @return Comment
*/
public function insert($activityId, Comment $postBody, $optParams = array()) {
$params = array('activityId' => $activityId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Comment($data);
} else {
return $data;
}
}
/**
* Retrieves an existing comment. (comments.get)
*
* @param string $commentId ID of the comment to get.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return Comment
*/
public function get($commentId, $optParams = array()) {
$params = array('commentId' => $commentId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Comment($data);
} else {
return $data;
}
}
/**
* Retrieves a list of comments, possibly filtered. (comments.list)
*
* @param string $activityId The ID of the activity containing the comments.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string orderBy Sort search results.
* @opt_param string pageToken A continuation token that allows pagination.
* @opt_param string maxResults The maximum number of activities to include in the response.
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommentList
*/
public function listComments($activityId, $optParams = array()) {
$params = array('activityId' => $activityId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommentList($data);
} else {
return $data;
}
}
/**
* Deletes an existing comment. (comments.delete)
*
* @param string $commentId ID of the comment to remove.
*/
public function delete($commentId, $optParams = array()) {
$params = array('commentId' => $commentId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "acl" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $acl = $orkutService->acl;
* </code>
*/
class AclServiceResource extends apiServiceResource {
/**
* Excludes an element from the ACL of the activity. (acl.delete)
*
* @param string $activityId ID of the activity.
* @param string $userId ID of the user to be removed from the activity.
*/
public function delete($activityId, $userId, $optParams = array()) {
$params = array('activityId' => $activityId, 'userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "communityRelated" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communityRelated = $orkutService->communityRelated;
* </code>
*/
class CommunityRelatedServiceResource extends apiServiceResource {
/**
* Retrieves the communities related to another one. (communityRelated.list)
*
* @param int $communityId The ID of the community whose related communities will be listed.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityList
*/
public function listCommunityRelated($communityId, $optParams = array()) {
$params = array('communityId' => $communityId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommunityList($data);
} else {
return $data;
}
}
}
/**
* The "scraps" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $scraps = $orkutService->scraps;
* </code>
*/
class ScrapsServiceResource extends apiServiceResource {
/**
* Creates a new scrap. (scraps.insert)
*
* @param Activity $postBody
* @return Activity
*/
public function insert(Activity $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Activity($data);
} else {
return $data;
}
}
}
/**
* The "communityPollVotes" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communityPollVotes = $orkutService->communityPollVotes;
* </code>
*/
class CommunityPollVotesServiceResource extends apiServiceResource {
/**
* Votes on a community poll. (communityPollVotes.insert)
*
* @param int $communityId The ID of the community whose poll is being voted.
* @param string $pollId The ID of the poll being voted.
* @param CommunityPollVote $postBody
* @return CommunityPollVote
*/
public function insert($communityId, $pollId, CommunityPollVote $postBody, $optParams = array()) {
$params = array('communityId' => $communityId, 'pollId' => $pollId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new CommunityPollVote($data);
} else {
return $data;
}
}
}
/**
* The "communities" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communities = $orkutService->communities;
* </code>
*/
class CommunitiesServiceResource extends apiServiceResource {
/**
* Retrieves the communities an user is member of. (communities.list)
*
* @param string $userId The ID of the user whose communities will be listed. Can be me to refer to caller.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string orderBy How to order the communities by.
* @opt_param string maxResults The maximum number of communities to include in the response.
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return CommunityList
*/
public function listCommunities($userId, $optParams = array()) {
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommunityList($data);
} else {
return $data;
}
}
/**
* Retrieves the profile of a community. (communities.get)
*
* @param int $communityId The ID of the community to get.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string hl Specifies the interface language (host language) of your user interface.
* @return Community
*/
public function get($communityId, $optParams = array()) {
$params = array('communityId' => $communityId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Community($data);
} else {
return $data;
}
}
}
/**
* The "communityFollow" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $communityFollow = $orkutService->communityFollow;
* </code>
*/
class CommunityFollowServiceResource extends apiServiceResource {
/**
* Adds an user as a follower of a community. (communityFollow.insert)
*
* @param int $communityId ID of the community.
* @param string $userId ID of the user.
* @return CommunityMembers
*/
public function insert($communityId, $userId, $optParams = array()) {
$params = array('communityId' => $communityId, 'userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new CommunityMembers($data);
} else {
return $data;
}
}
/**
* Removes an user from the followers of a community. (communityFollow.delete)
*
* @param int $communityId ID of the community.
* @param string $userId ID of the user.
*/
public function delete($communityId, $userId, $optParams = array()) {
$params = array('communityId' => $communityId, 'userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "activityVisibility" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $activityVisibility = $orkutService->activityVisibility;
* </code>
*/
class ActivityVisibilityServiceResource extends apiServiceResource {
/**
* Updates the visibility of an existing activity. This method supports patch semantics.
* (activityVisibility.patch)
*
* @param string $activityId ID of the activity.
* @param Visibility $postBody
* @return Visibility
*/
public function patch($activityId, Visibility $postBody, $optParams = array()) {
$params = array('activityId' => $activityId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Visibility($data);
} else {
return $data;
}
}
/**
* Updates the visibility of an existing activity. (activityVisibility.update)
*
* @param string $activityId ID of the activity.
* @param Visibility $postBody
* @return Visibility
*/
public function update($activityId, Visibility $postBody, $optParams = array()) {
$params = array('activityId' => $activityId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Visibility($data);
} else {
return $data;
}
}
/**
* Gets the visibility of an existing activity. (activityVisibility.get)
*
* @param string $activityId ID of the activity to get the visibility.
* @return Visibility
*/
public function get($activityId, $optParams = array()) {
$params = array('activityId' => $activityId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Visibility($data);
} else {
return $data;
}
}
}
/**
* The "badges" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $badges = $orkutService->badges;
* </code>
*/
class BadgesServiceResource extends apiServiceResource {
/**
* Retrieves the list of visible badges of a user. (badges.list)
*
* @param string $userId The id of the user whose badges will be listed. Can be me to refer to caller.
* @return BadgeList
*/
public function listBadges($userId, $optParams = array()) {
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new BadgeList($data);
} else {
return $data;
}
}
/**
* Retrieves a badge from a user. (badges.get)
*
* @param string $userId The ID of the user whose badges will be listed. Can be me to refer to caller.
* @param string $badgeId The ID of the badge that will be retrieved.
* @return Badge
*/
public function get($userId, $badgeId, $optParams = array()) {
$params = array('userId' => $userId, 'badgeId' => $badgeId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Badge($data);
} else {
return $data;
}
}
}
/**
* The "counters" collection of methods.
* Typical usage is:
* <code>
* $orkutService = new apiOrkutService(...);
* $counters = $orkutService->counters;
* </code>
*/
class CountersServiceResource extends apiServiceResource {
/**
* Retrieves the counters of an user. (counters.list)
*
* @param string $userId The ID of the user whose counters will be listed. Can be me to refer to caller.
* @return Counters
*/
public function listCounters($userId, $optParams = array()) {
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Counters($data);
} else {
return $data;
}
}
}
/**
* Service definition for Orkut (v2).
*
* <p>
* Lets you manage activities, comments and badges in Orkut. More stuff coming in time.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/orkut/v2/reference.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiOrkutService extends apiService {
public $communityMembers;
public $activities;
public $communityPollComments;
public $communityPolls;
public $communityMessages;
public $communityTopics;
public $comments;
public $acl;
public $communityRelated;
public $scraps;
public $communityPollVotes;
public $communities;
public $communityFollow;
public $activityVisibility;
public $badges;
public $counters;
/**
* Constructs the internal representation of the Orkut service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/orkut/v2/';
$this->version = 'v2';
$this->serviceName = 'orkut';
$apiClient->addService($this->serviceName, $this->version);
$this->communityMembers = new CommunityMembersServiceResource($this, $this->serviceName, 'communityMembers', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "userId": {"required": true, "type": "string", "location": "path"}}, "id": "orkut.communityMembers.insert", "httpMethod": "POST", "path": "communities/{communityId}/members/{userId}", "response": {"$ref": "CommunityMembers"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "userId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "communities/{communityId}/members/{userId}", "id": "orkut.communityMembers.delete"}, "list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "friendsOnly": {"type": "boolean", "location": "query"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "hl": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "minimum": "1", "type": "integer", "location": "query"}}, "id": "orkut.communityMembers.list", "httpMethod": "GET", "path": "communities/{communityId}/members", "response": {"$ref": "CommunityMembersList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "userId": {"required": true, "type": "string", "location": "path"}, "hl": {"type": "string", "location": "query"}}, "id": "orkut.communityMembers.get", "httpMethod": "GET", "path": "communities/{communityId}/members/{userId}", "response": {"$ref": "CommunityMembers"}}}}', true));
$this->activities = new ActivitiesServiceResource($this, $this->serviceName, 'activities', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"collection": {"required": true, "enum": ["all", "scraps", "stream"], "location": "path", "type": "string"}, "pageToken": {"type": "string", "location": "query"}, "userId": {"required": true, "type": "string", "location": "path"}, "hl": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "maximum": "100", "minimum": "1", "location": "query", "type": "integer"}}, "id": "orkut.activities.list", "httpMethod": "GET", "path": "people/{userId}/activities/{collection}", "response": {"$ref": "ActivityList"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"activityId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "activities/{activityId}", "id": "orkut.activities.delete"}}}', true));
$this->communityPollComments = new CommunityPollCommentsServiceResource($this, $this->serviceName, 'communityPollComments', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "pollId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "CommunityPollComment"}, "id": "orkut.communityPollComments.insert", "httpMethod": "POST", "path": "communities/{communityId}/polls/{pollId}/comments", "response": {"$ref": "CommunityPollComment"}}, "list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "hl": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "minimum": "1", "type": "integer", "location": "query"}, "pollId": {"required": true, "type": "string", "location": "path"}}, "id": "orkut.communityPollComments.list", "httpMethod": "GET", "path": "communities/{communityId}/polls/{pollId}/comments", "response": {"$ref": "CommunityPollCommentList"}}}}', true));
$this->communityPolls = new CommunityPollsServiceResource($this, $this->serviceName, 'communityPolls', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "communityId": {"required": true, "type": "string", "location": "path"}, "hl": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "minimum": "1", "type": "integer", "location": "query"}}, "id": "orkut.communityPolls.list", "httpMethod": "GET", "path": "communities/{communityId}/polls", "response": {"$ref": "CommunityPollList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "hl": {"type": "string", "location": "query"}, "pollId": {"required": true, "type": "string", "location": "path"}}, "id": "orkut.communityPolls.get", "httpMethod": "GET", "path": "communities/{communityId}/polls/{pollId}", "response": {"$ref": "CommunityPoll"}}}}', true));
$this->communityMessages = new CommunityMessagesServiceResource($this, $this->serviceName, 'communityMessages', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"topicId": {"format": "uint64", "required": true, "type": "string", "location": "path"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "CommunityMessage"}, "id": "orkut.communityMessages.insert", "httpMethod": "POST", "path": "communities/{communityId}/topics/{topicId}/messages", "response": {"$ref": "CommunityMessage"}}, "list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "hl": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "maximum": "100", "minimum": "1", "location": "query", "type": "integer"}, "topicId": {"format": "uint64", "required": true, "type": "string", "location": "path"}}, "id": "orkut.communityMessages.list", "httpMethod": "GET", "path": "communities/{communityId}/topics/{topicId}/messages", "response": {"$ref": "CommunityMessageList"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"topicId": {"format": "uint64", "required": true, "type": "string", "location": "path"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "messageId": {"format": "uint64", "required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "communities/{communityId}/topics/{topicId}/messages/{messageId}", "id": "orkut.communityMessages.delete"}}}', true));
$this->communityTopics = new CommunityTopicsServiceResource($this, $this->serviceName, 'communityTopics', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"isShout": {"type": "boolean", "location": "query"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}}, "request": {"$ref": "CommunityTopic"}, "id": "orkut.communityTopics.insert", "httpMethod": "POST", "path": "communities/{communityId}/topics", "response": {"$ref": "CommunityTopic"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"topicId": {"format": "uint64", "required": true, "type": "string", "location": "path"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}}, "httpMethod": "DELETE", "path": "communities/{communityId}/topics/{topicId}", "id": "orkut.communityTopics.delete"}, "list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "hl": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "maximum": "100", "minimum": "1", "location": "query", "type": "integer"}}, "id": "orkut.communityTopics.list", "httpMethod": "GET", "path": "communities/{communityId}/topics", "response": {"$ref": "CommunityTopicList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"topicId": {"format": "uint64", "required": true, "type": "string", "location": "path"}, "communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "hl": {"type": "string", "location": "query"}}, "id": "orkut.communityTopics.get", "httpMethod": "GET", "path": "communities/{communityId}/topics/{topicId}", "response": {"$ref": "CommunityTopic"}}}}', true));
$this->comments = new CommentsServiceResource($this, $this->serviceName, 'comments', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"activityId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Comment"}, "id": "orkut.comments.insert", "httpMethod": "POST", "path": "activities/{activityId}/comments", "response": {"$ref": "Comment"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"commentId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "comments/{commentId}", "id": "orkut.comments.delete"}, "list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"orderBy": {"default": "DESCENDING_SORT", "enum": ["ascending", "descending"], "location": "query", "type": "string"}, "pageToken": {"type": "string", "location": "query"}, "activityId": {"required": true, "type": "string", "location": "path"}, "hl": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "minimum": "1", "type": "integer", "location": "query"}}, "id": "orkut.comments.list", "httpMethod": "GET", "path": "activities/{activityId}/comments", "response": {"$ref": "CommentList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"commentId": {"required": true, "type": "string", "location": "path"}, "hl": {"type": "string", "location": "query"}}, "id": "orkut.comments.get", "httpMethod": "GET", "path": "comments/{commentId}", "response": {"$ref": "Comment"}}}}', true));
$this->acl = new AclServiceResource($this, $this->serviceName, 'acl', json_decode('{"methods": {"delete": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"activityId": {"required": true, "type": "string", "location": "path"}, "userId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "activities/{activityId}/acl/{userId}", "id": "orkut.acl.delete"}}}', true));
$this->communityRelated = new CommunityRelatedServiceResource($this, $this->serviceName, 'communityRelated', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "hl": {"type": "string", "location": "query"}}, "id": "orkut.communityRelated.list", "httpMethod": "GET", "path": "communities/{communityId}/related", "response": {"$ref": "CommunityList"}}}}', true));
$this->scraps = new ScrapsServiceResource($this, $this->serviceName, 'scraps', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/orkut"], "request": {"$ref": "Activity"}, "response": {"$ref": "Activity"}, "httpMethod": "POST", "path": "activities/scraps", "id": "orkut.scraps.insert"}}}', true));
$this->communityPollVotes = new CommunityPollVotesServiceResource($this, $this->serviceName, 'communityPollVotes', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "pollId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "CommunityPollVote"}, "id": "orkut.communityPollVotes.insert", "httpMethod": "POST", "path": "communities/{communityId}/polls/{pollId}/votes", "response": {"$ref": "CommunityPollVote"}}}}', true));
$this->communities = new CommunitiesServiceResource($this, $this->serviceName, 'communities', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"orderBy": {"enum": ["id", "ranked"], "type": "string", "location": "query"}, "userId": {"required": true, "type": "string", "location": "path"}, "hl": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "minimum": "1", "type": "integer", "location": "query"}}, "id": "orkut.communities.list", "httpMethod": "GET", "path": "people/{userId}/communities", "response": {"$ref": "CommunityList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "hl": {"type": "string", "location": "query"}}, "id": "orkut.communities.get", "httpMethod": "GET", "path": "communities/{communityId}", "response": {"$ref": "Community"}}}}', true));
$this->communityFollow = new CommunityFollowServiceResource($this, $this->serviceName, 'communityFollow', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "userId": {"required": true, "type": "string", "location": "path"}}, "id": "orkut.communityFollow.insert", "httpMethod": "POST", "path": "communities/{communityId}/followers/{userId}", "response": {"$ref": "CommunityMembers"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"communityId": {"format": "int32", "required": true, "type": "integer", "location": "path"}, "userId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "communities/{communityId}/followers/{userId}", "id": "orkut.communityFollow.delete"}}}', true));
$this->activityVisibility = new ActivityVisibilityServiceResource($this, $this->serviceName, 'activityVisibility', json_decode('{"methods": {"get": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"activityId": {"required": true, "type": "string", "location": "path"}}, "id": "orkut.activityVisibility.get", "httpMethod": "GET", "path": "activities/{activityId}/visibility", "response": {"$ref": "Visibility"}}, "update": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"activityId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Visibility"}, "id": "orkut.activityVisibility.update", "httpMethod": "PUT", "path": "activities/{activityId}/visibility", "response": {"$ref": "Visibility"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/orkut"], "parameters": {"activityId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Visibility"}, "id": "orkut.activityVisibility.patch", "httpMethod": "PATCH", "path": "activities/{activityId}/visibility", "response": {"$ref": "Visibility"}}}}', true));
$this->badges = new BadgesServiceResource($this, $this->serviceName, 'badges', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"userId": {"required": true, "type": "string", "location": "path"}}, "id": "orkut.badges.list", "httpMethod": "GET", "path": "people/{userId}/badges", "response": {"$ref": "BadgeList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"userId": {"required": true, "type": "string", "location": "path"}, "badgeId": {"format": "int64", "required": true, "type": "string", "location": "path"}}, "id": "orkut.badges.get", "httpMethod": "GET", "path": "people/{userId}/badges/{badgeId}", "response": {"$ref": "Badge"}}}}', true));
$this->counters = new CountersServiceResource($this, $this->serviceName, 'counters', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/orkut", "https://www.googleapis.com/auth/orkut.readonly"], "parameters": {"userId": {"required": true, "type": "string", "location": "path"}}, "id": "orkut.counters.list", "httpMethod": "GET", "path": "people/{userId}/counters", "response": {"$ref": "Counters"}}}}', true));
}
}
class Acl extends apiModel {
protected $__itemsType = 'AclItems';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $description;
public $totalParticipants;
public function setItems(/* array(AclItems) */ $items) {
$this->assertIsArray($items, 'AclItems', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setTotalParticipants($totalParticipants) {
$this->totalParticipants = $totalParticipants;
}
public function getTotalParticipants() {
return $this->totalParticipants;
}
}
class AclItems extends apiModel {
public $type;
public $id;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class Activity extends apiModel {
public $kind;
protected $__linksType = 'OrkutLinkResource';
protected $__linksDataType = 'array';
public $links;
public $title;
protected $__objectType = 'ActivityObject';
protected $__objectDataType = '';
public $object;
public $updated;
protected $__actorType = 'OrkutAuthorResource';
protected $__actorDataType = '';
public $actor;
protected $__accessType = 'Acl';
protected $__accessDataType = '';
public $access;
public $verb;
public $published;
public $id;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setLinks(/* array(OrkutLinkResource) */ $links) {
$this->assertIsArray($links, 'OrkutLinkResource', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setObject(ActivityObject $object) {
$this->object = $object;
}
public function getObject() {
return $this->object;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setActor(OrkutAuthorResource $actor) {
$this->actor = $actor;
}
public function getActor() {
return $this->actor;
}
public function setAccess(Acl $access) {
$this->access = $access;
}
public function getAccess() {
return $this->access;
}
public function setVerb($verb) {
$this->verb = $verb;
}
public function getVerb() {
return $this->verb;
}
public function setPublished($published) {
$this->published = $published;
}
public function getPublished() {
return $this->published;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class ActivityList extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Activity';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Activity) */ $items) {
$this->assertIsArray($items, 'Activity', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class ActivityObject extends apiModel {
public $content;
protected $__itemsType = 'OrkutActivityobjectsResource';
protected $__itemsDataType = 'array';
public $items;
protected $__repliesType = 'ActivityObjectReplies';
protected $__repliesDataType = '';
public $replies;
public $objectType;
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setItems(/* array(OrkutActivityobjectsResource) */ $items) {
$this->assertIsArray($items, 'OrkutActivityobjectsResource', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setReplies(ActivityObjectReplies $replies) {
$this->replies = $replies;
}
public function getReplies() {
return $this->replies;
}
public function setObjectType($objectType) {
$this->objectType = $objectType;
}
public function getObjectType() {
return $this->objectType;
}
}
class ActivityObjectReplies extends apiModel {
public $totalItems;
protected $__itemsType = 'Comment';
protected $__itemsDataType = 'array';
public $items;
public $url;
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setItems(/* array(Comment) */ $items) {
$this->assertIsArray($items, 'Comment', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class Badge extends apiModel {
public $badgeSmallLogo;
public $kind;
public $description;
public $sponsorLogo;
public $sponsorName;
public $badgeLargeLogo;
public $caption;
public $sponsorUrl;
public $id;
public function setBadgeSmallLogo($badgeSmallLogo) {
$this->badgeSmallLogo = $badgeSmallLogo;
}
public function getBadgeSmallLogo() {
return $this->badgeSmallLogo;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setSponsorLogo($sponsorLogo) {
$this->sponsorLogo = $sponsorLogo;
}
public function getSponsorLogo() {
return $this->sponsorLogo;
}
public function setSponsorName($sponsorName) {
$this->sponsorName = $sponsorName;
}
public function getSponsorName() {
return $this->sponsorName;
}
public function setBadgeLargeLogo($badgeLargeLogo) {
$this->badgeLargeLogo = $badgeLargeLogo;
}
public function getBadgeLargeLogo() {
return $this->badgeLargeLogo;
}
public function setCaption($caption) {
$this->caption = $caption;
}
public function getCaption() {
return $this->caption;
}
public function setSponsorUrl($sponsorUrl) {
$this->sponsorUrl = $sponsorUrl;
}
public function getSponsorUrl() {
return $this->sponsorUrl;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class BadgeList extends apiModel {
protected $__itemsType = 'Badge';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Badge) */ $items) {
$this->assertIsArray($items, 'Badge', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class Comment extends apiModel {
protected $__inReplyToType = 'CommentInReplyTo';
protected $__inReplyToDataType = '';
public $inReplyTo;
public $kind;
protected $__linksType = 'OrkutLinkResource';
protected $__linksDataType = 'array';
public $links;
protected $__actorType = 'OrkutAuthorResource';
protected $__actorDataType = '';
public $actor;
public $content;
public $published;
public $id;
public function setInReplyTo(CommentInReplyTo $inReplyTo) {
$this->inReplyTo = $inReplyTo;
}
public function getInReplyTo() {
return $this->inReplyTo;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setLinks(/* array(OrkutLinkResource) */ $links) {
$this->assertIsArray($links, 'OrkutLinkResource', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
public function setActor(OrkutAuthorResource $actor) {
$this->actor = $actor;
}
public function getActor() {
return $this->actor;
}
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setPublished($published) {
$this->published = $published;
}
public function getPublished() {
return $this->published;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class CommentInReplyTo extends apiModel {
public $type;
public $href;
public $ref;
public $rel;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setHref($href) {
$this->href = $href;
}
public function getHref() {
return $this->href;
}
public function setRef($ref) {
$this->ref = $ref;
}
public function getRef() {
return $this->ref;
}
public function setRel($rel) {
$this->rel = $rel;
}
public function getRel() {
return $this->rel;
}
}
class CommentList extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Comment';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $previousPageToken;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Comment) */ $items) {
$this->assertIsArray($items, 'Comment', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setPreviousPageToken($previousPageToken) {
$this->previousPageToken = $previousPageToken;
}
public function getPreviousPageToken() {
return $this->previousPageToken;
}
}
class Community extends apiModel {
public $category;
public $kind;
public $member_count;
public $description;
public $language;
protected $__linksType = 'OrkutLinkResource';
protected $__linksDataType = 'array';
public $links;
public $creation_date;
protected $__ownerType = 'OrkutAuthorResource';
protected $__ownerDataType = '';
public $owner;
protected $__moderatorsType = 'OrkutAuthorResource';
protected $__moderatorsDataType = 'array';
public $moderators;
public $location;
protected $__co_ownersType = 'OrkutAuthorResource';
protected $__co_ownersDataType = 'array';
public $co_owners;
public $photo_url;
public $id;
public $name;
public function setCategory($category) {
$this->category = $category;
}
public function getCategory() {
return $this->category;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setMember_count($member_count) {
$this->member_count = $member_count;
}
public function getMember_count() {
return $this->member_count;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setLanguage($language) {
$this->language = $language;
}
public function getLanguage() {
return $this->language;
}
public function setLinks(/* array(OrkutLinkResource) */ $links) {
$this->assertIsArray($links, 'OrkutLinkResource', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
public function setCreation_date($creation_date) {
$this->creation_date = $creation_date;
}
public function getCreation_date() {
return $this->creation_date;
}
public function setOwner(OrkutAuthorResource $owner) {
$this->owner = $owner;
}
public function getOwner() {
return $this->owner;
}
public function setModerators(/* array(OrkutAuthorResource) */ $moderators) {
$this->assertIsArray($moderators, 'OrkutAuthorResource', __METHOD__);
$this->moderators = $moderators;
}
public function getModerators() {
return $this->moderators;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setCo_owners(/* array(OrkutAuthorResource) */ $co_owners) {
$this->assertIsArray($co_owners, 'OrkutAuthorResource', __METHOD__);
$this->co_owners = $co_owners;
}
public function getCo_owners() {
return $this->co_owners;
}
public function setPhoto_url($photo_url) {
$this->photo_url = $photo_url;
}
public function getPhoto_url() {
return $this->photo_url;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class CommunityList extends apiModel {
protected $__itemsType = 'Community';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Community) */ $items) {
$this->assertIsArray($items, 'Community', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class CommunityMembers extends apiModel {
protected $__communityMembershipStatusType = 'CommunityMembershipStatus';
protected $__communityMembershipStatusDataType = '';
public $communityMembershipStatus;
protected $__personType = 'OrkutActivitypersonResource';
protected $__personDataType = '';
public $person;
public $kind;
public function setCommunityMembershipStatus(CommunityMembershipStatus $communityMembershipStatus) {
$this->communityMembershipStatus = $communityMembershipStatus;
}
public function getCommunityMembershipStatus() {
return $this->communityMembershipStatus;
}
public function setPerson(OrkutActivitypersonResource $person) {
$this->person = $person;
}
public function getPerson() {
return $this->person;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class CommunityMembersList extends apiModel {
public $nextPageToken;
public $kind;
protected $__itemsType = 'CommunityMembers';
protected $__itemsDataType = 'array';
public $items;
public $prevPageToken;
public $lastPageToken;
public $firstPageToken;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(CommunityMembers) */ $items) {
$this->assertIsArray($items, 'CommunityMembers', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setPrevPageToken($prevPageToken) {
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken() {
return $this->prevPageToken;
}
public function setLastPageToken($lastPageToken) {
$this->lastPageToken = $lastPageToken;
}
public function getLastPageToken() {
return $this->lastPageToken;
}
public function setFirstPageToken($firstPageToken) {
$this->firstPageToken = $firstPageToken;
}
public function getFirstPageToken() {
return $this->firstPageToken;
}
}
class CommunityMembershipStatus extends apiModel {
public $status;
public $isFollowing;
public $isRestoreAvailable;
public $isModerator;
public $kind;
public $isCoOwner;
public $canCreatePoll;
public $canShout;
public $isOwner;
public $canCreateTopic;
public $isTakebackAvailable;
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setIsFollowing($isFollowing) {
$this->isFollowing = $isFollowing;
}
public function getIsFollowing() {
return $this->isFollowing;
}
public function setIsRestoreAvailable($isRestoreAvailable) {
$this->isRestoreAvailable = $isRestoreAvailable;
}
public function getIsRestoreAvailable() {
return $this->isRestoreAvailable;
}
public function setIsModerator($isModerator) {
$this->isModerator = $isModerator;
}
public function getIsModerator() {
return $this->isModerator;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setIsCoOwner($isCoOwner) {
$this->isCoOwner = $isCoOwner;
}
public function getIsCoOwner() {
return $this->isCoOwner;
}
public function setCanCreatePoll($canCreatePoll) {
$this->canCreatePoll = $canCreatePoll;
}
public function getCanCreatePoll() {
return $this->canCreatePoll;
}
public function setCanShout($canShout) {
$this->canShout = $canShout;
}
public function getCanShout() {
return $this->canShout;
}
public function setIsOwner($isOwner) {
$this->isOwner = $isOwner;
}
public function getIsOwner() {
return $this->isOwner;
}
public function setCanCreateTopic($canCreateTopic) {
$this->canCreateTopic = $canCreateTopic;
}
public function getCanCreateTopic() {
return $this->canCreateTopic;
}
public function setIsTakebackAvailable($isTakebackAvailable) {
$this->isTakebackAvailable = $isTakebackAvailable;
}
public function getIsTakebackAvailable() {
return $this->isTakebackAvailable;
}
}
class CommunityMessage extends apiModel {
public $body;
public $kind;
protected $__linksType = 'OrkutLinkResource';
protected $__linksDataType = 'array';
public $links;
protected $__authorType = 'OrkutAuthorResource';
protected $__authorDataType = '';
public $author;
public $id;
public $addedDate;
public $isSpam;
public $subject;
public function setBody($body) {
$this->body = $body;
}
public function getBody() {
return $this->body;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setLinks(/* array(OrkutLinkResource) */ $links) {
$this->assertIsArray($links, 'OrkutLinkResource', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
public function setAuthor(OrkutAuthorResource $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setAddedDate($addedDate) {
$this->addedDate = $addedDate;
}
public function getAddedDate() {
return $this->addedDate;
}
public function setIsSpam($isSpam) {
$this->isSpam = $isSpam;
}
public function getIsSpam() {
return $this->isSpam;
}
public function setSubject($subject) {
$this->subject = $subject;
}
public function getSubject() {
return $this->subject;
}
}
class CommunityMessageList extends apiModel {
public $nextPageToken;
public $kind;
protected $__itemsType = 'CommunityMessage';
protected $__itemsDataType = 'array';
public $items;
public $prevPageToken;
public $lastPageToken;
public $firstPageToken;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(CommunityMessage) */ $items) {
$this->assertIsArray($items, 'CommunityMessage', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setPrevPageToken($prevPageToken) {
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken() {
return $this->prevPageToken;
}
public function setLastPageToken($lastPageToken) {
$this->lastPageToken = $lastPageToken;
}
public function getLastPageToken() {
return $this->lastPageToken;
}
public function setFirstPageToken($firstPageToken) {
$this->firstPageToken = $firstPageToken;
}
public function getFirstPageToken() {
return $this->firstPageToken;
}
}
class CommunityPoll extends apiModel {
protected $__linksType = 'OrkutLinkResource';
protected $__linksDataType = 'array';
public $links;
public $isMultipleAnswers;
protected $__imageType = 'CommunityPollImage';
protected $__imageDataType = '';
public $image;
public $endingTime;
public $isVotingAllowedForNonMembers;
public $isSpam;
public $totalNumberOfVotes;
protected $__authorType = 'OrkutAuthorResource';
protected $__authorDataType = '';
public $author;
public $question;
public $id;
public $isRestricted;
public $communityId;
public $isUsersVotePublic;
public $lastUpdate;
public $description;
public $votedOptions;
public $isOpenForVoting;
public $isClosed;
public $hasVoted;
public $kind;
public $creationTime;
protected $__optionsType = 'OrkutCommunitypolloptionResource';
protected $__optionsDataType = 'array';
public $options;
public function setLinks(/* array(OrkutLinkResource) */ $links) {
$this->assertIsArray($links, 'OrkutLinkResource', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
public function setIsMultipleAnswers($isMultipleAnswers) {
$this->isMultipleAnswers = $isMultipleAnswers;
}
public function getIsMultipleAnswers() {
return $this->isMultipleAnswers;
}
public function setImage(CommunityPollImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setEndingTime($endingTime) {
$this->endingTime = $endingTime;
}
public function getEndingTime() {
return $this->endingTime;
}
public function setIsVotingAllowedForNonMembers($isVotingAllowedForNonMembers) {
$this->isVotingAllowedForNonMembers = $isVotingAllowedForNonMembers;
}
public function getIsVotingAllowedForNonMembers() {
return $this->isVotingAllowedForNonMembers;
}
public function setIsSpam($isSpam) {
$this->isSpam = $isSpam;
}
public function getIsSpam() {
return $this->isSpam;
}
public function setTotalNumberOfVotes($totalNumberOfVotes) {
$this->totalNumberOfVotes = $totalNumberOfVotes;
}
public function getTotalNumberOfVotes() {
return $this->totalNumberOfVotes;
}
public function setAuthor(OrkutAuthorResource $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setQuestion($question) {
$this->question = $question;
}
public function getQuestion() {
return $this->question;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setIsRestricted($isRestricted) {
$this->isRestricted = $isRestricted;
}
public function getIsRestricted() {
return $this->isRestricted;
}
public function setCommunityId($communityId) {
$this->communityId = $communityId;
}
public function getCommunityId() {
return $this->communityId;
}
public function setIsUsersVotePublic($isUsersVotePublic) {
$this->isUsersVotePublic = $isUsersVotePublic;
}
public function getIsUsersVotePublic() {
return $this->isUsersVotePublic;
}
public function setLastUpdate($lastUpdate) {
$this->lastUpdate = $lastUpdate;
}
public function getLastUpdate() {
return $this->lastUpdate;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setVotedOptions(/* array(int) */ $votedOptions) {
$this->assertIsArray($votedOptions, 'int', __METHOD__);
$this->votedOptions = $votedOptions;
}
public function getVotedOptions() {
return $this->votedOptions;
}
public function setIsOpenForVoting($isOpenForVoting) {
$this->isOpenForVoting = $isOpenForVoting;
}
public function getIsOpenForVoting() {
return $this->isOpenForVoting;
}
public function setIsClosed($isClosed) {
$this->isClosed = $isClosed;
}
public function getIsClosed() {
return $this->isClosed;
}
public function setHasVoted($hasVoted) {
$this->hasVoted = $hasVoted;
}
public function getHasVoted() {
return $this->hasVoted;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setCreationTime($creationTime) {
$this->creationTime = $creationTime;
}
public function getCreationTime() {
return $this->creationTime;
}
public function setOptions(/* array(OrkutCommunitypolloptionResource) */ $options) {
$this->assertIsArray($options, 'OrkutCommunitypolloptionResource', __METHOD__);
$this->options = $options;
}
public function getOptions() {
return $this->options;
}
}
class CommunityPollComment extends apiModel {
public $body;
public $kind;
public $addedDate;
public $id;
protected $__authorType = 'OrkutAuthorResource';
protected $__authorDataType = '';
public $author;
public function setBody($body) {
$this->body = $body;
}
public function getBody() {
return $this->body;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAddedDate($addedDate) {
$this->addedDate = $addedDate;
}
public function getAddedDate() {
return $this->addedDate;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setAuthor(OrkutAuthorResource $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
}
class CommunityPollCommentList extends apiModel {
public $nextPageToken;
public $kind;
protected $__itemsType = 'CommunityPollComment';
protected $__itemsDataType = 'array';
public $items;
public $prevPageToken;
public $lastPageToken;
public $firstPageToken;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(CommunityPollComment) */ $items) {
$this->assertIsArray($items, 'CommunityPollComment', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setPrevPageToken($prevPageToken) {
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken() {
return $this->prevPageToken;
}
public function setLastPageToken($lastPageToken) {
$this->lastPageToken = $lastPageToken;
}
public function getLastPageToken() {
return $this->lastPageToken;
}
public function setFirstPageToken($firstPageToken) {
$this->firstPageToken = $firstPageToken;
}
public function getFirstPageToken() {
return $this->firstPageToken;
}
}
class CommunityPollImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class CommunityPollList extends apiModel {
public $nextPageToken;
public $kind;
protected $__itemsType = 'CommunityPoll';
protected $__itemsDataType = 'array';
public $items;
public $prevPageToken;
public $lastPageToken;
public $firstPageToken;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(CommunityPoll) */ $items) {
$this->assertIsArray($items, 'CommunityPoll', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setPrevPageToken($prevPageToken) {
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken() {
return $this->prevPageToken;
}
public function setLastPageToken($lastPageToken) {
$this->lastPageToken = $lastPageToken;
}
public function getLastPageToken() {
return $this->lastPageToken;
}
public function setFirstPageToken($firstPageToken) {
$this->firstPageToken = $firstPageToken;
}
public function getFirstPageToken() {
return $this->firstPageToken;
}
}
class CommunityPollVote extends apiModel {
public $kind;
public $optionIds;
public $isVotevisible;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setOptionIds(/* array(int) */ $optionIds) {
$this->assertIsArray($optionIds, 'int', __METHOD__);
$this->optionIds = $optionIds;
}
public function getOptionIds() {
return $this->optionIds;
}
public function setIsVotevisible($isVotevisible) {
$this->isVotevisible = $isVotevisible;
}
public function getIsVotevisible() {
return $this->isVotevisible;
}
}
class CommunityTopic extends apiModel {
public $body;
public $lastUpdate;
public $kind;
protected $__linksType = 'OrkutLinkResource';
protected $__linksDataType = 'array';
public $links;
protected $__authorType = 'OrkutAuthorResource';
protected $__authorDataType = '';
public $author;
public $title;
protected $__messagesType = 'CommunityMessage';
protected $__messagesDataType = 'array';
public $messages;
public $latestMessageSnippet;
public $isClosed;
public $numberOfReplies;
public $id;
public function setBody($body) {
$this->body = $body;
}
public function getBody() {
return $this->body;
}
public function setLastUpdate($lastUpdate) {
$this->lastUpdate = $lastUpdate;
}
public function getLastUpdate() {
return $this->lastUpdate;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setLinks(/* array(OrkutLinkResource) */ $links) {
$this->assertIsArray($links, 'OrkutLinkResource', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
public function setAuthor(OrkutAuthorResource $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setMessages(/* array(CommunityMessage) */ $messages) {
$this->assertIsArray($messages, 'CommunityMessage', __METHOD__);
$this->messages = $messages;
}
public function getMessages() {
return $this->messages;
}
public function setLatestMessageSnippet($latestMessageSnippet) {
$this->latestMessageSnippet = $latestMessageSnippet;
}
public function getLatestMessageSnippet() {
return $this->latestMessageSnippet;
}
public function setIsClosed($isClosed) {
$this->isClosed = $isClosed;
}
public function getIsClosed() {
return $this->isClosed;
}
public function setNumberOfReplies($numberOfReplies) {
$this->numberOfReplies = $numberOfReplies;
}
public function getNumberOfReplies() {
return $this->numberOfReplies;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class CommunityTopicList extends apiModel {
public $nextPageToken;
public $kind;
protected $__itemsType = 'CommunityTopic';
protected $__itemsDataType = 'array';
public $items;
public $prevPageToken;
public $lastPageToken;
public $firstPageToken;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItems(/* array(CommunityTopic) */ $items) {
$this->assertIsArray($items, 'CommunityTopic', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setPrevPageToken($prevPageToken) {
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken() {
return $this->prevPageToken;
}
public function setLastPageToken($lastPageToken) {
$this->lastPageToken = $lastPageToken;
}
public function getLastPageToken() {
return $this->lastPageToken;
}
public function setFirstPageToken($firstPageToken) {
$this->firstPageToken = $firstPageToken;
}
public function getFirstPageToken() {
return $this->firstPageToken;
}
}
class Counters extends apiModel {
protected $__itemsType = 'OrkutCounterResource';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(OrkutCounterResource) */ $items) {
$this->assertIsArray($items, 'OrkutCounterResource', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class OrkutActivityobjectsResource extends apiModel {
public $displayName;
protected $__linksType = 'OrkutLinkResource';
protected $__linksDataType = 'array';
public $links;
public $content;
protected $__personType = 'OrkutActivitypersonResource';
protected $__personDataType = '';
public $person;
public $id;
public $objectType;
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setLinks(/* array(OrkutLinkResource) */ $links) {
$this->assertIsArray($links, 'OrkutLinkResource', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setPerson(OrkutActivitypersonResource $person) {
$this->person = $person;
}
public function getPerson() {
return $this->person;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setObjectType($objectType) {
$this->objectType = $objectType;
}
public function getObjectType() {
return $this->objectType;
}
}
class OrkutActivitypersonResource extends apiModel {
protected $__nameType = 'OrkutActivitypersonResourceName';
protected $__nameDataType = '';
public $name;
public $url;
public $gender;
protected $__imageType = 'OrkutActivitypersonResourceImage';
protected $__imageDataType = '';
public $image;
public $birthday;
public $id;
public function setName(OrkutActivitypersonResourceName $name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setGender($gender) {
$this->gender = $gender;
}
public function getGender() {
return $this->gender;
}
public function setImage(OrkutActivitypersonResourceImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setBirthday($birthday) {
$this->birthday = $birthday;
}
public function getBirthday() {
return $this->birthday;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class OrkutActivitypersonResourceImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class OrkutActivitypersonResourceName extends apiModel {
public $givenName;
public $familyName;
public function setGivenName($givenName) {
$this->givenName = $givenName;
}
public function getGivenName() {
return $this->givenName;
}
public function setFamilyName($familyName) {
$this->familyName = $familyName;
}
public function getFamilyName() {
return $this->familyName;
}
}
class OrkutAuthorResource extends apiModel {
public $url;
protected $__imageType = 'OrkutAuthorResourceImage';
protected $__imageDataType = '';
public $image;
public $displayName;
public $id;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setImage(OrkutAuthorResourceImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class OrkutAuthorResourceImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class OrkutCommunitypolloptionResource extends apiModel {
protected $__imageType = 'OrkutCommunitypolloptionResourceImage';
protected $__imageDataType = '';
public $image;
public $optionId;
public $description;
public $numberOfVotes;
public function setImage(OrkutCommunitypolloptionResourceImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setOptionId($optionId) {
$this->optionId = $optionId;
}
public function getOptionId() {
return $this->optionId;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setNumberOfVotes($numberOfVotes) {
$this->numberOfVotes = $numberOfVotes;
}
public function getNumberOfVotes() {
return $this->numberOfVotes;
}
}
class OrkutCommunitypolloptionResourceImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class OrkutCounterResource extends apiModel {
public $total;
protected $__linkType = 'OrkutLinkResource';
protected $__linkDataType = '';
public $link;
public $name;
public function setTotal($total) {
$this->total = $total;
}
public function getTotal() {
return $this->total;
}
public function setLink(OrkutLinkResource $link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class OrkutLinkResource extends apiModel {
public $href;
public $type;
public $rel;
public $title;
public function setHref($href) {
$this->href = $href;
}
public function getHref() {
return $this->href;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setRel($rel) {
$this->rel = $rel;
}
public function getRel() {
return $this->rel;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
}
class Visibility extends apiModel {
public $kind;
public $visibility;
protected $__linksType = 'OrkutLinkResource';
protected $__linksDataType = 'array';
public $links;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setVisibility($visibility) {
$this->visibility = $visibility;
}
public function getVisibility() {
return $this->visibility;
}
public function setLinks(/* array(OrkutLinkResource) */ $links) {
$this->assertIsArray($links, 'OrkutLinkResource', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiOrkutService.php | PHP | asf20 | 90,735 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "currentLocation" collection of methods.
* Typical usage is:
* <code>
* $latitudeService = new apiLatitudeService(...);
* $currentLocation = $latitudeService->currentLocation;
* </code>
*/
class CurrentLocationServiceResource extends apiServiceResource {
/**
* Updates or creates the user's current location. (currentLocation.insert)
*
* @param Location $postBody
* @return Location
*/
public function insert(Location $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Location($data);
} else {
return $data;
}
}
/**
* Returns the authenticated user's current location. (currentLocation.get)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string granularity Granularity of the requested location.
* @return Location
*/
public function get($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Location($data);
} else {
return $data;
}
}
/**
* Deletes the authenticated user's current location. (currentLocation.delete)
*
*/
public function delete($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "location" collection of methods.
* Typical usage is:
* <code>
* $latitudeService = new apiLatitudeService(...);
* $location = $latitudeService->location;
* </code>
*/
class LocationServiceResource extends apiServiceResource {
/**
* Inserts or updates a location in the user's location history. (location.insert)
*
* @param Location $postBody
* @return Location
*/
public function insert(Location $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Location($data);
} else {
return $data;
}
}
/**
* Reads a location from the user's location history. (location.get)
*
* @param string $locationId Timestamp of the location to read (ms since epoch).
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string granularity Granularity of the location to return.
* @return Location
*/
public function get($locationId, $optParams = array()) {
$params = array('locationId' => $locationId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Location($data);
} else {
return $data;
}
}
/**
* Lists the user's location history. (location.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string max-results Maximum number of locations to return.
* @opt_param string max-time Maximum timestamp of locations to return (ms since epoch).
* @opt_param string min-time Minimum timestamp of locations to return (ms since epoch).
* @opt_param string granularity Granularity of the requested locations.
* @return LocationFeed
*/
public function listLocation($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new LocationFeed($data);
} else {
return $data;
}
}
/**
* Deletes a location from the user's location history. (location.delete)
*
* @param string $locationId Timestamp of the location to delete (ms since epoch).
*/
public function delete($locationId, $optParams = array()) {
$params = array('locationId' => $locationId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* Service definition for Latitude (v1).
*
* <p>
* Lets you read and update your current location and work with your location history
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/latitude/v1/using_rest.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiLatitudeService extends apiService {
public $currentLocation;
public $location;
/**
* Constructs the internal representation of the Latitude service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/latitude/v1/';
$this->version = 'v1';
$this->serviceName = 'latitude';
$apiClient->addService($this->serviceName, $this->version);
$this->currentLocation = new CurrentLocationServiceResource($this, $this->serviceName, 'currentLocation', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/latitude.all.best", "https://www.googleapis.com/auth/latitude.all.city", "https://www.googleapis.com/auth/latitude.current.best", "https://www.googleapis.com/auth/latitude.current.city"], "request": {"$ref": "LatitudeCurrentlocationResourceJson"}, "response": {"$ref": "LatitudeCurrentlocationResourceJson"}, "httpMethod": "POST", "path": "currentLocation", "id": "latitude.currentLocation.insert"}, "delete": {"id": "latitude.currentLocation.delete", "path": "currentLocation", "httpMethod": "DELETE", "scopes": ["https://www.googleapis.com/auth/latitude.all.best", "https://www.googleapis.com/auth/latitude.all.city", "https://www.googleapis.com/auth/latitude.current.best", "https://www.googleapis.com/auth/latitude.current.city"]}, "get": {"scopes": ["https://www.googleapis.com/auth/latitude.all.best", "https://www.googleapis.com/auth/latitude.all.city", "https://www.googleapis.com/auth/latitude.current.best", "https://www.googleapis.com/auth/latitude.current.city"], "parameters": {"granularity": {"type": "string", "location": "query"}}, "response": {"$ref": "LatitudeCurrentlocationResourceJson"}, "httpMethod": "GET", "path": "currentLocation", "id": "latitude.currentLocation.get"}}}', true));
$this->location = new LocationServiceResource($this, $this->serviceName, 'location', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/latitude.all.best", "https://www.googleapis.com/auth/latitude.all.city"], "request": {"$ref": "Location"}, "response": {"$ref": "Location"}, "httpMethod": "POST", "path": "location", "id": "latitude.location.insert"}, "delete": {"scopes": ["https://www.googleapis.com/auth/latitude.all.best", "https://www.googleapis.com/auth/latitude.all.city"], "parameters": {"locationId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "location/{locationId}", "id": "latitude.location.delete"}, "list": {"scopes": ["https://www.googleapis.com/auth/latitude.all.best", "https://www.googleapis.com/auth/latitude.all.city"], "parameters": {"max-results": {"type": "string", "location": "query"}, "max-time": {"type": "string", "location": "query"}, "min-time": {"type": "string", "location": "query"}, "granularity": {"type": "string", "location": "query"}}, "response": {"$ref": "LocationFeed"}, "httpMethod": "GET", "path": "location", "id": "latitude.location.list"}, "get": {"scopes": ["https://www.googleapis.com/auth/latitude.all.best", "https://www.googleapis.com/auth/latitude.all.city"], "parameters": {"locationId": {"required": true, "type": "string", "location": "path"}, "granularity": {"type": "string", "location": "query"}}, "id": "latitude.location.get", "httpMethod": "GET", "path": "location/{locationId}", "response": {"$ref": "Location"}}}}', true));
}
}
class Location extends apiModel {
public $kind;
public $altitude;
public $longitude;
public $activityId;
public $latitude;
public $altitudeAccuracy;
public $timestampMs;
public $speed;
public $heading;
public $accuracy;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAltitude($altitude) {
$this->altitude = $altitude;
}
public function getAltitude() {
return $this->altitude;
}
public function setLongitude($longitude) {
$this->longitude = $longitude;
}
public function getLongitude() {
return $this->longitude;
}
public function setActivityId($activityId) {
$this->activityId = $activityId;
}
public function getActivityId() {
return $this->activityId;
}
public function setLatitude($latitude) {
$this->latitude = $latitude;
}
public function getLatitude() {
return $this->latitude;
}
public function setAltitudeAccuracy($altitudeAccuracy) {
$this->altitudeAccuracy = $altitudeAccuracy;
}
public function getAltitudeAccuracy() {
return $this->altitudeAccuracy;
}
public function setTimestampMs($timestampMs) {
$this->timestampMs = $timestampMs;
}
public function getTimestampMs() {
return $this->timestampMs;
}
public function setSpeed($speed) {
$this->speed = $speed;
}
public function getSpeed() {
return $this->speed;
}
public function setHeading($heading) {
$this->heading = $heading;
}
public function getHeading() {
return $this->heading;
}
public function setAccuracy($accuracy) {
$this->accuracy = $accuracy;
}
public function getAccuracy() {
return $this->accuracy;
}
}
class LocationFeed extends apiModel {
protected $__itemsType = 'Location';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Location) */ $items) {
$this->assertIsArray($items, 'Location', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiLatitudeService.php | PHP | asf20 | 11,269 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "freebusy" collection of methods.
* Typical usage is:
* <code>
* $calendarService = new apiCalendarService(...);
* $freebusy = $calendarService->freebusy;
* </code>
*/
class FreebusyServiceResource extends apiServiceResource {
/**
* Returns free/busy information for a set of calendars. (freebusy.query)
*
* @param FreeBusyRequest $postBody
* @return FreeBusyResponse
*/
public function query(FreeBusyRequest $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('query', array($params));
if ($this->useObjects()) {
return new FreeBusyResponse($data);
} else {
return $data;
}
}
}
/**
* The "settings" collection of methods.
* Typical usage is:
* <code>
* $calendarService = new apiCalendarService(...);
* $settings = $calendarService->settings;
* </code>
*/
class SettingsServiceResource extends apiServiceResource {
/**
* Returns all user settings for the authenticated user. (settings.list)
*
* @return Settings
*/
public function listSettings($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Settings($data);
} else {
return $data;
}
}
/**
* Returns a single user setting. (settings.get)
*
* @param string $setting Name of the user setting.
* @return Setting
*/
public function get($setting, $optParams = array()) {
$params = array('setting' => $setting);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Setting($data);
} else {
return $data;
}
}
}
/**
* The "calendarList" collection of methods.
* Typical usage is:
* <code>
* $calendarService = new apiCalendarService(...);
* $calendarList = $calendarService->calendarList;
* </code>
*/
class CalendarListServiceResource extends apiServiceResource {
/**
* Adds an entry to the user's calendar list. (calendarList.insert)
*
* @param CalendarListEntry $postBody
* @return CalendarListEntry
*/
public function insert(CalendarListEntry $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new CalendarListEntry($data);
} else {
return $data;
}
}
/**
* Returns an entry on the user's calendar list. (calendarList.get)
*
* @param string $calendarId Calendar identifier.
* @return CalendarListEntry
*/
public function get($calendarId, $optParams = array()) {
$params = array('calendarId' => $calendarId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new CalendarListEntry($data);
} else {
return $data;
}
}
/**
* Returns entries on the user's calendar list. (calendarList.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken Token specifying which result page to return. Optional.
* @opt_param bool showHidden Whether to show hidden entries. Optional. The default is False.
* @opt_param int maxResults Maximum number of entries returned on one result page. Optional.
* @opt_param string minAccessRole The minimum access role for the user in the returned entires. Optional. The default is no restriction.
* @return CalendarList
*/
public function listCalendarList($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CalendarList($data);
} else {
return $data;
}
}
/**
* Updates an entry on the user's calendar list. (calendarList.update)
*
* @param string $calendarId Calendar identifier.
* @param CalendarListEntry $postBody
* @return CalendarListEntry
*/
public function update($calendarId, CalendarListEntry $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new CalendarListEntry($data);
} else {
return $data;
}
}
/**
* Updates an entry on the user's calendar list. This method supports patch semantics.
* (calendarList.patch)
*
* @param string $calendarId Calendar identifier.
* @param CalendarListEntry $postBody
* @return CalendarListEntry
*/
public function patch($calendarId, CalendarListEntry $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new CalendarListEntry($data);
} else {
return $data;
}
}
/**
* Deletes an entry on the user's calendar list. (calendarList.delete)
*
* @param string $calendarId Calendar identifier.
*/
public function delete($calendarId, $optParams = array()) {
$params = array('calendarId' => $calendarId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "calendars" collection of methods.
* Typical usage is:
* <code>
* $calendarService = new apiCalendarService(...);
* $calendars = $calendarService->calendars;
* </code>
*/
class CalendarsServiceResource extends apiServiceResource {
/**
* Creates a secondary calendar. (calendars.insert)
*
* @param Calendar $postBody
* @return Calendar
*/
public function insert(Calendar $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Calendar($data);
} else {
return $data;
}
}
/**
* Returns metadata for a calendar. (calendars.get)
*
* @param string $calendarId Calendar identifier.
* @return Calendar
*/
public function get($calendarId, $optParams = array()) {
$params = array('calendarId' => $calendarId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Calendar($data);
} else {
return $data;
}
}
/**
* Clears a primary calendar. This operation deletes all data associated with the primary calendar
* of an account and cannot be undone. (calendars.clear)
*
* @param string $calendarId Calendar identifier.
*/
public function clear($calendarId, $optParams = array()) {
$params = array('calendarId' => $calendarId);
$params = array_merge($params, $optParams);
$data = $this->__call('clear', array($params));
return $data;
}
/**
* Updates metadata for a calendar. (calendars.update)
*
* @param string $calendarId Calendar identifier.
* @param Calendar $postBody
* @return Calendar
*/
public function update($calendarId, Calendar $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Calendar($data);
} else {
return $data;
}
}
/**
* Updates metadata for a calendar. This method supports patch semantics. (calendars.patch)
*
* @param string $calendarId Calendar identifier.
* @param Calendar $postBody
* @return Calendar
*/
public function patch($calendarId, Calendar $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Calendar($data);
} else {
return $data;
}
}
/**
* Deletes a secondary calendar. (calendars.delete)
*
* @param string $calendarId Calendar identifier.
*/
public function delete($calendarId, $optParams = array()) {
$params = array('calendarId' => $calendarId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "acl" collection of methods.
* Typical usage is:
* <code>
* $calendarService = new apiCalendarService(...);
* $acl = $calendarService->acl;
* </code>
*/
class AclServiceResource extends apiServiceResource {
/**
* Creates an access control rule. (acl.insert)
*
* @param string $calendarId Calendar identifier.
* @param AclRule $postBody
* @return AclRule
*/
public function insert($calendarId, AclRule $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new AclRule($data);
} else {
return $data;
}
}
/**
* Returns an access control rule. (acl.get)
*
* @param string $calendarId Calendar identifier.
* @param string $ruleId ACL rule identifier.
* @return AclRule
*/
public function get($calendarId, $ruleId, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'ruleId' => $ruleId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new AclRule($data);
} else {
return $data;
}
}
/**
* Returns the rules in the access control list for the calendar. (acl.list)
*
* @param string $calendarId Calendar identifier.
* @return Acl
*/
public function listAcl($calendarId, $optParams = array()) {
$params = array('calendarId' => $calendarId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Acl($data);
} else {
return $data;
}
}
/**
* Updates an access control rule. (acl.update)
*
* @param string $calendarId Calendar identifier.
* @param string $ruleId ACL rule identifier.
* @param AclRule $postBody
* @return AclRule
*/
public function update($calendarId, $ruleId, AclRule $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'ruleId' => $ruleId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new AclRule($data);
} else {
return $data;
}
}
/**
* Updates an access control rule. This method supports patch semantics. (acl.patch)
*
* @param string $calendarId Calendar identifier.
* @param string $ruleId ACL rule identifier.
* @param AclRule $postBody
* @return AclRule
*/
public function patch($calendarId, $ruleId, AclRule $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'ruleId' => $ruleId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new AclRule($data);
} else {
return $data;
}
}
/**
* Deletes an access control rule. (acl.delete)
*
* @param string $calendarId Calendar identifier.
* @param string $ruleId ACL rule identifier.
*/
public function delete($calendarId, $ruleId, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'ruleId' => $ruleId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "colors" collection of methods.
* Typical usage is:
* <code>
* $calendarService = new apiCalendarService(...);
* $colors = $calendarService->colors;
* </code>
*/
class ColorsServiceResource extends apiServiceResource {
/**
* Returns the color definitions for calendars and events. (colors.get)
*
* @return Colors
*/
public function get($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Colors($data);
} else {
return $data;
}
}
}
/**
* The "events" collection of methods.
* Typical usage is:
* <code>
* $calendarService = new apiCalendarService(...);
* $events = $calendarService->events;
* </code>
*/
class EventsServiceResource extends apiServiceResource {
/**
* Resets a specialized instance of a recurring event to its original state. (events.reset)
*
* @param string $calendarId Calendar identifier.
* @param string $eventId Event identifier.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool sendNotifications Whether to send notifications about the event update. Optional. The default is False.
* @return Event
*/
public function reset($calendarId, $eventId, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'eventId' => $eventId);
$params = array_merge($params, $optParams);
$data = $this->__call('reset', array($params));
if ($this->useObjects()) {
return new Event($data);
} else {
return $data;
}
}
/**
* Creates an event. (events.insert)
*
* @param string $calendarId Calendar identifier.
* @param Event $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool sendNotifications Whether to send notifications about the creation of the new event. Optional. The default is False.
* @return Event
*/
public function insert($calendarId, Event $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Event($data);
} else {
return $data;
}
}
/**
* Returns an event. (events.get)
*
* @param string $calendarId Calendar identifier.
* @param string $eventId Event identifier.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string timeZone Time zone used in the response. Optional. The default is the time zone of the calendar.
* @opt_param int maxAttendees The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* @return Event
*/
public function get($calendarId, $eventId, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'eventId' => $eventId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Event($data);
} else {
return $data;
}
}
/**
* Moves an event to another calendar, i.e. changes an event's organizer. (events.move)
*
* @param string $calendarId Calendar identifier of the source calendar where the event currently is on.
* @param string $eventId Event identifier.
* @param string $destination Calendar identifier of the target calendar where the event is to be moved to.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool sendNotifications Whether to send notifications about the change of the event's organizer. Optional. The default is False.
* @return Event
*/
public function move($calendarId, $eventId, $destination, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'eventId' => $eventId, 'destination' => $destination);
$params = array_merge($params, $optParams);
$data = $this->__call('move', array($params));
if ($this->useObjects()) {
return new Event($data);
} else {
return $data;
}
}
/**
* Returns events on the specified calendar. (events.list)
*
* @param string $calendarId Calendar identifier.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string orderBy The order of the events returned in the result. Optional. The default is an unspecified, stable order.
* @opt_param bool showHiddenInvitations Whether to include hidden invitations in the result. Optional. The default is False.
* @opt_param bool showDeleted Whether to include deleted events (with 'eventStatus' equals 'cancelled') in the result. Optional. The default is False.
* @opt_param string iCalUID Specifies iCalendar UID (iCalUID) of events to be included in the response. Optional.
* @opt_param string updatedMin Lower bound for an event's last modification time (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by last modification time.
* @opt_param bool singleEvents Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying recurring events themselves. Optional. The default is False.
* @opt_param int maxResults Maximum number of events returned on one result page. Optional.
* @opt_param string q Free text search terms to find events that match these terms in any field, except for extended properties. Optional.
* @opt_param string pageToken Token specifying which result page to return. Optional.
* @opt_param string timeMin Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time.
* @opt_param string timeZone Time zone used in the response. Optional. The default is the time zone of the calendar.
* @opt_param string timeMax Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time.
* @opt_param int maxAttendees The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* @return Events
*/
public function listEvents($calendarId, $optParams = array()) {
$params = array('calendarId' => $calendarId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Events($data);
} else {
return $data;
}
}
/**
* Updates an event. (events.update)
*
* @param string $calendarId Calendar identifier.
* @param string $eventId Event identifier.
* @param Event $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool sendNotifications Whether to send notifications about the event update (e.g. attendee's responses, title changes, etc.). Optional. The default is False.
* @return Event
*/
public function update($calendarId, $eventId, Event $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'eventId' => $eventId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Event($data);
} else {
return $data;
}
}
/**
* Updates an event. This method supports patch semantics. (events.patch)
*
* @param string $calendarId Calendar identifier.
* @param string $eventId Event identifier.
* @param Event $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool sendNotifications Whether to send notifications about the event update (e.g. attendee's responses, title changes, etc.). Optional. The default is False.
* @return Event
*/
public function patch($calendarId, $eventId, Event $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'eventId' => $eventId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Event($data);
} else {
return $data;
}
}
/**
* Returns instances of the specified recurring event. (events.instances)
*
* @param string $calendarId Calendar identifier.
* @param string $eventId Recurring event identifier.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool showDeleted Whether to include deleted events (with 'eventStatus' equals 'cancelled') in the result. Optional. The default is False.
* @opt_param int maxResults Maximum number of events returned on one result page. Optional.
* @opt_param string pageToken Token specifying which result page to return. Optional.
* @opt_param string timeZone Time zone used in the response. Optional. The default is the time zone of the calendar.
* @opt_param string originalStart The original start time of the instance in the result. Optional.
* @opt_param int maxAttendees The maximum number of attendees to include in the response. If there are more than the specified number of attendees, only the participant is returned. Optional.
* @return Events
*/
public function instances($calendarId, $eventId, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'eventId' => $eventId);
$params = array_merge($params, $optParams);
$data = $this->__call('instances', array($params));
if ($this->useObjects()) {
return new Events($data);
} else {
return $data;
}
}
/**
* Imports an event. (events.import)
*
* @param string $calendarId Calendar identifier.
* @param Event $postBody
* @return Event
*/
public function import($calendarId, Event $postBody, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('import', array($params));
if ($this->useObjects()) {
return new Event($data);
} else {
return $data;
}
}
/**
* Creates an event based on a simple text string. (events.quickAdd)
*
* @param string $calendarId Calendar identifier.
* @param string $text The text describing the event to be created.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool sendNotifications Whether to send notifications about the creation of the event. Optional. The default is False.
* @return Event
*/
public function quickAdd($calendarId, $text, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'text' => $text);
$params = array_merge($params, $optParams);
$data = $this->__call('quickAdd', array($params));
if ($this->useObjects()) {
return new Event($data);
} else {
return $data;
}
}
/**
* Deletes an event. (events.delete)
*
* @param string $calendarId Calendar identifier.
* @param string $eventId Event identifier.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool sendNotifications Whether to send notifications about the deletion of the event. Optional. The default is False.
*/
public function delete($calendarId, $eventId, $optParams = array()) {
$params = array('calendarId' => $calendarId, 'eventId' => $eventId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* Service definition for Calendar (v3).
*
* <p>
* Lets you manipulate events and other calendar data.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/calendar/v3/using.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiCalendarService extends apiService {
public $freebusy;
public $settings;
public $calendarList;
public $calendars;
public $acl;
public $colors;
public $events;
/**
* Constructs the internal representation of the Calendar service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/calendar/v3/';
$this->version = 'v3';
$this->serviceName = 'calendar';
$apiClient->addService($this->serviceName, $this->version);
$this->freebusy = new FreebusyServiceResource($this, $this->serviceName, 'freebusy', json_decode('{"methods": {"query": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "request": {"$ref": "FreeBusyRequest"}, "response": {"$ref": "FreeBusyResponse"}, "httpMethod": "POST", "path": "freeBusy", "id": "calendar.freebusy.query"}}}', true));
$this->settings = new SettingsServiceResource($this, $this->serviceName, 'settings', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "id": "calendar.settings.list", "httpMethod": "GET", "path": "users/me/settings", "response": {"$ref": "Settings"}}, "get": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"setting": {"required": true, "type": "string", "location": "path"}}, "id": "calendar.settings.get", "httpMethod": "GET", "path": "users/me/settings/{setting}", "response": {"$ref": "Setting"}}}}', true));
$this->calendarList = new CalendarListServiceResource($this, $this->serviceName, 'calendarList', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/calendar"], "request": {"$ref": "CalendarListEntry"}, "response": {"$ref": "CalendarListEntry"}, "httpMethod": "POST", "path": "users/me/calendarList", "id": "calendar.calendarList.insert"}, "get": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "id": "calendar.calendarList.get", "httpMethod": "GET", "path": "users/me/calendarList/{calendarId}", "response": {"$ref": "CalendarListEntry"}}, "list": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "showHidden": {"type": "boolean", "location": "query"}, "maxResults": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}, "minAccessRole": {"enum": ["freeBusyReader", "owner", "reader", "writer"], "type": "string", "location": "query"}}, "response": {"$ref": "CalendarList"}, "httpMethod": "GET", "path": "users/me/calendarList", "id": "calendar.calendarList.list"}, "update": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "CalendarListEntry"}, "id": "calendar.calendarList.update", "httpMethod": "PUT", "path": "users/me/calendarList/{calendarId}", "response": {"$ref": "CalendarListEntry"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "CalendarListEntry"}, "id": "calendar.calendarList.patch", "httpMethod": "PATCH", "path": "users/me/calendarList/{calendarId}", "response": {"$ref": "CalendarListEntry"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "users/me/calendarList/{calendarId}", "id": "calendar.calendarList.delete"}}}', true));
$this->calendars = new CalendarsServiceResource($this, $this->serviceName, 'calendars', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/calendar"], "request": {"$ref": "Calendar"}, "response": {"$ref": "Calendar"}, "httpMethod": "POST", "path": "calendars", "id": "calendar.calendars.insert"}, "get": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "id": "calendar.calendars.get", "httpMethod": "GET", "path": "calendars/{calendarId}", "response": {"$ref": "Calendar"}}, "clear": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "POST", "path": "calendars/{calendarId}/clear", "id": "calendar.calendars.clear"}, "update": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Calendar"}, "id": "calendar.calendars.update", "httpMethod": "PUT", "path": "calendars/{calendarId}", "response": {"$ref": "Calendar"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Calendar"}, "id": "calendar.calendars.patch", "httpMethod": "PATCH", "path": "calendars/{calendarId}", "response": {"$ref": "Calendar"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "calendars/{calendarId}", "id": "calendar.calendars.delete"}}}', true));
$this->acl = new AclServiceResource($this, $this->serviceName, 'acl', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "AclRule"}, "id": "calendar.acl.insert", "httpMethod": "POST", "path": "calendars/{calendarId}/acl", "response": {"$ref": "AclRule"}}, "get": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}, "ruleId": {"required": true, "type": "string", "location": "path"}}, "id": "calendar.acl.get", "httpMethod": "GET", "path": "calendars/{calendarId}/acl/{ruleId}", "response": {"$ref": "AclRule"}}, "list": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "id": "calendar.acl.list", "httpMethod": "GET", "path": "calendars/{calendarId}/acl", "response": {"$ref": "Acl"}}, "update": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}, "ruleId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "AclRule"}, "id": "calendar.acl.update", "httpMethod": "PUT", "path": "calendars/{calendarId}/acl/{ruleId}", "response": {"$ref": "AclRule"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}, "ruleId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "AclRule"}, "id": "calendar.acl.patch", "httpMethod": "PATCH", "path": "calendars/{calendarId}/acl/{ruleId}", "response": {"$ref": "AclRule"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}, "ruleId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "calendars/{calendarId}/acl/{ruleId}", "id": "calendar.acl.delete"}}}', true));
$this->colors = new ColorsServiceResource($this, $this->serviceName, 'colors', json_decode('{"methods": {"get": {"id": "calendar.colors.get", "path": "colors", "httpMethod": "GET", "response": {"$ref": "Colors"}}}}', true));
$this->events = new EventsServiceResource($this, $this->serviceName, 'events', json_decode('{"methods": {"reset": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"eventId": {"required": true, "type": "string", "location": "path"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "sendNotifications": {"type": "boolean", "location": "query"}}, "id": "calendar.events.reset", "httpMethod": "POST", "path": "calendars/{calendarId}/events/{eventId}/reset", "response": {"$ref": "Event"}}, "insert": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}, "sendNotifications": {"type": "boolean", "location": "query"}}, "request": {"$ref": "Event"}, "id": "calendar.events.insert", "httpMethod": "POST", "path": "calendars/{calendarId}/events", "response": {"$ref": "Event"}}, "get": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"eventId": {"required": true, "type": "string", "location": "path"}, "timeZone": {"type": "string", "location": "query"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "maxAttendees": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}}, "id": "calendar.events.get", "httpMethod": "GET", "path": "calendars/{calendarId}/events/{eventId}", "response": {"$ref": "Event"}}, "move": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"eventId": {"required": true, "type": "string", "location": "path"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "destination": {"required": true, "type": "string", "location": "query"}, "sendNotifications": {"type": "boolean", "location": "query"}}, "id": "calendar.events.move", "httpMethod": "POST", "path": "calendars/{calendarId}/events/{eventId}/move", "response": {"$ref": "Event"}}, "list": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"orderBy": {"enum": ["startTime", "updated"], "type": "string", "location": "query"}, "showHiddenInvitations": {"type": "boolean", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "iCalUID": {"type": "string", "location": "query"}, "updatedMin": {"type": "string", "location": "query"}, "singleEvents": {"type": "boolean", "location": "query"}, "maxResults": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}, "q": {"type": "string", "location": "query"}, "showDeleted": {"type": "boolean", "location": "query"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "timeMin": {"type": "string", "location": "query"}, "timeZone": {"type": "string", "location": "query"}, "timeMax": {"type": "string", "location": "query"}, "maxAttendees": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}}, "id": "calendar.events.list", "httpMethod": "GET", "path": "calendars/{calendarId}/events", "response": {"$ref": "Events"}}, "update": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"eventId": {"required": true, "type": "string", "location": "path"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "sendNotifications": {"type": "boolean", "location": "query"}}, "request": {"$ref": "Event"}, "id": "calendar.events.update", "httpMethod": "PUT", "path": "calendars/{calendarId}/events/{eventId}", "response": {"$ref": "Event"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"eventId": {"required": true, "type": "string", "location": "path"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "sendNotifications": {"type": "boolean", "location": "query"}}, "request": {"$ref": "Event"}, "id": "calendar.events.patch", "httpMethod": "PATCH", "path": "calendars/{calendarId}/events/{eventId}", "response": {"$ref": "Event"}}, "instances": {"scopes": ["https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.readonly"], "parameters": {"eventId": {"required": true, "type": "string", "location": "path"}, "pageToken": {"type": "string", "location": "query"}, "maxResults": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}, "showDeleted": {"type": "boolean", "location": "query"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "timeZone": {"type": "string", "location": "query"}, "originalStart": {"type": "string", "location": "query"}, "maxAttendees": {"format": "int32", "minimum": "1", "type": "integer", "location": "query"}}, "id": "calendar.events.instances", "httpMethod": "GET", "path": "calendars/{calendarId}/events/{eventId}/instances", "response": {"$ref": "Events"}}, "import": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"calendarId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Event"}, "id": "calendar.events.import", "httpMethod": "POST", "path": "calendars/{calendarId}/events/import", "response": {"$ref": "Event"}}, "quickAdd": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"text": {"required": true, "type": "string", "location": "query"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "sendNotifications": {"type": "boolean", "location": "query"}}, "id": "calendar.events.quickAdd", "httpMethod": "POST", "path": "calendars/{calendarId}/events/quickAdd", "response": {"$ref": "Event"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/calendar"], "parameters": {"eventId": {"required": true, "type": "string", "location": "path"}, "calendarId": {"required": true, "type": "string", "location": "path"}, "sendNotifications": {"type": "boolean", "location": "query"}}, "httpMethod": "DELETE", "path": "calendars/{calendarId}/events/{eventId}", "id": "calendar.events.delete"}}}', true));
}
}
class Acl extends apiModel {
public $nextPageToken;
protected $__itemsType = 'AclRule';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(AclRule) */ $items) {
$this->assertIsArray($items, 'AclRule', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class AclRule extends apiModel {
protected $__scopeType = 'AclRuleScope';
protected $__scopeDataType = '';
public $scope;
public $kind;
public $etag;
public $role;
public $id;
public function setScope(AclRuleScope $scope) {
$this->scope = $scope;
}
public function getScope() {
return $this->scope;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setRole($role) {
$this->role = $role;
}
public function getRole() {
return $this->role;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class AclRuleScope extends apiModel {
public $type;
public $value;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class Calendar extends apiModel {
public $kind;
public $description;
public $summary;
public $etag;
public $location;
public $timeZone;
public $id;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setSummary($summary) {
$this->summary = $summary;
}
public function getSummary() {
return $this->summary;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setTimeZone($timeZone) {
$this->timeZone = $timeZone;
}
public function getTimeZone() {
return $this->timeZone;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class CalendarList extends apiModel {
public $nextPageToken;
protected $__itemsType = 'CalendarListEntry';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(CalendarListEntry) */ $items) {
$this->assertIsArray($items, 'CalendarListEntry', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class CalendarListEntry extends apiModel {
public $kind;
protected $__defaultRemindersType = 'EventReminder';
protected $__defaultRemindersDataType = 'array';
public $defaultReminders;
public $description;
public $colorId;
public $selected;
public $summary;
public $etag;
public $location;
public $summaryOverride;
public $timeZone;
public $hidden;
public $accessRole;
public $id;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDefaultReminders(/* array(EventReminder) */ $defaultReminders) {
$this->assertIsArray($defaultReminders, 'EventReminder', __METHOD__);
$this->defaultReminders = $defaultReminders;
}
public function getDefaultReminders() {
return $this->defaultReminders;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setColorId($colorId) {
$this->colorId = $colorId;
}
public function getColorId() {
return $this->colorId;
}
public function setSelected($selected) {
$this->selected = $selected;
}
public function getSelected() {
return $this->selected;
}
public function setSummary($summary) {
$this->summary = $summary;
}
public function getSummary() {
return $this->summary;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setSummaryOverride($summaryOverride) {
$this->summaryOverride = $summaryOverride;
}
public function getSummaryOverride() {
return $this->summaryOverride;
}
public function setTimeZone($timeZone) {
$this->timeZone = $timeZone;
}
public function getTimeZone() {
return $this->timeZone;
}
public function setHidden($hidden) {
$this->hidden = $hidden;
}
public function getHidden() {
return $this->hidden;
}
public function setAccessRole($accessRole) {
$this->accessRole = $accessRole;
}
public function getAccessRole() {
return $this->accessRole;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class ColorDefinition extends apiModel {
public $foreground;
public $background;
public function setForeground($foreground) {
$this->foreground = $foreground;
}
public function getForeground() {
return $this->foreground;
}
public function setBackground($background) {
$this->background = $background;
}
public function getBackground() {
return $this->background;
}
}
class Colors extends apiModel {
protected $__calendarType = 'ColorDefinition';
protected $__calendarDataType = 'map';
public $calendar;
public $updated;
protected $__eventType = 'ColorDefinition';
protected $__eventDataType = 'map';
public $event;
public $kind;
public function setCalendar(ColorDefinition $calendar) {
$this->calendar = $calendar;
}
public function getCalendar() {
return $this->calendar;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setEvent(ColorDefinition $event) {
$this->event = $event;
}
public function getEvent() {
return $this->event;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class Error extends apiModel {
public $domain;
public $reason;
public function setDomain($domain) {
$this->domain = $domain;
}
public function getDomain() {
return $this->domain;
}
public function setReason($reason) {
$this->reason = $reason;
}
public function getReason() {
return $this->reason;
}
}
class Event extends apiModel {
protected $__creatorType = 'EventCreator';
protected $__creatorDataType = '';
public $creator;
protected $__organizerType = 'EventOrganizer';
protected $__organizerDataType = '';
public $organizer;
public $id;
protected $__attendeesType = 'EventAttendee';
protected $__attendeesDataType = 'array';
public $attendees;
public $htmlLink;
public $recurrence;
protected $__startType = 'EventDateTime';
protected $__startDataType = '';
public $start;
public $etag;
public $location;
public $recurringEventId;
protected $__originalStartTimeType = 'EventDateTime';
protected $__originalStartTimeDataType = '';
public $originalStartTime;
public $status;
public $updated;
protected $__gadgetType = 'EventGadget';
protected $__gadgetDataType = '';
public $gadget;
public $description;
public $iCalUID;
protected $__extendedPropertiesType = 'EventExtendedProperties';
protected $__extendedPropertiesDataType = '';
public $extendedProperties;
public $sequence;
public $visibility;
public $guestsCanModify;
protected $__endType = 'EventDateTime';
protected $__endDataType = '';
public $end;
public $attendeesOmitted;
public $kind;
public $created;
public $colorId;
public $anyoneCanAddSelf;
protected $__remindersType = 'EventReminders';
protected $__remindersDataType = '';
public $reminders;
public $guestsCanSeeOtherGuests;
public $summary;
public $guestsCanInviteOthers;
public $transparency;
public $privateCopy;
public function setCreator(EventCreator $creator) {
$this->creator = $creator;
}
public function getCreator() {
return $this->creator;
}
public function setOrganizer(EventOrganizer $organizer) {
$this->organizer = $organizer;
}
public function getOrganizer() {
return $this->organizer;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setAttendees(/* array(EventAttendee) */ $attendees) {
$this->assertIsArray($attendees, 'EventAttendee', __METHOD__);
$this->attendees = $attendees;
}
public function getAttendees() {
return $this->attendees;
}
public function setHtmlLink($htmlLink) {
$this->htmlLink = $htmlLink;
}
public function getHtmlLink() {
return $this->htmlLink;
}
public function setRecurrence(/* array(string) */ $recurrence) {
$this->assertIsArray($recurrence, 'string', __METHOD__);
$this->recurrence = $recurrence;
}
public function getRecurrence() {
return $this->recurrence;
}
public function setStart(EventDateTime $start) {
$this->start = $start;
}
public function getStart() {
return $this->start;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
public function setRecurringEventId($recurringEventId) {
$this->recurringEventId = $recurringEventId;
}
public function getRecurringEventId() {
return $this->recurringEventId;
}
public function setOriginalStartTime(EventDateTime $originalStartTime) {
$this->originalStartTime = $originalStartTime;
}
public function getOriginalStartTime() {
return $this->originalStartTime;
}
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setGadget(EventGadget $gadget) {
$this->gadget = $gadget;
}
public function getGadget() {
return $this->gadget;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setICalUID($iCalUID) {
$this->iCalUID = $iCalUID;
}
public function getICalUID() {
return $this->iCalUID;
}
public function setExtendedProperties(EventExtendedProperties $extendedProperties) {
$this->extendedProperties = $extendedProperties;
}
public function getExtendedProperties() {
return $this->extendedProperties;
}
public function setSequence($sequence) {
$this->sequence = $sequence;
}
public function getSequence() {
return $this->sequence;
}
public function setVisibility($visibility) {
$this->visibility = $visibility;
}
public function getVisibility() {
return $this->visibility;
}
public function setGuestsCanModify($guestsCanModify) {
$this->guestsCanModify = $guestsCanModify;
}
public function getGuestsCanModify() {
return $this->guestsCanModify;
}
public function setEnd(EventDateTime $end) {
$this->end = $end;
}
public function getEnd() {
return $this->end;
}
public function setAttendeesOmitted($attendeesOmitted) {
$this->attendeesOmitted = $attendeesOmitted;
}
public function getAttendeesOmitted() {
return $this->attendeesOmitted;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setColorId($colorId) {
$this->colorId = $colorId;
}
public function getColorId() {
return $this->colorId;
}
public function setAnyoneCanAddSelf($anyoneCanAddSelf) {
$this->anyoneCanAddSelf = $anyoneCanAddSelf;
}
public function getAnyoneCanAddSelf() {
return $this->anyoneCanAddSelf;
}
public function setReminders(EventReminders $reminders) {
$this->reminders = $reminders;
}
public function getReminders() {
return $this->reminders;
}
public function setGuestsCanSeeOtherGuests($guestsCanSeeOtherGuests) {
$this->guestsCanSeeOtherGuests = $guestsCanSeeOtherGuests;
}
public function getGuestsCanSeeOtherGuests() {
return $this->guestsCanSeeOtherGuests;
}
public function setSummary($summary) {
$this->summary = $summary;
}
public function getSummary() {
return $this->summary;
}
public function setGuestsCanInviteOthers($guestsCanInviteOthers) {
$this->guestsCanInviteOthers = $guestsCanInviteOthers;
}
public function getGuestsCanInviteOthers() {
return $this->guestsCanInviteOthers;
}
public function setTransparency($transparency) {
$this->transparency = $transparency;
}
public function getTransparency() {
return $this->transparency;
}
public function setPrivateCopy($privateCopy) {
$this->privateCopy = $privateCopy;
}
public function getPrivateCopy() {
return $this->privateCopy;
}
}
class EventAttendee extends apiModel {
public $comment;
public $displayName;
public $self;
public $responseStatus;
public $additionalGuests;
public $resource;
public $organizer;
public $optional;
public $email;
public function setComment($comment) {
$this->comment = $comment;
}
public function getComment() {
return $this->comment;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setSelf($self) {
$this->self = $self;
}
public function getSelf() {
return $this->self;
}
public function setResponseStatus($responseStatus) {
$this->responseStatus = $responseStatus;
}
public function getResponseStatus() {
return $this->responseStatus;
}
public function setAdditionalGuests($additionalGuests) {
$this->additionalGuests = $additionalGuests;
}
public function getAdditionalGuests() {
return $this->additionalGuests;
}
public function setResource($resource) {
$this->resource = $resource;
}
public function getResource() {
return $this->resource;
}
public function setOrganizer($organizer) {
$this->organizer = $organizer;
}
public function getOrganizer() {
return $this->organizer;
}
public function setOptional($optional) {
$this->optional = $optional;
}
public function getOptional() {
return $this->optional;
}
public function setEmail($email) {
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
}
class EventCreator extends apiModel {
public $displayName;
public $email;
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setEmail($email) {
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
}
class EventDateTime extends apiModel {
public $date;
public $timeZone;
public $dateTime;
public function setDate($date) {
$this->date = $date;
}
public function getDate() {
return $this->date;
}
public function setTimeZone($timeZone) {
$this->timeZone = $timeZone;
}
public function getTimeZone() {
return $this->timeZone;
}
public function setDateTime($dateTime) {
$this->dateTime = $dateTime;
}
public function getDateTime() {
return $this->dateTime;
}
}
class EventExtendedProperties extends apiModel {
public $shared;
public $private;
public function setShared($shared) {
$this->shared = $shared;
}
public function getShared() {
return $this->shared;
}
public function setPrivate($private) {
$this->private = $private;
}
public function getPrivate() {
return $this->private;
}
}
class EventGadget extends apiModel {
public $preferences;
public $title;
public $height;
public $width;
public $link;
public $type;
public $display;
public $iconLink;
public function setPreferences($preferences) {
$this->preferences = $preferences;
}
public function getPreferences() {
return $this->preferences;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setHeight($height) {
$this->height = $height;
}
public function getHeight() {
return $this->height;
}
public function setWidth($width) {
$this->width = $width;
}
public function getWidth() {
return $this->width;
}
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setDisplay($display) {
$this->display = $display;
}
public function getDisplay() {
return $this->display;
}
public function setIconLink($iconLink) {
$this->iconLink = $iconLink;
}
public function getIconLink() {
return $this->iconLink;
}
}
class EventOrganizer extends apiModel {
public $displayName;
public $email;
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setEmail($email) {
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
}
class EventReminder extends apiModel {
public $minutes;
public $method;
public function setMinutes($minutes) {
$this->minutes = $minutes;
}
public function getMinutes() {
return $this->minutes;
}
public function setMethod($method) {
$this->method = $method;
}
public function getMethod() {
return $this->method;
}
}
class EventReminders extends apiModel {
protected $__overridesType = 'EventReminder';
protected $__overridesDataType = 'array';
public $overrides;
public $useDefault;
public function setOverrides(/* array(EventReminder) */ $overrides) {
$this->assertIsArray($overrides, 'EventReminder', __METHOD__);
$this->overrides = $overrides;
}
public function getOverrides() {
return $this->overrides;
}
public function setUseDefault($useDefault) {
$this->useDefault = $useDefault;
}
public function getUseDefault() {
return $this->useDefault;
}
}
class Events extends apiModel {
public $nextPageToken;
public $kind;
protected $__defaultRemindersType = 'EventReminder';
protected $__defaultRemindersDataType = 'array';
public $defaultReminders;
public $description;
protected $__itemsType = 'Event';
protected $__itemsDataType = 'array';
public $items;
public $updated;
public $summary;
public $etag;
public $timeZone;
public $accessRole;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDefaultReminders(/* array(EventReminder) */ $defaultReminders) {
$this->assertIsArray($defaultReminders, 'EventReminder', __METHOD__);
$this->defaultReminders = $defaultReminders;
}
public function getDefaultReminders() {
return $this->defaultReminders;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setItems(/* array(Event) */ $items) {
$this->assertIsArray($items, 'Event', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setSummary($summary) {
$this->summary = $summary;
}
public function getSummary() {
return $this->summary;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setTimeZone($timeZone) {
$this->timeZone = $timeZone;
}
public function getTimeZone() {
return $this->timeZone;
}
public function setAccessRole($accessRole) {
$this->accessRole = $accessRole;
}
public function getAccessRole() {
return $this->accessRole;
}
}
class FreeBusyCalendar extends apiModel {
protected $__busyType = 'TimePeriod';
protected $__busyDataType = 'array';
public $busy;
protected $__errorsType = 'Error';
protected $__errorsDataType = 'array';
public $errors;
public function setBusy(/* array(TimePeriod) */ $busy) {
$this->assertIsArray($busy, 'TimePeriod', __METHOD__);
$this->busy = $busy;
}
public function getBusy() {
return $this->busy;
}
public function setErrors(/* array(Error) */ $errors) {
$this->assertIsArray($errors, 'Error', __METHOD__);
$this->errors = $errors;
}
public function getErrors() {
return $this->errors;
}
}
class FreeBusyGroup extends apiModel {
protected $__errorsType = 'Error';
protected $__errorsDataType = 'array';
public $errors;
public $calendars;
public function setErrors(/* array(Error) */ $errors) {
$this->assertIsArray($errors, 'Error', __METHOD__);
$this->errors = $errors;
}
public function getErrors() {
return $this->errors;
}
public function setCalendars(/* array(string) */ $calendars) {
$this->assertIsArray($calendars, 'string', __METHOD__);
$this->calendars = $calendars;
}
public function getCalendars() {
return $this->calendars;
}
}
class FreeBusyRequest extends apiModel {
public $calendarExpansionMax;
public $groupExpansionMax;
public $timeMax;
protected $__itemsType = 'FreeBusyRequestItem';
protected $__itemsDataType = 'array';
public $items;
public $timeMin;
public $timeZone;
public function setCalendarExpansionMax($calendarExpansionMax) {
$this->calendarExpansionMax = $calendarExpansionMax;
}
public function getCalendarExpansionMax() {
return $this->calendarExpansionMax;
}
public function setGroupExpansionMax($groupExpansionMax) {
$this->groupExpansionMax = $groupExpansionMax;
}
public function getGroupExpansionMax() {
return $this->groupExpansionMax;
}
public function setTimeMax($timeMax) {
$this->timeMax = $timeMax;
}
public function getTimeMax() {
return $this->timeMax;
}
public function setItems(/* array(FreeBusyRequestItem) */ $items) {
$this->assertIsArray($items, 'FreeBusyRequestItem', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setTimeMin($timeMin) {
$this->timeMin = $timeMin;
}
public function getTimeMin() {
return $this->timeMin;
}
public function setTimeZone($timeZone) {
$this->timeZone = $timeZone;
}
public function getTimeZone() {
return $this->timeZone;
}
}
class FreeBusyRequestItem extends apiModel {
public $id;
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class FreeBusyResponse extends apiModel {
public $timeMax;
public $kind;
protected $__calendarsType = 'FreeBusyCalendar';
protected $__calendarsDataType = 'map';
public $calendars;
public $timeMin;
protected $__groupsType = 'FreeBusyGroup';
protected $__groupsDataType = 'map';
public $groups;
public function setTimeMax($timeMax) {
$this->timeMax = $timeMax;
}
public function getTimeMax() {
return $this->timeMax;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setCalendars(FreeBusyCalendar $calendars) {
$this->calendars = $calendars;
}
public function getCalendars() {
return $this->calendars;
}
public function setTimeMin($timeMin) {
$this->timeMin = $timeMin;
}
public function getTimeMin() {
return $this->timeMin;
}
public function setGroups(FreeBusyGroup $groups) {
$this->groups = $groups;
}
public function getGroups() {
return $this->groups;
}
}
class Setting extends apiModel {
public $kind;
public $etag;
public $id;
public $value;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setValue($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
class Settings extends apiModel {
protected $__itemsType = 'Setting';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setItems(/* array(Setting) */ $items) {
$this->assertIsArray($items, 'Setting', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class TimePeriod extends apiModel {
public $start;
public $end;
public function setStart($start) {
$this->start = $start;
}
public function getStart() {
return $this->start;
}
public function setEnd($end) {
$this->end = $end;
}
public function getEnd() {
return $this->end;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiCalendarService.php | PHP | asf20 | 68,448 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "webfonts" collection of methods.
* Typical usage is:
* <code>
* $webfontsService = new apiWebfontsService(...);
* $webfonts = $webfontsService->webfonts;
* </code>
*/
class WebfontsServiceResource extends apiServiceResource {
/**
* Retrieves the list of fonts currently served by the Google Web Fonts Developer API
* (webfonts.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string sort Enables sorting of the list
* @return WebfontList
*/
public function listWebfonts($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new WebfontList($data);
} else {
return $data;
}
}
}
/**
* Service definition for Webfonts (v1).
*
* <p>
* The Google Web Fonts Developer API.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/webfonts/docs/developer_api.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiWebfontsService extends apiService {
public $webfonts;
/**
* Constructs the internal representation of the Webfonts service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/webfonts/v1/';
$this->version = 'v1';
$this->serviceName = 'webfonts';
$apiClient->addService($this->serviceName, $this->version);
$this->webfonts = new WebfontsServiceResource($this, $this->serviceName, 'webfonts', json_decode('{"methods": {"list": {"parameters": {"sort": {"enum": ["alpha", "date", "popularity", "style", "trending"], "type": "string", "location": "query"}}, "id": "webfonts.webfonts.list", "httpMethod": "GET", "path": "webfonts", "response": {"$ref": "WebfontList"}}}}', true));
}
}
class Webfont extends apiModel {
public $kind;
public $variants;
public $subsets;
public $family;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setVariants($variants) {
$this->variants = $variants;
}
public function getVariants() {
return $this->variants;
}
public function setSubsets($subsets) {
$this->subsets = $subsets;
}
public function getSubsets() {
return $this->subsets;
}
public function setFamily($family) {
$this->family = $family;
}
public function getFamily() {
return $this->family;
}
}
class WebfontList extends apiModel {
protected $__itemsType = 'Webfont';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Webfont) */ $items) {
$this->assertIsArray($items, 'Webfont', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiWebfontsService.php | PHP | asf20 | 3,898 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "url" collection of methods.
* Typical usage is:
* <code>
* $urlshortenerService = new apiUrlshortenerService(...);
* $url = $urlshortenerService->url;
* </code>
*/
class UrlServiceResource extends apiServiceResource {
/**
* Creates a new short URL. (url.insert)
*
* @param Url $postBody
* @return Url
*/
public function insert(Url $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Url($data);
} else {
return $data;
}
}
/**
* Retrieves a list of URLs shortened by a user. (url.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string start-token Token for requesting successive pages of results.
* @opt_param string projection Additional information to return.
* @return UrlHistory
*/
public function listUrl($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new UrlHistory($data);
} else {
return $data;
}
}
/**
* Expands a short URL or gets creation time and analytics. (url.get)
*
* @param string $shortUrl The short URL, including the protocol.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string projection Additional information to return.
* @return Url
*/
public function get($shortUrl, $optParams = array()) {
$params = array('shortUrl' => $shortUrl);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Url($data);
} else {
return $data;
}
}
}
/**
* Service definition for Urlshortener (v1).
*
* <p>
* Lets you create, inspect, and manage goo.gl short URLs
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/urlshortener/v1/getting_started.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiUrlshortenerService extends apiService {
public $url;
/**
* Constructs the internal representation of the Urlshortener service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/urlshortener/v1/';
$this->version = 'v1';
$this->serviceName = 'urlshortener';
$apiClient->addService($this->serviceName, $this->version);
$this->url = new UrlServiceResource($this, $this->serviceName, 'url', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/urlshortener"], "request": {"$ref": "Url"}, "response": {"$ref": "Url"}, "httpMethod": "POST", "path": "url", "id": "urlshortener.url.insert"}, "list": {"scopes": ["https://www.googleapis.com/auth/urlshortener"], "parameters": {"start-token": {"type": "string", "location": "query"}, "projection": {"enum": ["ANALYTICS_CLICKS", "FULL"], "type": "string", "location": "query"}}, "response": {"$ref": "UrlHistory"}, "httpMethod": "GET", "path": "url/history", "id": "urlshortener.url.list"}, "get": {"parameters": {"shortUrl": {"required": true, "type": "string", "location": "query"}, "projection": {"enum": ["ANALYTICS_CLICKS", "ANALYTICS_TOP_STRINGS", "FULL"], "type": "string", "location": "query"}}, "id": "urlshortener.url.get", "httpMethod": "GET", "path": "url", "response": {"$ref": "Url"}}}}', true));
}
}
class AnalyticsSnapshot extends apiModel {
public $shortUrlClicks;
protected $__countriesType = 'StringCount';
protected $__countriesDataType = 'array';
public $countries;
protected $__platformsType = 'StringCount';
protected $__platformsDataType = 'array';
public $platforms;
protected $__browsersType = 'StringCount';
protected $__browsersDataType = 'array';
public $browsers;
protected $__referrersType = 'StringCount';
protected $__referrersDataType = 'array';
public $referrers;
public $longUrlClicks;
public function setShortUrlClicks($shortUrlClicks) {
$this->shortUrlClicks = $shortUrlClicks;
}
public function getShortUrlClicks() {
return $this->shortUrlClicks;
}
public function setCountries(/* array(StringCount) */ $countries) {
$this->assertIsArray($countries, 'StringCount', __METHOD__);
$this->countries = $countries;
}
public function getCountries() {
return $this->countries;
}
public function setPlatforms(/* array(StringCount) */ $platforms) {
$this->assertIsArray($platforms, 'StringCount', __METHOD__);
$this->platforms = $platforms;
}
public function getPlatforms() {
return $this->platforms;
}
public function setBrowsers(/* array(StringCount) */ $browsers) {
$this->assertIsArray($browsers, 'StringCount', __METHOD__);
$this->browsers = $browsers;
}
public function getBrowsers() {
return $this->browsers;
}
public function setReferrers(/* array(StringCount) */ $referrers) {
$this->assertIsArray($referrers, 'StringCount', __METHOD__);
$this->referrers = $referrers;
}
public function getReferrers() {
return $this->referrers;
}
public function setLongUrlClicks($longUrlClicks) {
$this->longUrlClicks = $longUrlClicks;
}
public function getLongUrlClicks() {
return $this->longUrlClicks;
}
}
class AnalyticsSummary extends apiModel {
protected $__weekType = 'AnalyticsSnapshot';
protected $__weekDataType = '';
public $week;
protected $__allTimeType = 'AnalyticsSnapshot';
protected $__allTimeDataType = '';
public $allTime;
protected $__twoHoursType = 'AnalyticsSnapshot';
protected $__twoHoursDataType = '';
public $twoHours;
protected $__dayType = 'AnalyticsSnapshot';
protected $__dayDataType = '';
public $day;
protected $__monthType = 'AnalyticsSnapshot';
protected $__monthDataType = '';
public $month;
public function setWeek(AnalyticsSnapshot $week) {
$this->week = $week;
}
public function getWeek() {
return $this->week;
}
public function setAllTime(AnalyticsSnapshot $allTime) {
$this->allTime = $allTime;
}
public function getAllTime() {
return $this->allTime;
}
public function setTwoHours(AnalyticsSnapshot $twoHours) {
$this->twoHours = $twoHours;
}
public function getTwoHours() {
return $this->twoHours;
}
public function setDay(AnalyticsSnapshot $day) {
$this->day = $day;
}
public function getDay() {
return $this->day;
}
public function setMonth(AnalyticsSnapshot $month) {
$this->month = $month;
}
public function getMonth() {
return $this->month;
}
}
class StringCount extends apiModel {
public $count;
public $id;
public function setCount($count) {
$this->count = $count;
}
public function getCount() {
return $this->count;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class Url extends apiModel {
public $status;
public $kind;
public $created;
protected $__analyticsType = 'AnalyticsSummary';
protected $__analyticsDataType = '';
public $analytics;
public $longUrl;
public $id;
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setAnalytics(AnalyticsSummary $analytics) {
$this->analytics = $analytics;
}
public function getAnalytics() {
return $this->analytics;
}
public function setLongUrl($longUrl) {
$this->longUrl = $longUrl;
}
public function getLongUrl() {
return $this->longUrl;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class UrlHistory extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Url';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $itemsPerPage;
public $totalItems;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Url) */ $items) {
$this->assertIsArray($items, 'Url', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setItemsPerPage($itemsPerPage) {
$this->itemsPerPage = $itemsPerPage;
}
public function getItemsPerPage() {
return $this->itemsPerPage;
}
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiUrlshortenerService.php | PHP | asf20 | 10,109 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "tasks" collection of methods.
* Typical usage is:
* <code>
* $tasksService = new apiTasksService(...);
* $tasks = $tasksService->tasks;
* </code>
*/
class TasksServiceResource extends apiServiceResource {
/**
* Creates a new task on the specified task list. (tasks.insert)
*
* @param string $tasklist Task list identifier.
* @param Task $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string parent Parent task identifier. If the task is created at the top level, this parameter is omitted. Optional.
* @opt_param string previous Previous sibling task identifier. If the task is created at the first position among its siblings, this parameter is omitted. Optional.
* @return Task
*/
public function insert($tasklist, Task $postBody, $optParams = array()) {
$params = array('tasklist' => $tasklist, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Task($data);
} else {
return $data;
}
}
/**
* Returns the specified task. (tasks.get)
*
* @param string $tasklist Task list identifier.
* @param string $task Task identifier.
* @return Task
*/
public function get($tasklist, $task, $optParams = array()) {
$params = array('tasklist' => $tasklist, 'task' => $task);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Task($data);
} else {
return $data;
}
}
/**
* Clears all completed tasks from the specified task list. The affected tasks will be marked as
* 'hidden' and no longer be returned by default when retrieving all tasks for a task list.
* (tasks.clear)
*
* @param string $tasklist Task list identifier.
*/
public function clear($tasklist, $optParams = array()) {
$params = array('tasklist' => $tasklist);
$params = array_merge($params, $optParams);
$data = $this->__call('clear', array($params));
return $data;
}
/**
* Moves the specified task to another position in the task list. This can include putting it as a
* child task under a new parent and/or move it to a different position among its sibling tasks.
* (tasks.move)
*
* @param string $tasklist Task list identifier.
* @param string $task Task identifier.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string parent New parent task identifier. If the task is moved to the top level, this parameter is omitted. Optional.
* @opt_param string previous New previous sibling task identifier. If the task is moved to the first position among its siblings, this parameter is omitted. Optional.
* @return Task
*/
public function move($tasklist, $task, $optParams = array()) {
$params = array('tasklist' => $tasklist, 'task' => $task);
$params = array_merge($params, $optParams);
$data = $this->__call('move', array($params));
if ($this->useObjects()) {
return new Task($data);
} else {
return $data;
}
}
/**
* Returns all tasks in the specified task list. (tasks.list)
*
* @param string $tasklist Task list identifier.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string dueMax Upper bound for a task's due date (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by due date.
* @opt_param bool showDeleted Flag indicating whether deleted tasks are returned in the result. Optional. The default is False.
* @opt_param string updatedMin Lower bound for a task's last modification time (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by last modification time.
* @opt_param string completedMin Lower bound for a task's completion date (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by completion date.
* @opt_param string maxResults Maximum number of task lists returned on one page. Optional. The default is 100.
* @opt_param bool showCompleted Flag indicating whether completed tasks are returned in the result. Optional. The default is True.
* @opt_param string pageToken Token specifying the result page to return. Optional.
* @opt_param string completedMax Upper bound for a task's completion date (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by completion date.
* @opt_param bool showHidden Flag indicating whether hidden tasks are returned in the result. Optional. The default is False.
* @opt_param string dueMin Lower bound for a task's due date (as a RFC 3339 timestamp) to filter by. Optional. The default is not to filter by due date.
* @return Tasks
*/
public function listTasks($tasklist, $optParams = array()) {
$params = array('tasklist' => $tasklist);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new Tasks($data);
} else {
return $data;
}
}
/**
* Updates the specified task. (tasks.update)
*
* @param string $tasklist Task list identifier.
* @param string $task Task identifier.
* @param Task $postBody
* @return Task
*/
public function update($tasklist, $task, Task $postBody, $optParams = array()) {
$params = array('tasklist' => $tasklist, 'task' => $task, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Task($data);
} else {
return $data;
}
}
/**
* Updates the specified task. This method supports patch semantics. (tasks.patch)
*
* @param string $tasklist Task list identifier.
* @param string $task Task identifier.
* @param Task $postBody
* @return Task
*/
public function patch($tasklist, $task, Task $postBody, $optParams = array()) {
$params = array('tasklist' => $tasklist, 'task' => $task, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Task($data);
} else {
return $data;
}
}
/**
* Deletes the specified task from the task list. (tasks.delete)
*
* @param string $tasklist Task list identifier.
* @param string $task Task identifier.
*/
public function delete($tasklist, $task, $optParams = array()) {
$params = array('tasklist' => $tasklist, 'task' => $task);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "tasklists" collection of methods.
* Typical usage is:
* <code>
* $tasksService = new apiTasksService(...);
* $tasklists = $tasksService->tasklists;
* </code>
*/
class TasklistsServiceResource extends apiServiceResource {
/**
* Creates a new task list and adds it to the authenticated user's task lists. (tasklists.insert)
*
* @param TaskList $postBody
* @return TaskList
*/
public function insert(TaskList $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new TaskList($data);
} else {
return $data;
}
}
/**
* Returns the authenticated user's specified task list. (tasklists.get)
*
* @param string $tasklist Task list identifier.
* @return TaskList
*/
public function get($tasklist, $optParams = array()) {
$params = array('tasklist' => $tasklist);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new TaskList($data);
} else {
return $data;
}
}
/**
* Returns all the authenticated user's task lists. (tasklists.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken Token specifying the result page to return. Optional.
* @opt_param string maxResults Maximum number of task lists returned on one page. Optional. The default is 100.
* @return TaskLists
*/
public function listTasklists($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new TaskLists($data);
} else {
return $data;
}
}
/**
* Updates the authenticated user's specified task list. (tasklists.update)
*
* @param string $tasklist Task list identifier.
* @param TaskList $postBody
* @return TaskList
*/
public function update($tasklist, TaskList $postBody, $optParams = array()) {
$params = array('tasklist' => $tasklist, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new TaskList($data);
} else {
return $data;
}
}
/**
* Updates the authenticated user's specified task list. This method supports patch semantics.
* (tasklists.patch)
*
* @param string $tasklist Task list identifier.
* @param TaskList $postBody
* @return TaskList
*/
public function patch($tasklist, TaskList $postBody, $optParams = array()) {
$params = array('tasklist' => $tasklist, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new TaskList($data);
} else {
return $data;
}
}
/**
* Deletes the authenticated user's specified task list. (tasklists.delete)
*
* @param string $tasklist Task list identifier.
*/
public function delete($tasklist, $optParams = array()) {
$params = array('tasklist' => $tasklist);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* Service definition for Tasks (v1).
*
* <p>
* Lets you manage your tasks and task lists.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="http://code.google.com/apis/tasks/v1/using.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiTasksService extends apiService {
public $tasks;
public $tasklists;
/**
* Constructs the internal representation of the Tasks service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/tasks/v1/';
$this->version = 'v1';
$this->serviceName = 'tasks';
$apiClient->addService($this->serviceName, $this->version);
$this->tasks = new TasksServiceResource($this, $this->serviceName, 'tasks', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}, "parent": {"type": "string", "location": "query"}, "previous": {"type": "string", "location": "query"}}, "request": {"$ref": "Task"}, "id": "tasks.tasks.insert", "httpMethod": "POST", "path": "lists/{tasklist}/tasks", "response": {"$ref": "Task"}}, "get": {"scopes": ["https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/tasks.readonly"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}, "task": {"required": true, "type": "string", "location": "path"}}, "id": "tasks.tasks.get", "httpMethod": "GET", "path": "lists/{tasklist}/tasks/{task}", "response": {"$ref": "Task"}}, "clear": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "POST", "path": "lists/{tasklist}/clear", "id": "tasks.tasks.clear"}, "move": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"previous": {"type": "string", "location": "query"}, "tasklist": {"required": true, "type": "string", "location": "path"}, "parent": {"type": "string", "location": "query"}, "task": {"required": true, "type": "string", "location": "path"}}, "id": "tasks.tasks.move", "httpMethod": "POST", "path": "lists/{tasklist}/tasks/{task}/move", "response": {"$ref": "Task"}}, "list": {"scopes": ["https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/tasks.readonly"], "parameters": {"dueMax": {"type": "string", "location": "query"}, "tasklist": {"required": true, "type": "string", "location": "path"}, "pageToken": {"type": "string", "location": "query"}, "updatedMin": {"type": "string", "location": "query"}, "completedMin": {"type": "string", "location": "query"}, "maxResults": {"format": "int64", "type": "string", "location": "query"}, "showCompleted": {"type": "boolean", "location": "query"}, "showDeleted": {"type": "boolean", "location": "query"}, "completedMax": {"type": "string", "location": "query"}, "showHidden": {"type": "boolean", "location": "query"}, "dueMin": {"type": "string", "location": "query"}}, "id": "tasks.tasks.list", "httpMethod": "GET", "path": "lists/{tasklist}/tasks", "response": {"$ref": "Tasks"}}, "update": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}, "task": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Task"}, "id": "tasks.tasks.update", "httpMethod": "PUT", "path": "lists/{tasklist}/tasks/{task}", "response": {"$ref": "Task"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}, "task": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Task"}, "id": "tasks.tasks.patch", "httpMethod": "PATCH", "path": "lists/{tasklist}/tasks/{task}", "response": {"$ref": "Task"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}, "task": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "lists/{tasklist}/tasks/{task}", "id": "tasks.tasks.delete"}}}', true));
$this->tasklists = new TasklistsServiceResource($this, $this->serviceName, 'tasklists', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/tasks"], "request": {"$ref": "TaskList"}, "response": {"$ref": "TaskList"}, "httpMethod": "POST", "path": "users/@me/lists", "id": "tasks.tasklists.insert"}, "get": {"scopes": ["https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/tasks.readonly"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}}, "id": "tasks.tasklists.get", "httpMethod": "GET", "path": "users/@me/lists/{tasklist}", "response": {"$ref": "TaskList"}}, "list": {"scopes": ["https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/tasks.readonly"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"format": "int64", "type": "string", "location": "query"}}, "response": {"$ref": "TaskLists"}, "httpMethod": "GET", "path": "users/@me/lists", "id": "tasks.tasklists.list"}, "update": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "TaskList"}, "id": "tasks.tasklists.update", "httpMethod": "PUT", "path": "users/@me/lists/{tasklist}", "response": {"$ref": "TaskList"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "TaskList"}, "id": "tasks.tasklists.patch", "httpMethod": "PATCH", "path": "users/@me/lists/{tasklist}", "response": {"$ref": "TaskList"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/tasks"], "parameters": {"tasklist": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "users/@me/lists/{tasklist}", "id": "tasks.tasklists.delete"}}}', true));
}
}
class Task extends apiModel {
public $status;
public $kind;
public $updated;
public $parent;
protected $__linksType = 'TaskLinks';
protected $__linksDataType = 'array';
public $links;
public $title;
public $deleted;
public $completed;
public $due;
public $etag;
public $notes;
public $position;
public $hidden;
public $id;
public $selfLink;
public function setStatus($status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setParent($parent) {
$this->parent = $parent;
}
public function getParent() {
return $this->parent;
}
public function setLinks(/* array(TaskLinks) */ $links) {
$this->assertIsArray($links, 'TaskLinks', __METHOD__);
$this->links = $links;
}
public function getLinks() {
return $this->links;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setDeleted($deleted) {
$this->deleted = $deleted;
}
public function getDeleted() {
return $this->deleted;
}
public function setCompleted($completed) {
$this->completed = $completed;
}
public function getCompleted() {
return $this->completed;
}
public function setDue($due) {
$this->due = $due;
}
public function getDue() {
return $this->due;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setNotes($notes) {
$this->notes = $notes;
}
public function getNotes() {
return $this->notes;
}
public function setPosition($position) {
$this->position = $position;
}
public function getPosition() {
return $this->position;
}
public function setHidden($hidden) {
$this->hidden = $hidden;
}
public function getHidden() {
return $this->hidden;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class TaskLinks extends apiModel {
public $type;
public $link;
public $description;
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setLink($link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
}
class TaskList extends apiModel {
public $kind;
public $etag;
public $id;
public $selfLink;
public $title;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
}
class TaskLists extends apiModel {
public $nextPageToken;
protected $__itemsType = 'TaskList';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(TaskList) */ $items) {
$this->assertIsArray($items, 'TaskList', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class Tasks extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Task';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Task) */ $items) {
$this->assertIsArray($items, 'Task', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiTasksService.php | PHP | asf20 | 23,059 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
/**
* The "blogs" collection of methods.
* Typical usage is:
* <code>
* $bloggerService = new apiBloggerService(...);
* $blogs = $bloggerService->blogs;
* </code>
*/
class BlogsServiceResource extends apiServiceResource {
/**
* Gets one blog by id. (blogs.get)
*
* @param string $blogId The ID of the blog to get.
* @return Blog
*/
public function get($blogId, $optParams = array()) {
$params = array('blogId' => $blogId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Blog($data);
} else {
return $data;
}
}
}
/**
* The "posts" collection of methods.
* Typical usage is:
* <code>
* $bloggerService = new apiBloggerService(...);
* $posts = $bloggerService->posts;
* </code>
*/
class PostsServiceResource extends apiServiceResource {
/**
* Retrieves a list of posts, possibly filtered. (posts.list)
*
* @param string $blogId ID of the blog to fetch posts from.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken Continuation token if the request is paged.
* @opt_param bool fetchBodies Whether the body content of posts is included.
* @opt_param string maxResults Maximum number of posts to fetch.
* @opt_param string startDate Earliest post date to fetch.
* @return PostList
*/
public function listPosts($blogId, $optParams = array()) {
$params = array('blogId' => $blogId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new PostList($data);
} else {
return $data;
}
}
/**
* Get a post by id. (posts.get)
*
* @param string $blogId ID of the blog to fetch the post from.
* @param string $postId The ID of the post
* @return Post
*/
public function get($blogId, $postId, $optParams = array()) {
$params = array('blogId' => $blogId, 'postId' => $postId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Post($data);
} else {
return $data;
}
}
}
/**
* The "pages" collection of methods.
* Typical usage is:
* <code>
* $bloggerService = new apiBloggerService(...);
* $pages = $bloggerService->pages;
* </code>
*/
class PagesServiceResource extends apiServiceResource {
/**
* Retrieves pages for a blog, possibly filtered. (pages.list)
*
* @param string $blogId ID of the blog to fetch pages from.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool fetchBodies Whether to retrieve the Page bodies.
* @return PageList
*/
public function listPages($blogId, $optParams = array()) {
$params = array('blogId' => $blogId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new PageList($data);
} else {
return $data;
}
}
/**
* Gets one blog page by id. (pages.get)
*
* @param string $blogId ID of the blog containing the page.
* @param string $pageId The ID of the page to get.
* @return Page
*/
public function get($blogId, $pageId, $optParams = array()) {
$params = array('blogId' => $blogId, 'pageId' => $pageId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Page($data);
} else {
return $data;
}
}
}
/**
* The "comments" collection of methods.
* Typical usage is:
* <code>
* $bloggerService = new apiBloggerService(...);
* $comments = $bloggerService->comments;
* </code>
*/
class CommentsServiceResource extends apiServiceResource {
/**
* Retrieves the comments for a blog, possibly filtered. (comments.list)
*
* @param string $blogId ID of the blog to fetch comments from.
* @param string $postId ID of the post to fetch posts from.
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string startDate Earliest date of comment to fetch.
* @opt_param string maxResults Maximum number of comments to include in the result.
* @opt_param string pageToken Continuation token if request is paged.
* @opt_param bool fetchBodies Whether the body content of the comments is included.
* @return CommentList
*/
public function listComments($blogId, $postId, $optParams = array()) {
$params = array('blogId' => $blogId, 'postId' => $postId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new CommentList($data);
} else {
return $data;
}
}
/**
* Gets one comment by id. (comments.get)
*
* @param string $blogId ID of the blog to containing the comment.
* @param string $postId ID of the post to fetch posts from.
* @param string $commentId The ID of the comment to get.
* @return Comment
*/
public function get($blogId, $postId, $commentId, $optParams = array()) {
$params = array('blogId' => $blogId, 'postId' => $postId, 'commentId' => $commentId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Comment($data);
} else {
return $data;
}
}
}
/**
* The "users" collection of methods.
* Typical usage is:
* <code>
* $bloggerService = new apiBloggerService(...);
* $users = $bloggerService->users;
* </code>
*/
class UsersServiceResource extends apiServiceResource {
/**
* Gets one user by id. (users.get)
*
* @param string $userId The ID of the user to get.
* @return User
*/
public function get($userId, $optParams = array()) {
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new User($data);
} else {
return $data;
}
}
}
/**
* The "blogs" collection of methods.
* Typical usage is:
* <code>
* $bloggerService = new apiBloggerService(...);
* $blogs = $bloggerService->blogs;
* </code>
*/
class UsersBlogsServiceResource extends apiServiceResource {
/**
* Retrieves a list of blogs, possibly filtered. (blogs.list)
*
* @param string $userId ID of the user whose blogs are to be fetched.
* @return BlogList
*/
public function listUsersBlogs($userId, $optParams = array()) {
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new BlogList($data);
} else {
return $data;
}
}
}
/**
* Service definition for Blogger (v2).
*
* <p>
* API for access to the data within Blogger.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://code.google.com/apis/blogger/docs/2.0/json/getting_started.html" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiBloggerService extends apiService {
public $blogs;
public $posts;
public $pages;
public $comments;
public $users;
public $users_blogs;
/**
* Constructs the internal representation of the Blogger service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/blogger/v2/';
$this->version = 'v2';
$this->serviceName = 'blogger';
$apiClient->addService($this->serviceName, $this->version);
$this->blogs = new BlogsServiceResource($this, $this->serviceName, 'blogs', json_decode('{"methods": {"get": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"blogId": {"required": true, "type": "string", "location": "path"}}, "id": "blogger.blogs.get", "httpMethod": "GET", "path": "blogs/{blogId}", "response": {"$ref": "Blog"}}}}', true));
$this->posts = new PostsServiceResource($this, $this->serviceName, 'posts', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "fetchBodies": {"type": "boolean", "location": "query"}, "blogId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}, "startDate": {"type": "string", "location": "query"}}, "id": "blogger.posts.list", "httpMethod": "GET", "path": "blogs/{blogId}/posts", "response": {"$ref": "PostList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"postId": {"required": true, "type": "string", "location": "path"}, "blogId": {"required": true, "type": "string", "location": "path"}}, "id": "blogger.posts.get", "httpMethod": "GET", "path": "blogs/{blogId}/posts/{postId}", "response": {"$ref": "Post"}}}}', true));
$this->pages = new PagesServiceResource($this, $this->serviceName, 'pages', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"fetchBodies": {"type": "boolean", "location": "query"}, "blogId": {"required": true, "type": "string", "location": "path"}}, "id": "blogger.pages.list", "httpMethod": "GET", "path": "blogs/{blogId}/pages", "response": {"$ref": "PageList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"pageId": {"required": true, "type": "string", "location": "path"}, "blogId": {"required": true, "type": "string", "location": "path"}}, "id": "blogger.pages.get", "httpMethod": "GET", "path": "blogs/{blogId}/pages/{pageId}", "response": {"$ref": "Page"}}}}', true));
$this->comments = new CommentsServiceResource($this, $this->serviceName, 'comments', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"startDate": {"type": "string", "location": "query"}, "postId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}, "pageToken": {"type": "string", "location": "query"}, "fetchBodies": {"type": "boolean", "location": "query"}, "blogId": {"required": true, "type": "string", "location": "path"}}, "id": "blogger.comments.list", "httpMethod": "GET", "path": "blogs/{blogId}/posts/{postId}/comments", "response": {"$ref": "CommentList"}}, "get": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"commentId": {"required": true, "type": "string", "location": "path"}, "postId": {"required": true, "type": "string", "location": "path"}, "blogId": {"required": true, "type": "string", "location": "path"}}, "id": "blogger.comments.get", "httpMethod": "GET", "path": "blogs/{blogId}/posts/{postId}/comments/{commentId}", "response": {"$ref": "Comment"}}}}', true));
$this->users = new UsersServiceResource($this, $this->serviceName, 'users', json_decode('{"methods": {"get": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"userId": {"required": true, "type": "string", "location": "path"}}, "id": "blogger.users.get", "httpMethod": "GET", "path": "users/{userId}", "response": {"$ref": "User"}}}}', true));
$this->users_blogs = new UsersBlogsServiceResource($this, $this->serviceName, 'blogs', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/blogger"], "parameters": {"userId": {"required": true, "type": "string", "location": "path"}}, "id": "blogger.users.blogs.list", "httpMethod": "GET", "path": "users/{userId}/blogs", "response": {"$ref": "BlogList"}}}}', true));
}
}
class Blog extends apiModel {
public $kind;
public $description;
protected $__localeType = 'BlogLocale';
protected $__localeDataType = '';
public $locale;
protected $__postsType = 'BlogPosts';
protected $__postsDataType = '';
public $posts;
public $updated;
public $id;
public $url;
public $published;
protected $__pagesType = 'BlogPages';
protected $__pagesDataType = '';
public $pages;
public $selfLink;
public $name;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setLocale(BlogLocale $locale) {
$this->locale = $locale;
}
public function getLocale() {
return $this->locale;
}
public function setPosts(BlogPosts $posts) {
$this->posts = $posts;
}
public function getPosts() {
return $this->posts;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setPublished($published) {
$this->published = $published;
}
public function getPublished() {
return $this->published;
}
public function setPages(BlogPages $pages) {
$this->pages = $pages;
}
public function getPages() {
return $this->pages;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class BlogList extends apiModel {
protected $__itemsType = 'Blog';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Blog) */ $items) {
$this->assertIsArray($items, 'Blog', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class BlogLocale extends apiModel {
public $country;
public $variant;
public $language;
public function setCountry($country) {
$this->country = $country;
}
public function getCountry() {
return $this->country;
}
public function setVariant($variant) {
$this->variant = $variant;
}
public function getVariant() {
return $this->variant;
}
public function setLanguage($language) {
$this->language = $language;
}
public function getLanguage() {
return $this->language;
}
}
class BlogPages extends apiModel {
public $totalItems;
public $selfLink;
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class BlogPosts extends apiModel {
public $totalItems;
public $selfLink;
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class Comment extends apiModel {
public $content;
public $kind;
protected $__authorType = 'CommentAuthor';
protected $__authorDataType = '';
public $author;
public $updated;
protected $__blogType = 'CommentBlog';
protected $__blogDataType = '';
public $blog;
public $published;
protected $__postType = 'CommentPost';
protected $__postDataType = '';
public $post;
public $id;
public $selfLink;
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAuthor(CommentAuthor $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setBlog(CommentBlog $blog) {
$this->blog = $blog;
}
public function getBlog() {
return $this->blog;
}
public function setPublished($published) {
$this->published = $published;
}
public function getPublished() {
return $this->published;
}
public function setPost(CommentPost $post) {
$this->post = $post;
}
public function getPost() {
return $this->post;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class CommentAuthor extends apiModel {
public $url;
protected $__imageType = 'CommentAuthorImage';
protected $__imageDataType = '';
public $image;
public $displayName;
public $id;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setImage(CommentAuthorImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class CommentAuthorImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class CommentBlog extends apiModel {
public $id;
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class CommentList extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Comment';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $prevPageToken;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Comment) */ $items) {
$this->assertIsArray($items, 'Comment', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setPrevPageToken($prevPageToken) {
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken() {
return $this->prevPageToken;
}
}
class CommentPost extends apiModel {
public $id;
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class Page extends apiModel {
public $content;
public $kind;
protected $__authorType = 'PageAuthor';
protected $__authorDataType = '';
public $author;
public $url;
public $title;
public $updated;
protected $__blogType = 'PageBlog';
protected $__blogDataType = '';
public $blog;
public $published;
public $id;
public $selfLink;
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAuthor(PageAuthor $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setBlog(PageBlog $blog) {
$this->blog = $blog;
}
public function getBlog() {
return $this->blog;
}
public function setPublished($published) {
$this->published = $published;
}
public function getPublished() {
return $this->published;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class PageAuthor extends apiModel {
public $url;
protected $__imageType = 'PageAuthorImage';
protected $__imageDataType = '';
public $image;
public $displayName;
public $id;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setImage(PageAuthorImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class PageAuthorImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class PageBlog extends apiModel {
public $id;
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class PageList extends apiModel {
protected $__itemsType = 'Page';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public function setItems(/* array(Page) */ $items) {
$this->assertIsArray($items, 'Page', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
}
class Post extends apiModel {
public $content;
public $kind;
protected $__authorType = 'PostAuthor';
protected $__authorDataType = '';
public $author;
protected $__repliesType = 'PostReplies';
protected $__repliesDataType = '';
public $replies;
public $labels;
public $updated;
protected $__blogType = 'PostBlog';
protected $__blogDataType = '';
public $blog;
public $url;
public $published;
public $title;
public $id;
public $selfLink;
public function setContent($content) {
$this->content = $content;
}
public function getContent() {
return $this->content;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setAuthor(PostAuthor $author) {
$this->author = $author;
}
public function getAuthor() {
return $this->author;
}
public function setReplies(PostReplies $replies) {
$this->replies = $replies;
}
public function getReplies() {
return $this->replies;
}
public function setLabels(/* array(string) */ $labels) {
$this->assertIsArray($labels, 'string', __METHOD__);
$this->labels = $labels;
}
public function getLabels() {
return $this->labels;
}
public function setUpdated($updated) {
$this->updated = $updated;
}
public function getUpdated() {
return $this->updated;
}
public function setBlog(PostBlog $blog) {
$this->blog = $blog;
}
public function getBlog() {
return $this->blog;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setPublished($published) {
$this->published = $published;
}
public function getPublished() {
return $this->published;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class PostAuthor extends apiModel {
public $url;
protected $__imageType = 'PostAuthorImage';
protected $__imageDataType = '';
public $image;
public $displayName;
public $id;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setImage(PostAuthorImage $image) {
$this->image = $image;
}
public function getImage() {
return $this->image;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class PostAuthorImage extends apiModel {
public $url;
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
}
class PostBlog extends apiModel {
public $id;
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
}
class PostList extends apiModel {
public $nextPageToken;
protected $__itemsType = 'Post';
protected $__itemsDataType = 'array';
public $items;
public $kind;
public $prevPageToken;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setItems(/* array(Post) */ $items) {
$this->assertIsArray($items, 'Post', __METHOD__);
$this->items = $items;
}
public function getItems() {
return $this->items;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setPrevPageToken($prevPageToken) {
$this->prevPageToken = $prevPageToken;
}
public function getPrevPageToken() {
return $this->prevPageToken;
}
}
class PostReplies extends apiModel {
public $totalItems;
public $selfLink;
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class User extends apiModel {
public $about;
public $displayName;
public $created;
protected $__localeType = 'UserLocale';
protected $__localeDataType = '';
public $locale;
protected $__blogsType = 'UserBlogs';
protected $__blogsDataType = '';
public $blogs;
public $kind;
public $url;
public $id;
public $selfLink;
public function setAbout($about) {
$this->about = $about;
}
public function getAbout() {
return $this->about;
}
public function setDisplayName($displayName) {
$this->displayName = $displayName;
}
public function getDisplayName() {
return $this->displayName;
}
public function setCreated($created) {
$this->created = $created;
}
public function getCreated() {
return $this->created;
}
public function setLocale(UserLocale $locale) {
$this->locale = $locale;
}
public function getLocale() {
return $this->locale;
}
public function setBlogs(UserBlogs $blogs) {
$this->blogs = $blogs;
}
public function getBlogs() {
return $this->blogs;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setUrl($url) {
$this->url = $url;
}
public function getUrl() {
return $this->url;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class UserBlogs extends apiModel {
public $selfLink;
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class UserLocale extends apiModel {
public $country;
public $variant;
public $language;
public function setCountry($country) {
$this->country = $country;
}
public function getCountry() {
return $this->country;
}
public function setVariant($variant) {
$this->variant = $variant;
}
public function getVariant() {
return $this->variant;
}
public function setLanguage($language) {
$this->language = $language;
}
public function getLanguage() {
return $this->language;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiBloggerService.php | PHP | asf20 | 30,514 |
<?php
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "tables" collection of methods.
* Typical usage is:
* <code>
* $bigqueryService = new apiBigqueryService(...);
* $tables = $bigqueryService->tables;
* </code>
*/
class TablesServiceResource extends apiServiceResource {
/**
* Creates a new, empty table in the dataset. (tables.insert)
*
* @param Table $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string projectId Project ID of the new table
* @opt_param string datasetId Dataset ID of the new table
* @return Table
*/
public function insert(Table $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Table($data);
} else {
return $data;
}
}
/**
* Gets the specified table resource by table ID. This method does not return the data in the table,
* it only returns the table resource, which describes the structure of this table. (tables.get)
*
* @param string $projectId Project ID of the requested table
* @param string $datasetId Dataset ID of the requested table
* @param string $tableId Table ID of the requested table
* @return Table
*/
public function get($projectId, $datasetId, $tableId, $optParams = array()) {
$params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Table($data);
} else {
return $data;
}
}
/**
* Lists all tables in the specified dataset. (tables.list)
*
* @param string $projectId Project ID of the tables to list
* @param string $datasetId Dataset ID of the tables to list
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken Page token, returned by a previous call, to request the next page of results
* @opt_param string maxResults Maximum number of results to return
* @return TableList
*/
public function listTables($projectId, $datasetId, $optParams = array()) {
$params = array('projectId' => $projectId, 'datasetId' => $datasetId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new TableList($data);
} else {
return $data;
}
}
/**
* Updates information in an existing table, specified by tableId. (tables.update)
*
* @param Table $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string projectId Project ID of the table to update
* @opt_param string datasetId Dataset ID of the table to update
* @opt_param string tableId Table ID of the table to update
* @return Table
*/
public function update(Table $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Table($data);
} else {
return $data;
}
}
/**
* Updates information in an existing table, specified by tableId. This method supports patch
* semantics. (tables.patch)
*
* @param string $projectId Project ID of the table to update
* @param string $datasetId Dataset ID of the table to update
* @param string $tableId Table ID of the table to update
* @param Table $postBody
* @return Table
*/
public function patch($projectId, $datasetId, $tableId, Table $postBody, $optParams = array()) {
$params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Table($data);
} else {
return $data;
}
}
/**
* Deletes the table specified by tableId from the dataset. If the table contains data, all the data
* will be deleted. (tables.delete)
*
* @param string $projectId Project ID of the table to delete
* @param string $datasetId Dataset ID of the table to delete
* @param string $tableId Table ID of the table to delete
*/
public function delete($projectId, $datasetId, $tableId, $optParams = array()) {
$params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "datasets" collection of methods.
* Typical usage is:
* <code>
* $bigqueryService = new apiBigqueryService(...);
* $datasets = $bigqueryService->datasets;
* </code>
*/
class DatasetsServiceResource extends apiServiceResource {
/**
* Creates a new empty dataset. (datasets.insert)
*
* @param Dataset $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string projectId Project ID of the new dataset
* @return Dataset
*/
public function insert(Dataset $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Dataset($data);
} else {
return $data;
}
}
/**
* Returns the dataset specified by datasetID. (datasets.get)
*
* @param string $projectId Project ID of the requested dataset
* @param string $datasetId Dataset ID of the requested dataset
* @return Dataset
*/
public function get($projectId, $datasetId, $optParams = array()) {
$params = array('projectId' => $projectId, 'datasetId' => $datasetId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Dataset($data);
} else {
return $data;
}
}
/**
* Lists all the datasets in the specified project to which the caller has read access; however, a
* project owner can list (but not necessarily get) all datasets in his project. (datasets.list)
*
* @param string $projectId Project ID of the datasets to be listed
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken Page token, returned by a previous call, to request the next page of results
* @opt_param string maxResults The maximum number of results to return
* @return DatasetList
*/
public function listDatasets($projectId, $optParams = array()) {
$params = array('projectId' => $projectId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new DatasetList($data);
} else {
return $data;
}
}
/**
* Updates information in an existing dataset, specified by datasetId. Properties not included in
* the submitted resource will not be changed. If you include the access property without any values
* assigned, the request will fail as you must specify at least one owner for a dataset.
* (datasets.update)
*
* @param Dataset $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string projectId Project ID of the dataset being updated
* @opt_param string datasetId Dataset ID of the dataset being updated
* @return Dataset
*/
public function update(Dataset $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('update', array($params));
if ($this->useObjects()) {
return new Dataset($data);
} else {
return $data;
}
}
/**
* Updates information in an existing dataset, specified by datasetId. Properties not included in
* the submitted resource will not be changed. If you include the access property without any values
* assigned, the request will fail as you must specify at least one owner for a dataset. This method
* supports patch semantics. (datasets.patch)
*
* @param string $projectId Project ID of the dataset being updated
* @param string $datasetId Dataset ID of the dataset being updated
* @param Dataset $postBody
* @return Dataset
*/
public function patch($projectId, $datasetId, Dataset $postBody, $optParams = array()) {
$params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('patch', array($params));
if ($this->useObjects()) {
return new Dataset($data);
} else {
return $data;
}
}
/**
* Deletes the dataset specified by datasetId value. Before you can delete a dataset, you must
* delete all its tables, either manually or by specifying deleteContents. Immediately after
* deletion, you can create another dataset with the same name. (datasets.delete)
*
* @param string $projectId Project ID of the dataset being deleted
* @param string $datasetId Dataset ID of dataset being deleted
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param bool deleteContents If True, delete all the tables in the dataset. If False and the dataset contains tables, the request will fail. Default is False
*/
public function delete($projectId, $datasetId, $optParams = array()) {
$params = array('projectId' => $projectId, 'datasetId' => $datasetId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "jobs" collection of methods.
* Typical usage is:
* <code>
* $bigqueryService = new apiBigqueryService(...);
* $jobs = $bigqueryService->jobs;
* </code>
*/
class JobsServiceResource extends apiServiceResource {
/**
* Starts a new asynchronous job. (jobs.insert)
*
* @param Job $postBody
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string projectId Project ID of the project that will be billed for the job
* @return Job
*/
public function insert(Job $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
return new Job($data);
} else {
return $data;
}
}
/**
* Retrieves the specified job by ID. (jobs.get)
*
* @param string $projectId Project ID of the requested job
* @param string $jobId Job ID of the requested job
* @return Job
*/
public function get($projectId, $jobId, $optParams = array()) {
$params = array('projectId' => $projectId, 'jobId' => $jobId);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Job($data);
} else {
return $data;
}
}
/**
* Lists all the Jobs in the specified project that were started by the user. (jobs.list)
*
* @param string $projectId Project ID of the jobs to list
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string projection Restrict information returned to a set of selected fields
* @opt_param string stateFilter Filter for job state
* @opt_param bool allUsers Whether to display jobs owned by all users in the project. Default false
* @opt_param string maxResults Maximum number of results to return
* @opt_param string pageToken Page token, returned by a previous call, to request the next page of results
* @return JobList
*/
public function listJobs($projectId, $optParams = array()) {
$params = array('projectId' => $projectId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new JobList($data);
} else {
return $data;
}
}
/**
* Runs a BigQuery SQL query synchronously and returns query results if the query completes within a
* specified timeout. (jobs.query)
*
* @param string $projectId Project ID of the project billed for the query
* @param QueryRequest $postBody
* @return QueryResponse
*/
public function query($projectId, QueryRequest $postBody, $optParams = array()) {
$params = array('projectId' => $projectId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('query', array($params));
if ($this->useObjects()) {
return new QueryResponse($data);
} else {
return $data;
}
}
/**
* Retrieves the results of a query job. (jobs.getQueryResults)
*
* @param string $projectId Project ID of the query job
* @param string $jobId Job ID of the query job
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string timeoutMs How long to wait for the query to complete, in milliseconds, before returning. Default is to return immediately. If the timeout passes before the job completes, the request will fail with a TIMEOUT error
* @opt_param string startIndex Zero-based index of the starting row
* @opt_param string maxResults Maximum number of results to read
* @return GetQueryResultsResponse
*/
public function getQueryResults($projectId, $jobId, $optParams = array()) {
$params = array('projectId' => $projectId, 'jobId' => $jobId);
$params = array_merge($params, $optParams);
$data = $this->__call('getQueryResults', array($params));
if ($this->useObjects()) {
return new GetQueryResultsResponse($data);
} else {
return $data;
}
}
/**
* Deletes a completed job specified by job ID. (jobs.delete)
*
* @param string $projectId Project ID of the job to delete
* @param string $jobId Job ID of the job to delete
*/
public function delete($projectId, $jobId, $optParams = array()) {
$params = array('projectId' => $projectId, 'jobId' => $jobId);
$params = array_merge($params, $optParams);
$data = $this->__call('delete', array($params));
return $data;
}
}
/**
* The "tabledata" collection of methods.
* Typical usage is:
* <code>
* $bigqueryService = new apiBigqueryService(...);
* $tabledata = $bigqueryService->tabledata;
* </code>
*/
class TabledataServiceResource extends apiServiceResource {
/**
* Retrieves table data from a specified set of rows. (tabledata.list)
*
* @param string $projectId Project ID of the table to read
* @param string $datasetId Dataset ID of the table to read
* @param string $tableId Table ID of the table to read
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string startIndex Zero-based index of the starting row to read
* @opt_param string maxResults Maximum number of results to return
* @return TableDataList
*/
public function listTabledata($projectId, $datasetId, $tableId, $optParams = array()) {
$params = array('projectId' => $projectId, 'datasetId' => $datasetId, 'tableId' => $tableId);
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new TableDataList($data);
} else {
return $data;
}
}
}
/**
* The "projects" collection of methods.
* Typical usage is:
* <code>
* $bigqueryService = new apiBigqueryService(...);
* $projects = $bigqueryService->projects;
* </code>
*/
class ProjectsServiceResource extends apiServiceResource {
/**
* Lists the projects to which you have at least read access. (projects.list)
*
* @param array $optParams Optional parameters. Valid optional parameters are listed below.
*
* @opt_param string pageToken Page token, returned by a previous call, to request the next page of results
* @opt_param string maxResults Maximum number of results to return
* @return ProjectList
*/
public function listProjects($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) {
return new ProjectList($data);
} else {
return $data;
}
}
}
/**
* Service definition for Bigquery (v2).
*
* <p>
* A data platform for customers to create, manage, share and query data.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://code.google.com/apis/bigquery/docs/v2/" target="_blank">API Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class apiBigqueryService extends apiService {
public $tables;
public $datasets;
public $jobs;
public $tabledata;
public $projects;
/**
* Constructs the internal representation of the Bigquery service.
*
* @param apiClient apiClient
*/
public function __construct(apiClient $apiClient) {
$this->rpcPath = '/rpc';
$this->restBasePath = '/bigquery/v2/';
$this->version = 'v2';
$this->serviceName = 'bigquery';
$apiClient->addService($this->serviceName, $this->version);
$this->tables = new TablesServiceResource($this, $this->serviceName, 'tables', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"type": "string", "location": "path"}, "datasetId": {"type": "string", "location": "path"}}, "request": {"$ref": "Table"}, "id": "bigquery.tables.insert", "httpMethod": "POST", "path": "projects/{projectId}/datasets/{datasetId}/tables", "response": {"$ref": "Table"}}, "get": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.tables.get", "httpMethod": "GET", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", "response": {"$ref": "Table"}}, "list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "datasetId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}, "projectId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.tables.list", "httpMethod": "GET", "path": "projects/{projectId}/datasets/{datasetId}/tables", "response": {"$ref": "TableList"}}, "update": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"type": "string", "location": "path"}, "tableId": {"type": "string", "location": "path"}, "datasetId": {"type": "string", "location": "path"}}, "request": {"$ref": "Table"}, "id": "bigquery.tables.update", "httpMethod": "PUT", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", "response": {"$ref": "Table"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Table"}, "id": "bigquery.tables.patch", "httpMethod": "PATCH", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", "response": {"$ref": "Table"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}", "id": "bigquery.tables.delete"}}}', true));
$this->datasets = new DatasetsServiceResource($this, $this->serviceName, 'datasets', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"type": "string", "location": "path"}}, "request": {"$ref": "Dataset"}, "id": "bigquery.datasets.insert", "httpMethod": "POST", "path": "projects/{projectId}/datasets", "response": {"$ref": "Dataset"}}, "get": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.datasets.get", "httpMethod": "GET", "path": "projects/{projectId}/datasets/{datasetId}", "response": {"$ref": "Dataset"}}, "list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}, "projectId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.datasets.list", "httpMethod": "GET", "path": "projects/{projectId}/datasets", "response": {"$ref": "DatasetList"}}, "update": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"type": "string", "location": "path"}, "datasetId": {"type": "string", "location": "path"}}, "request": {"$ref": "Dataset"}, "id": "bigquery.datasets.update", "httpMethod": "PUT", "path": "projects/{projectId}/datasets/{datasetId}", "response": {"$ref": "Dataset"}}, "patch": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "Dataset"}, "id": "bigquery.datasets.patch", "httpMethod": "PATCH", "path": "projects/{projectId}/datasets/{datasetId}", "response": {"$ref": "Dataset"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"deleteContents": {"type": "boolean", "location": "query"}, "datasetId": {"required": true, "type": "string", "location": "path"}, "projectId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "projects/{projectId}/datasets/{datasetId}", "id": "bigquery.datasets.delete"}}}', true));
$this->jobs = new JobsServiceResource($this, $this->serviceName, 'jobs', json_decode('{"methods": {"insert": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"type": "string", "location": "path"}}, "mediaUpload": {"accept": ["application/octet-stream"], "protocols": {"simple": {"path": "/upload/bigquery/v2/projects/{projectId}/jobs", "multipart": true}, "resumable": {"path": "/resumable/upload/bigquery/v2/projects/{projectId}/jobs", "multipart": true}}}, "request": {"$ref": "Job"}, "id": "bigquery.jobs.insert", "httpMethod": "POST", "path": "projects/{projectId}/jobs", "response": {"$ref": "Job"}}, "get": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "jobId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.jobs.get", "httpMethod": "GET", "path": "projects/{projectId}/jobs/{jobId}", "response": {"$ref": "Job"}}, "list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projection": {"enum": ["full", "minimal"], "type": "string", "location": "query"}, "stateFilter": {"enum": ["done", "pending", "running"], "repeated": true, "location": "query", "type": "string"}, "projectId": {"required": true, "type": "string", "location": "path"}, "allUsers": {"type": "boolean", "location": "query"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}, "pageToken": {"type": "string", "location": "query"}}, "id": "bigquery.jobs.list", "httpMethod": "GET", "path": "projects/{projectId}/jobs", "response": {"$ref": "JobList"}}, "query": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}}, "request": {"$ref": "QueryRequest"}, "id": "bigquery.jobs.query", "httpMethod": "POST", "path": "projects/{projectId}/queries", "response": {"$ref": "QueryResponse"}}, "getQueryResults": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"timeoutMs": {"format": "uint32", "type": "integer", "location": "query"}, "projectId": {"required": true, "type": "string", "location": "path"}, "startIndex": {"format": "uint64", "type": "string", "location": "query"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}, "jobId": {"required": true, "type": "string", "location": "path"}}, "id": "bigquery.jobs.getQueryResults", "httpMethod": "GET", "path": "projects/{projectId}/queries/{jobId}", "response": {"$ref": "GetQueryResultsResponse"}}, "delete": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "jobId": {"required": true, "type": "string", "location": "path"}}, "httpMethod": "DELETE", "path": "projects/{projectId}/jobs/{jobId}", "id": "bigquery.jobs.delete"}}}', true));
$this->tabledata = new TabledataServiceResource($this, $this->serviceName, 'tabledata', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"projectId": {"required": true, "type": "string", "location": "path"}, "startIndex": {"format": "uint64", "type": "string", "location": "query"}, "tableId": {"required": true, "type": "string", "location": "path"}, "datasetId": {"required": true, "type": "string", "location": "path"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}}, "id": "bigquery.tabledata.list", "httpMethod": "GET", "path": "projects/{projectId}/datasets/{datasetId}/tables/{tableId}/data", "response": {"$ref": "TableDataList"}}}}', true));
$this->projects = new ProjectsServiceResource($this, $this->serviceName, 'projects', json_decode('{"methods": {"list": {"scopes": ["https://www.googleapis.com/auth/bigquery"], "parameters": {"pageToken": {"type": "string", "location": "query"}, "maxResults": {"format": "uint32", "type": "integer", "location": "query"}}, "response": {"$ref": "ProjectList"}, "httpMethod": "GET", "path": "projects", "id": "bigquery.projects.list"}}}', true));
}
}
class Dataset extends apiModel {
public $kind;
public $description;
protected $__datasetReferenceType = 'DatasetReference';
protected $__datasetReferenceDataType = '';
public $datasetReference;
public $creationTime;
protected $__accessType = 'DatasetAccess';
protected $__accessDataType = 'array';
public $access;
public $etag;
public $friendlyName;
public $lastModifiedTime;
public $id;
public $selfLink;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setDatasetReference(DatasetReference $datasetReference) {
$this->datasetReference = $datasetReference;
}
public function getDatasetReference() {
return $this->datasetReference;
}
public function setCreationTime($creationTime) {
$this->creationTime = $creationTime;
}
public function getCreationTime() {
return $this->creationTime;
}
public function setAccess(/* array(DatasetAccess) */ $access) {
$this->assertIsArray($access, 'DatasetAccess', __METHOD__);
$this->access = $access;
}
public function getAccess() {
return $this->access;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setFriendlyName($friendlyName) {
$this->friendlyName = $friendlyName;
}
public function getFriendlyName() {
return $this->friendlyName;
}
public function setLastModifiedTime($lastModifiedTime) {
$this->lastModifiedTime = $lastModifiedTime;
}
public function getLastModifiedTime() {
return $this->lastModifiedTime;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class DatasetAccess extends apiModel {
public $specialGroup;
public $domain;
public $role;
public $groupByEmail;
public $userByEmail;
public function setSpecialGroup($specialGroup) {
$this->specialGroup = $specialGroup;
}
public function getSpecialGroup() {
return $this->specialGroup;
}
public function setDomain($domain) {
$this->domain = $domain;
}
public function getDomain() {
return $this->domain;
}
public function setRole($role) {
$this->role = $role;
}
public function getRole() {
return $this->role;
}
public function setGroupByEmail($groupByEmail) {
$this->groupByEmail = $groupByEmail;
}
public function getGroupByEmail() {
return $this->groupByEmail;
}
public function setUserByEmail($userByEmail) {
$this->userByEmail = $userByEmail;
}
public function getUserByEmail() {
return $this->userByEmail;
}
}
class DatasetList extends apiModel {
public $nextPageToken;
public $kind;
protected $__datasetsType = 'DatasetListDatasets';
protected $__datasetsDataType = 'array';
public $datasets;
public $etag;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDatasets(/* array(DatasetListDatasets) */ $datasets) {
$this->assertIsArray($datasets, 'DatasetListDatasets', __METHOD__);
$this->datasets = $datasets;
}
public function getDatasets() {
return $this->datasets;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
}
class DatasetListDatasets extends apiModel {
public $friendlyName;
public $kind;
public $id;
protected $__datasetReferenceType = 'DatasetReference';
protected $__datasetReferenceDataType = '';
public $datasetReference;
public function setFriendlyName($friendlyName) {
$this->friendlyName = $friendlyName;
}
public function getFriendlyName() {
return $this->friendlyName;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setDatasetReference(DatasetReference $datasetReference) {
$this->datasetReference = $datasetReference;
}
public function getDatasetReference() {
return $this->datasetReference;
}
}
class DatasetReference extends apiModel {
public $projectId;
public $datasetId;
public function setProjectId($projectId) {
$this->projectId = $projectId;
}
public function getProjectId() {
return $this->projectId;
}
public function setDatasetId($datasetId) {
$this->datasetId = $datasetId;
}
public function getDatasetId() {
return $this->datasetId;
}
}
class ErrorProto extends apiModel {
public $debugInfo;
public $message;
public $reason;
public $location;
public function setDebugInfo($debugInfo) {
$this->debugInfo = $debugInfo;
}
public function getDebugInfo() {
return $this->debugInfo;
}
public function setMessage($message) {
$this->message = $message;
}
public function getMessage() {
return $this->message;
}
public function setReason($reason) {
$this->reason = $reason;
}
public function getReason() {
return $this->reason;
}
public function setLocation($location) {
$this->location = $location;
}
public function getLocation() {
return $this->location;
}
}
class GetQueryResultsResponse extends apiModel {
public $kind;
protected $__rowsType = 'TableRow';
protected $__rowsDataType = 'array';
public $rows;
protected $__jobReferenceType = 'JobReference';
protected $__jobReferenceDataType = '';
public $jobReference;
public $jobComplete;
public $totalRows;
public $etag;
protected $__schemaType = 'TableSchema';
protected $__schemaDataType = '';
public $schema;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setRows(/* array(TableRow) */ $rows) {
$this->assertIsArray($rows, 'TableRow', __METHOD__);
$this->rows = $rows;
}
public function getRows() {
return $this->rows;
}
public function setJobReference(JobReference $jobReference) {
$this->jobReference = $jobReference;
}
public function getJobReference() {
return $this->jobReference;
}
public function setJobComplete($jobComplete) {
$this->jobComplete = $jobComplete;
}
public function getJobComplete() {
return $this->jobComplete;
}
public function setTotalRows($totalRows) {
$this->totalRows = $totalRows;
}
public function getTotalRows() {
return $this->totalRows;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setSchema(TableSchema $schema) {
$this->schema = $schema;
}
public function getSchema() {
return $this->schema;
}
}
class Job extends apiModel {
protected $__statusType = 'JobStatus';
protected $__statusDataType = '';
public $status;
public $kind;
protected $__statisticsType = 'JobStatistics';
protected $__statisticsDataType = '';
public $statistics;
protected $__jobReferenceType = 'JobReference';
protected $__jobReferenceDataType = '';
public $jobReference;
public $etag;
protected $__configurationType = 'JobConfiguration';
protected $__configurationDataType = '';
public $configuration;
public $id;
public $selfLink;
public function setStatus(JobStatus $status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setStatistics(JobStatistics $statistics) {
$this->statistics = $statistics;
}
public function getStatistics() {
return $this->statistics;
}
public function setJobReference(JobReference $jobReference) {
$this->jobReference = $jobReference;
}
public function getJobReference() {
return $this->jobReference;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setConfiguration(JobConfiguration $configuration) {
$this->configuration = $configuration;
}
public function getConfiguration() {
return $this->configuration;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
}
class JobConfiguration extends apiModel {
protected $__loadType = 'JobConfigurationLoad';
protected $__loadDataType = '';
public $load;
protected $__linkType = 'JobConfigurationLink';
protected $__linkDataType = '';
public $link;
protected $__queryType = 'JobConfigurationQuery';
protected $__queryDataType = '';
public $query;
protected $__copyType = 'JobConfigurationTableCopy';
protected $__copyDataType = '';
public $copy;
protected $__extractType = 'JobConfigurationExtract';
protected $__extractDataType = '';
public $extract;
public $properties;
public function setLoad(JobConfigurationLoad $load) {
$this->load = $load;
}
public function getLoad() {
return $this->load;
}
public function setLink(JobConfigurationLink $link) {
$this->link = $link;
}
public function getLink() {
return $this->link;
}
public function setQuery(JobConfigurationQuery $query) {
$this->query = $query;
}
public function getQuery() {
return $this->query;
}
public function setCopy(JobConfigurationTableCopy $copy) {
$this->copy = $copy;
}
public function getCopy() {
return $this->copy;
}
public function setExtract(JobConfigurationExtract $extract) {
$this->extract = $extract;
}
public function getExtract() {
return $this->extract;
}
public function setProperties($properties) {
$this->properties = $properties;
}
public function getProperties() {
return $this->properties;
}
}
class JobConfigurationExtract extends apiModel {
public $destinationUri;
protected $__sourceTableType = 'TableReference';
protected $__sourceTableDataType = '';
public $sourceTable;
public function setDestinationUri($destinationUri) {
$this->destinationUri = $destinationUri;
}
public function getDestinationUri() {
return $this->destinationUri;
}
public function setSourceTable(TableReference $sourceTable) {
$this->sourceTable = $sourceTable;
}
public function getSourceTable() {
return $this->sourceTable;
}
}
class JobConfigurationLink extends apiModel {
public $createDisposition;
protected $__destinationTableType = 'TableReference';
protected $__destinationTableDataType = '';
public $destinationTable;
public $sourceUri;
public function setCreateDisposition($createDisposition) {
$this->createDisposition = $createDisposition;
}
public function getCreateDisposition() {
return $this->createDisposition;
}
public function setDestinationTable(TableReference $destinationTable) {
$this->destinationTable = $destinationTable;
}
public function getDestinationTable() {
return $this->destinationTable;
}
public function setSourceUri($sourceUri) {
$this->sourceUri = $sourceUri;
}
public function getSourceUri() {
return $this->sourceUri;
}
}
class JobConfigurationLoad extends apiModel {
public $encoding;
public $fieldDelimiter;
protected $__destinationTableType = 'TableReference';
protected $__destinationTableDataType = '';
public $destinationTable;
public $maxBadRecords;
public $writeDisposition;
public $sourceUris;
public $skipLeadingRows;
public $createDisposition;
protected $__schemaType = 'TableSchema';
protected $__schemaDataType = '';
public $schema;
public function setEncoding($encoding) {
$this->encoding = $encoding;
}
public function getEncoding() {
return $this->encoding;
}
public function setFieldDelimiter($fieldDelimiter) {
$this->fieldDelimiter = $fieldDelimiter;
}
public function getFieldDelimiter() {
return $this->fieldDelimiter;
}
public function setDestinationTable(TableReference $destinationTable) {
$this->destinationTable = $destinationTable;
}
public function getDestinationTable() {
return $this->destinationTable;
}
public function setMaxBadRecords($maxBadRecords) {
$this->maxBadRecords = $maxBadRecords;
}
public function getMaxBadRecords() {
return $this->maxBadRecords;
}
public function setWriteDisposition($writeDisposition) {
$this->writeDisposition = $writeDisposition;
}
public function getWriteDisposition() {
return $this->writeDisposition;
}
public function setSourceUris(/* array(string) */ $sourceUris) {
$this->assertIsArray($sourceUris, 'string', __METHOD__);
$this->sourceUris = $sourceUris;
}
public function getSourceUris() {
return $this->sourceUris;
}
public function setSkipLeadingRows($skipLeadingRows) {
$this->skipLeadingRows = $skipLeadingRows;
}
public function getSkipLeadingRows() {
return $this->skipLeadingRows;
}
public function setCreateDisposition($createDisposition) {
$this->createDisposition = $createDisposition;
}
public function getCreateDisposition() {
return $this->createDisposition;
}
public function setSchema(TableSchema $schema) {
$this->schema = $schema;
}
public function getSchema() {
return $this->schema;
}
}
class JobConfigurationQuery extends apiModel {
public $createDisposition;
public $query;
public $writeDisposition;
protected $__destinationTableType = 'TableReference';
protected $__destinationTableDataType = '';
public $destinationTable;
protected $__defaultDatasetType = 'DatasetReference';
protected $__defaultDatasetDataType = '';
public $defaultDataset;
public function setCreateDisposition($createDisposition) {
$this->createDisposition = $createDisposition;
}
public function getCreateDisposition() {
return $this->createDisposition;
}
public function setQuery($query) {
$this->query = $query;
}
public function getQuery() {
return $this->query;
}
public function setWriteDisposition($writeDisposition) {
$this->writeDisposition = $writeDisposition;
}
public function getWriteDisposition() {
return $this->writeDisposition;
}
public function setDestinationTable(TableReference $destinationTable) {
$this->destinationTable = $destinationTable;
}
public function getDestinationTable() {
return $this->destinationTable;
}
public function setDefaultDataset(DatasetReference $defaultDataset) {
$this->defaultDataset = $defaultDataset;
}
public function getDefaultDataset() {
return $this->defaultDataset;
}
}
class JobConfigurationTableCopy extends apiModel {
public $createDisposition;
public $writeDisposition;
protected $__destinationTableType = 'TableReference';
protected $__destinationTableDataType = '';
public $destinationTable;
protected $__sourceTableType = 'TableReference';
protected $__sourceTableDataType = '';
public $sourceTable;
public function setCreateDisposition($createDisposition) {
$this->createDisposition = $createDisposition;
}
public function getCreateDisposition() {
return $this->createDisposition;
}
public function setWriteDisposition($writeDisposition) {
$this->writeDisposition = $writeDisposition;
}
public function getWriteDisposition() {
return $this->writeDisposition;
}
public function setDestinationTable(TableReference $destinationTable) {
$this->destinationTable = $destinationTable;
}
public function getDestinationTable() {
return $this->destinationTable;
}
public function setSourceTable(TableReference $sourceTable) {
$this->sourceTable = $sourceTable;
}
public function getSourceTable() {
return $this->sourceTable;
}
}
class JobList extends apiModel {
public $nextPageToken;
public $totalItems;
public $kind;
public $etag;
protected $__jobsType = 'JobListJobs';
protected $__jobsDataType = 'array';
public $jobs;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setJobs(/* array(JobListJobs) */ $jobs) {
$this->assertIsArray($jobs, 'JobListJobs', __METHOD__);
$this->jobs = $jobs;
}
public function getJobs() {
return $this->jobs;
}
}
class JobListJobs extends apiModel {
protected $__statusType = 'JobStatus';
protected $__statusDataType = '';
public $status;
protected $__statisticsType = 'JobStatistics';
protected $__statisticsDataType = '';
public $statistics;
protected $__jobReferenceType = 'JobReference';
protected $__jobReferenceDataType = '';
public $jobReference;
public $state;
protected $__configurationType = 'JobConfiguration';
protected $__configurationDataType = '';
public $configuration;
public $id;
protected $__errorResultType = 'ErrorProto';
protected $__errorResultDataType = '';
public $errorResult;
public function setStatus(JobStatus $status) {
$this->status = $status;
}
public function getStatus() {
return $this->status;
}
public function setStatistics(JobStatistics $statistics) {
$this->statistics = $statistics;
}
public function getStatistics() {
return $this->statistics;
}
public function setJobReference(JobReference $jobReference) {
$this->jobReference = $jobReference;
}
public function getJobReference() {
return $this->jobReference;
}
public function setState($state) {
$this->state = $state;
}
public function getState() {
return $this->state;
}
public function setConfiguration(JobConfiguration $configuration) {
$this->configuration = $configuration;
}
public function getConfiguration() {
return $this->configuration;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setErrorResult(ErrorProto $errorResult) {
$this->errorResult = $errorResult;
}
public function getErrorResult() {
return $this->errorResult;
}
}
class JobReference extends apiModel {
public $projectId;
public $jobId;
public function setProjectId($projectId) {
$this->projectId = $projectId;
}
public function getProjectId() {
return $this->projectId;
}
public function setJobId($jobId) {
$this->jobId = $jobId;
}
public function getJobId() {
return $this->jobId;
}
}
class JobStatistics extends apiModel {
public $endTime;
public $totalBytesProcessed;
public $startTime;
public function setEndTime($endTime) {
$this->endTime = $endTime;
}
public function getEndTime() {
return $this->endTime;
}
public function setTotalBytesProcessed($totalBytesProcessed) {
$this->totalBytesProcessed = $totalBytesProcessed;
}
public function getTotalBytesProcessed() {
return $this->totalBytesProcessed;
}
public function setStartTime($startTime) {
$this->startTime = $startTime;
}
public function getStartTime() {
return $this->startTime;
}
}
class JobStatus extends apiModel {
public $state;
protected $__errorsType = 'ErrorProto';
protected $__errorsDataType = 'array';
public $errors;
protected $__errorResultType = 'ErrorProto';
protected $__errorResultDataType = '';
public $errorResult;
public function setState($state) {
$this->state = $state;
}
public function getState() {
return $this->state;
}
public function setErrors(/* array(ErrorProto) */ $errors) {
$this->assertIsArray($errors, 'ErrorProto', __METHOD__);
$this->errors = $errors;
}
public function getErrors() {
return $this->errors;
}
public function setErrorResult(ErrorProto $errorResult) {
$this->errorResult = $errorResult;
}
public function getErrorResult() {
return $this->errorResult;
}
}
class ProjectList extends apiModel {
public $nextPageToken;
public $totalItems;
public $kind;
public $etag;
protected $__projectsType = 'ProjectListProjects';
protected $__projectsDataType = 'array';
public $projects;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setProjects(/* array(ProjectListProjects) */ $projects) {
$this->assertIsArray($projects, 'ProjectListProjects', __METHOD__);
$this->projects = $projects;
}
public function getProjects() {
return $this->projects;
}
}
class ProjectListProjects extends apiModel {
public $friendlyName;
public $kind;
public $id;
protected $__projectReferenceType = 'ProjectReference';
protected $__projectReferenceDataType = '';
public $projectReference;
public function setFriendlyName($friendlyName) {
$this->friendlyName = $friendlyName;
}
public function getFriendlyName() {
return $this->friendlyName;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setProjectReference(ProjectReference $projectReference) {
$this->projectReference = $projectReference;
}
public function getProjectReference() {
return $this->projectReference;
}
}
class ProjectReference extends apiModel {
public $projectId;
public function setProjectId($projectId) {
$this->projectId = $projectId;
}
public function getProjectId() {
return $this->projectId;
}
}
class QueryRequest extends apiModel {
public $timeoutMs;
public $query;
public $kind;
public $maxResults;
protected $__defaultDatasetType = 'DatasetReference';
protected $__defaultDatasetDataType = '';
public $defaultDataset;
public function setTimeoutMs($timeoutMs) {
$this->timeoutMs = $timeoutMs;
}
public function getTimeoutMs() {
return $this->timeoutMs;
}
public function setQuery($query) {
$this->query = $query;
}
public function getQuery() {
return $this->query;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setMaxResults($maxResults) {
$this->maxResults = $maxResults;
}
public function getMaxResults() {
return $this->maxResults;
}
public function setDefaultDataset(DatasetReference $defaultDataset) {
$this->defaultDataset = $defaultDataset;
}
public function getDefaultDataset() {
return $this->defaultDataset;
}
}
class QueryResponse extends apiModel {
public $kind;
protected $__rowsType = 'TableRow';
protected $__rowsDataType = 'array';
public $rows;
protected $__jobReferenceType = 'JobReference';
protected $__jobReferenceDataType = '';
public $jobReference;
public $jobComplete;
public $totalRows;
protected $__schemaType = 'TableSchema';
protected $__schemaDataType = '';
public $schema;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setRows(/* array(TableRow) */ $rows) {
$this->assertIsArray($rows, 'TableRow', __METHOD__);
$this->rows = $rows;
}
public function getRows() {
return $this->rows;
}
public function setJobReference(JobReference $jobReference) {
$this->jobReference = $jobReference;
}
public function getJobReference() {
return $this->jobReference;
}
public function setJobComplete($jobComplete) {
$this->jobComplete = $jobComplete;
}
public function getJobComplete() {
return $this->jobComplete;
}
public function setTotalRows($totalRows) {
$this->totalRows = $totalRows;
}
public function getTotalRows() {
return $this->totalRows;
}
public function setSchema(TableSchema $schema) {
$this->schema = $schema;
}
public function getSchema() {
return $this->schema;
}
}
class Table extends apiModel {
public $kind;
public $description;
public $creationTime;
protected $__tableReferenceType = 'TableReference';
protected $__tableReferenceDataType = '';
public $tableReference;
public $etag;
public $friendlyName;
public $lastModifiedTime;
public $id;
public $selfLink;
protected $__schemaType = 'TableSchema';
protected $__schemaDataType = '';
public $schema;
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
public function setCreationTime($creationTime) {
$this->creationTime = $creationTime;
}
public function getCreationTime() {
return $this->creationTime;
}
public function setTableReference(TableReference $tableReference) {
$this->tableReference = $tableReference;
}
public function getTableReference() {
return $this->tableReference;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setFriendlyName($friendlyName) {
$this->friendlyName = $friendlyName;
}
public function getFriendlyName() {
return $this->friendlyName;
}
public function setLastModifiedTime($lastModifiedTime) {
$this->lastModifiedTime = $lastModifiedTime;
}
public function getLastModifiedTime() {
return $this->lastModifiedTime;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
}
public function getSelfLink() {
return $this->selfLink;
}
public function setSchema(TableSchema $schema) {
$this->schema = $schema;
}
public function getSchema() {
return $this->schema;
}
}
class TableDataList extends apiModel {
protected $__rowsType = 'TableRow';
protected $__rowsDataType = 'array';
public $rows;
public $kind;
public $etag;
public $totalRows;
public function setRows(/* array(TableRow) */ $rows) {
$this->assertIsArray($rows, 'TableRow', __METHOD__);
$this->rows = $rows;
}
public function getRows() {
return $this->rows;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setTotalRows($totalRows) {
$this->totalRows = $totalRows;
}
public function getTotalRows() {
return $this->totalRows;
}
}
class TableFieldSchema extends apiModel {
protected $__fieldsType = 'TableFieldSchema';
protected $__fieldsDataType = 'array';
public $fields;
public $type;
public $mode;
public $name;
public function setFields(/* array(TableFieldSchema) */ $fields) {
$this->assertIsArray($fields, 'TableFieldSchema', __METHOD__);
$this->fields = $fields;
}
public function getFields() {
return $this->fields;
}
public function setType($type) {
$this->type = $type;
}
public function getType() {
return $this->type;
}
public function setMode($mode) {
$this->mode = $mode;
}
public function getMode() {
return $this->mode;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
class TableList extends apiModel {
public $nextPageToken;
protected $__tablesType = 'TableListTables';
protected $__tablesDataType = 'array';
public $tables;
public $kind;
public $etag;
public $totalItems;
public function setNextPageToken($nextPageToken) {
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken() {
return $this->nextPageToken;
}
public function setTables(/* array(TableListTables) */ $tables) {
$this->assertIsArray($tables, 'TableListTables', __METHOD__);
$this->tables = $tables;
}
public function getTables() {
return $this->tables;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setEtag($etag) {
$this->etag = $etag;
}
public function getEtag() {
return $this->etag;
}
public function setTotalItems($totalItems) {
$this->totalItems = $totalItems;
}
public function getTotalItems() {
return $this->totalItems;
}
}
class TableListTables extends apiModel {
public $friendlyName;
public $kind;
public $id;
protected $__tableReferenceType = 'TableReference';
protected $__tableReferenceDataType = '';
public $tableReference;
public function setFriendlyName($friendlyName) {
$this->friendlyName = $friendlyName;
}
public function getFriendlyName() {
return $this->friendlyName;
}
public function setKind($kind) {
$this->kind = $kind;
}
public function getKind() {
return $this->kind;
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setTableReference(TableReference $tableReference) {
$this->tableReference = $tableReference;
}
public function getTableReference() {
return $this->tableReference;
}
}
class TableReference extends apiModel {
public $projectId;
public $tableId;
public $datasetId;
public function setProjectId($projectId) {
$this->projectId = $projectId;
}
public function getProjectId() {
return $this->projectId;
}
public function setTableId($tableId) {
$this->tableId = $tableId;
}
public function getTableId() {
return $this->tableId;
}
public function setDatasetId($datasetId) {
$this->datasetId = $datasetId;
}
public function getDatasetId() {
return $this->datasetId;
}
}
class TableRow extends apiModel {
protected $__fType = 'TableRowF';
protected $__fDataType = 'array';
public $f;
public function setF(/* array(TableRowF) */ $f) {
$this->assertIsArray($f, 'TableRowF', __METHOD__);
$this->f = $f;
}
public function getF() {
return $this->f;
}
}
class TableRowF extends apiModel {
public $v;
public function setV($v) {
$this->v = $v;
}
public function getV() {
return $this->v;
}
}
class TableSchema extends apiModel {
protected $__fieldsType = 'TableFieldSchema';
protected $__fieldsDataType = 'array';
public $fields;
public function setFields(/* array(TableFieldSchema) */ $fields) {
$this->assertIsArray($fields, 'TableFieldSchema', __METHOD__);
$this->fields = $fields;
}
public function getFields() {
return $this->fields;
}
}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/contrib/apiBigqueryService.php | PHP | asf20 | 60,611 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Check for the required json and curl extensions, the Google API PHP Client won't function without them.
if (! function_exists('curl_init')) {
throw new Exception('Google PHP API Client requires the CURL PHP extension');
}
if (! function_exists('json_decode')) {
throw new Exception('Google PHP API Client requires the JSON PHP extension');
}
if (! function_exists('http_build_query')) {
throw new Exception('Google PHP API Client requires http_build_query()');
}
if (! ini_get('date.timezone') && function_exists('date_default_timezone_set')) {
date_default_timezone_set('UTC');
}
// hack around with the include paths a bit so the library 'just works'
$cwd = dirname(__FILE__);
set_include_path("$cwd" . PATH_SEPARATOR . get_include_path());
require_once "config.php";
// If a local configuration file is found, merge it's values with the default configuration
if (file_exists($cwd . '/local_config.php')) {
$defaultConfig = $apiConfig;
require_once ($cwd . '/local_config.php');
$apiConfig = array_merge($defaultConfig, $apiConfig);
}
// Include the top level classes, they each include their own dependencies
require_once 'service/apiModel.php';
require_once 'service/apiService.php';
require_once 'service/apiServiceRequest.php';
require_once 'auth/apiAuth.php';
require_once 'cache/apiCache.php';
require_once 'io/apiIO.php';
require_once('service/apiMediaFileUpload.php');
/**
* The Google API Client
* http://code.google.com/p/google-api-php-client/
*
* @author Chris Chabot <chabotc@google.com>
* @author Chirag Shah <chirags@google.com>
*/
class apiClient {
// the version of the discovery mechanism this class is meant to work with
const discoveryVersion = 'v0.3';
/**
* @static
* @var apiAuth $auth
*/
static $auth;
/** @var apiIo $io */
static $io;
/** @var apiCache $cache */
static $cache;
/** @var array $scopes */
protected $scopes = array();
/** @var bool $useObjects */
protected $useObjects = false;
// definitions of services that are discovered.
protected $services = array();
// Used to track authenticated state, can't discover services after doing authenticate()
private $authenticated = false;
private $defaultService = array(
'authorization_token_url' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
'request_token_url' => 'https://www.google.com/accounts/OAuthGetRequestToken',
'access_token_url' => 'https://www.google.com/accounts/OAuthGetAccessToken');
public function __construct($config = array()) {
global $apiConfig;
$apiConfig = array_merge($apiConfig, $config);
self::$cache = new $apiConfig['cacheClass']();
self::$auth = new $apiConfig['authClass']();
self::$io = new $apiConfig['ioClass']();
}
public function discover($service, $version = 'v1') {
$this->addService($service, $version);
$this->$service = $this->discoverService($service, $this->services[$service]['discoveryURI']);
return $this->$service;
}
/**
* Add a service
*/
public function addService($service, $version) {
global $apiConfig;
if ($this->authenticated) {
// Adding services after being authenticated, since the oauth scope is already set (so you wouldn't have access to that data)
throw new apiException('Cant add services after having authenticated');
}
$this->services[$service] = $this->defaultService;
if (isset($apiConfig['services'][$service])) {
// Merge the service descriptor with the default values
$this->services[$service] = array_merge($this->services[$service], $apiConfig['services'][$service]);
}
$this->services[$service]['discoveryURI'] = $apiConfig['basePath'] . '/discovery/' . self::discoveryVersion . '/describe/' . urlencode($service) . '/' . urlencode($version);
}
/**
* Set the type of Auth class the client should use.
* @param string $authClassName
*/
public function setAuthClass($authClassName) {
self::$auth = new $authClassName();
}
public function authenticate() {
$service = $this->prepareService();
$this->authenticated = true;
return self::$auth->authenticate($service);
}
/**
* Construct the OAuth 2.0 authorization request URI.
* @return string
*/
public function createAuthUrl() {
$service = $this->prepareService();
return self::$auth->createAuthUrl($service['scope']);
}
private function prepareService() {
$service = $this->defaultService;
$scopes = array();
if ($this->scopes) {
$scopes = $this->scopes;
} else {
foreach ($this->services as $key => $val) {
if (isset($val['scope'])) {
if (is_array($val['scope'])) {
$scopes = array_merge($val['scope'], $scopes);
} else {
$scopes[] = $val['scope'];
}
} else {
$scopes[] = 'https://www.googleapis.com/auth/' . $key;
}
unset($val['discoveryURI']);
unset($val['scope']);
$service = array_merge($service, $val);
}
}
$service['scope'] = implode(' ', $scopes);
return $service;
}
/**
* Set the OAuth 2.0 access token using the string that resulted from calling authenticate()
* or apiClient#getAccessToken().
* @param string $accessToken JSON encoded string containing in the following format:
* {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
* "expires_in":3600, "id_token":"TOKEN", "created":1320790426}
*/
public function setAccessToken($accessToken) {
if ($accessToken == null || 'null' == $accessToken) {
$accessToken = null;
}
self::$auth->setAccessToken($accessToken);
}
/**
* Get the OAuth 2.0 access token.
* @return string $accessToken JSON encoded string in the following format:
* {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
* "expires_in":3600,"id_token":"TOKEN", "created":1320790426}
*/
public function getAccessToken() {
$token = self::$auth->getAccessToken();
return (null == $token || 'null' == $token) ? null : $token;
}
/**
* Set the developer key to use, these are obtained through the API Console.
* @see http://code.google.com/apis/console-help/#generatingdevkeys
* @param string $developerKey
*/
public function setDeveloperKey($developerKey) {
self::$auth->setDeveloperKey($developerKey);
}
/**
* Set OAuth 2.0 "state" parameter to achieve per-request customization.
* @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
* @param string $state
*/
public function setState($state) {
self::$auth->setState($state);
}
/**
* @param string $accessType Possible values for access_type include:
* {@code "offline"} to request offline access from the user. (This is the default value)
* {@code "online"} to request online access from the user.
*/
public function setAccessType($accessType) {
self::$auth->setAccessType($accessType);
}
/**
* @param string $approvalPrompt Possible values for approval_prompt include:
* {@code "force"} to force the approval UI to appear. (This is the default value)
* {@code "auto"} to request auto-approval when possible.
*/
public function setApprovalPrompt($approvalPrompt) {
self::$auth->setApprovalPrompt($approvalPrompt);
}
/**
* Set the application name, this is included in the User-Agent HTTP header.
* @param string $applicationName
*/
public function setApplicationName($applicationName) {
global $apiConfig;
$apiConfig['application_name'] = $applicationName;
}
/**
* Set the OAuth 2.0 Client ID.
* @param string $clientId
*/
public function setClientId($clientId) {
global $apiConfig;
$apiConfig['oauth2_client_id'] = $clientId;
self::$auth->clientId = $clientId;
}
/**
* Set the OAuth 2.0 Client Secret.
* @param string $clientSecret
*/
public function setClientSecret($clientSecret) {
global $apiConfig;
$apiConfig['oauth2_client_secret'] = $clientSecret;
self::$auth->clientSecret = $clientSecret;
}
/**
* Set the OAuth 2.0 Redirect URI.
* @param string $redirectUri
*/
public function setRedirectUri($redirectUri) {
global $apiConfig;
$apiConfig['oauth2_redirect_uri'] = $redirectUri;
self::$auth->redirectUri = $redirectUri;
}
/**
* Fetches a fresh OAuth 2.0 access token with the given refresh token.
* @param string $refreshToken
* @return void
*/
public function refreshToken($refreshToken) {
self::$auth->refreshToken($refreshToken);
}
/**
* Revoke an OAuth2 access token or refresh token. This method will revoke the current access
* token, if a token isn't provided.
* @throws apiAuthException
* @param string|null $token The token (access token or a refresh token) that should be revoked.
* @return boolean Returns True if the revocation was successful, otherwise False.
*/
public function revokeToken($token = null) {
self::$auth->revokeToken($token);
}
/**
* Verify an id_token. This method will verify the current id_token, if one
* isn't provided.
* @throws apiAuthException
* @param string|null $token The token (id_token) that should be verified.
* @return apiLoginTicket Returns an apiLoginTicket if the verification was
* successful.
*/
public function verifyIdToken($token = null) {
return self::$auth->verifyIdToken($token);
}
/**
* This function allows you to overrule the automatically generated scopes,
* so that you can ask for more or less permission in the auth flow
* Set this before you call authenticate() though!
* @param array $scopes, ie: array('https://www.googleapis.com/auth/plus', 'https://www.googleapis.com/auth/moderator')
*/
public function setScopes($scopes) {
$this->scopes = is_string($scopes) ? explode(" ", $scopes) : $scopes;
}
/**
* Declare if objects should be returned by the api service classes.
*
* @param boolean $useObjects True if objects should be returned by the service classes.
* False if associative arrays should be returned (default behavior).
*/
public function setUseObjects($useObjects) {
global $apiConfig;
$apiConfig['use_objects'] = $useObjects;
}
private function discoverService($serviceName, $serviceURI) {
$request = self::$io->makeRequest(new apiHttpRequest($serviceURI));
if ($request->getResponseHttpCode() != 200) {
throw new apiException("Could not fetch discovery document for $serviceName, code: "
. $request->getResponseHttpCode() . ", response: " . $request->getResponseBody());
}
$discoveryResponse = $request->getResponseBody();
$discoveryDocument = json_decode($discoveryResponse, true);
if ($discoveryDocument == NULL) {
throw new apiException("Invalid json returned for $serviceName");
}
return new apiService($serviceName, $discoveryDocument, apiClient::getIo());
}
/**
* @static
* @return apiAuth the implementation of apiAuth.
*/
public static function getAuth() {
return apiClient::$auth;
}
/**
* @static
* @return apiIo the implementation of apiIo.
*/
public static function getIo() {
return apiClient::$io;
}
/**
* @return apiCache the implementation of apiCache.
*/
public function getCache() {
return apiClient::$cache;
}
}
// Exceptions that the Google PHP API Library can throw
class apiException extends Exception {}
class apiAuthException extends apiException {}
class apiCacheException extends apiException {}
class apiIOException extends apiException {}
class apiServiceException extends apiException {}
| zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/apiClient.php | PHP | asf20 | 12,320 |
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
global $apiConfig;
$apiConfig = array(
// True if objects should be returned by the service classes.
// False if associative arrays should be returned (default behavior).
'use_objects' => false,
// The application_name is included in the User-Agent HTTP header.
'application_name' => '',
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
'oauth2_client_id' => '',
'oauth2_client_secret' => '',
'oauth2_redirect_uri' => '',
// The developer key, you get this at https://code.google.com/apis/console
'developer_key' => '',
// OAuth1 Settings.
// If you're using the apiOAuth auth class, it will use these values for the oauth consumer key and secret.
// See http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html for info on how to obtain those
'oauth_consumer_key' => 'anonymous',
'oauth_consumer_secret' => 'anonymous',
// Site name to show in the Google's OAuth 1 authentication screen.
'site_name' => 'www.example.org',
// Which Authentication, Storage and HTTP IO classes to use.
'authClass' => 'apiOAuth2',
'ioClass' => 'apiCurlIO',
'cacheClass' => 'apiFileCache',
// If you want to run the test suite (by running # phpunit AllTests.php in the tests/ directory), fill in the settings below
'oauth_test_token' => '', // the oauth access token to use (which you can get by runing authenticate() as the test user and copying the token value), ie '{"key":"foo","secret":"bar","callback_url":null}'
'oauth_test_user' => '', // and the user ID to use, this can either be a vanity name 'testuser' or a numberic ID '123456'
// Don't change these unless you're working against a special development or testing environment.
'basePath' => 'https://www.googleapis.com',
// IO Class dependent configuration, you only have to configure the values for the class that was configured as the ioClass above
'ioFileCache_directory' =>
(function_exists('sys_get_temp_dir') ?
sys_get_temp_dir() . '/apiClient' :
'/tmp/apiClient'),
'ioMemCacheStorage_host' => '127.0.0.1',
'ioMemcacheStorage_port' => '11211',
// Definition of service specific values like scopes, oauth token URLs, etc
'services' => array(
'analytics' => array('scope' => 'https://www.googleapis.com/auth/analytics.readonly'),
'calendar' => array(
'scope' => array(
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.readonly",
)
),
'books' => array('scope' => 'https://www.googleapis.com/auth/books'),
'latitude' => array(
'scope' => array(
'https://www.googleapis.com/auth/latitude.all.best',
'https://www.googleapis.com/auth/latitude.all.city',
)
),
'moderator' => array('scope' => 'https://www.googleapis.com/auth/moderator'),
'oauth2' => array(
'scope' => array(
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
)
),
'plus' => array('scope' => 'https://www.googleapis.com/auth/plus.me'),
'siteVerification' => array('scope' => 'https://www.googleapis.com/auth/siteverification'),
'tasks' => array('scope' => 'https://www.googleapis.com/auth/tasks'),
'urlshortener' => array('scope' => 'https://www.googleapis.com/auth/urlshortener')
)
); | zzangtest123-google-drive-sdk-samples | php/libs/gd-v1-php/config.php | PHP | asf20 | 4,146 |
<?php
/**
* Model for storing OAuth credentials used for API requests and interaction
* with the OAuth authorization server.
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Model for storing OAuth credentials used for API requests and interaction
* with the OAuth authorization server. Only the access token is ever sent
* directly to API servers. The refresh token, client ID and client secret
* are sent to the OAuth authorization server to obtain access tokens.
*
* @author Ryan Boyd <rboyd@google.com>
*/
class OauthCredentials {
/**
* Access token obtained when exchanging authorization code with the OAuth
* provider.
*/
public $accessToken = '';
/**
* Time OAuth token was created.
*/
public $created = '';
/**
* Time in seconds after creation when token will expire
*/
public $expiresIn = '';
/**
* Refresh token obtained when exchanging the authorization code the first
* time, when a user explicitly approves access. When the OAuth request is
* auto-approved by Google due to a previous grant, a refresh token is not
* returned. Instead, the refresh token is looked up in the application's
* database, indexed based on the user ID returned from the Google UserInfo
* service.
*/
public $refreshToken = '';
/**
* Client ID, typically obtained from the Google APIs console at
* http://code.google.com/apis/console, and configured in the config.php
*/
public $clientId = '';
/**
* Client secret, typically obtained from the Google APIs console at
* http://code.google.com/apis/console, and configured in the config.php
*/
public $clientSecret = '';
/**
* Constructor for OauthCredentials. Sets values of member variables.
*
* @param string $accessToken Access token obtained when exchanging code
* @param string $refreshToken Refresh token obtained when 1st exchaning code
* @param int $created Time OAuth token was created
* @param int $expiresIn Time after "created" when access token will expire
* @param string $clientId OAuth client ID, obtained from APIs Console
* @param string $clientSecret OAuth client secret, obtained from APIs Console
*/
public function OauthCredentials($accessToken, $refreshToken, $created,
$expiresIn, $clientId, $clientSecret) {
$this->accessToken = $accessToken;
$this->refreshToken = $refreshToken;
$this->created = $created;
$this->expiresIn = $expiresIn;
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
}
/**
* Return JSON object representing the member variables
*
* @return string JSON string
*/
public function toJson() {
$arr = array('access_token' => $this->accessToken,
'refresh_token' => $this->refreshToken,
'created' => $this->created,
'expires_in' => $this->expiresIn,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
);
return json_encode($arr);
}
}
| zzangtest123-google-drive-sdk-samples | php/oauth_credentials.php | PHP | asf20 | 3,618 |
<?php
/**
* Handler for API requests from DrEdit PHP frontend. These requests
* retrieve, save or create files in Google Drive using pre-established
* authorization information stored in the session.
*
* @author Ryan Boyd <rboyd@google.com>
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Set configuration for client_id, client_secret and various OAuth endpoints
*/
require_once 'config.php';
/*
* Include class which handles requests to the Drive API
*/
require_once 'drive_handler.php';
/**
* Indicate the request type as a web API request. This prevents the
* authorization logic from redirecting the user in case of failures, and
* instead returns HTTP error codes for interpretation by the JavaScript.
*/
$requestType = 'webapi';
require_once 'auth_handler.php';
$authHandler = new AuthHandler($requestType);
$authHandler->VerifyAuth();
header('Content-type: application/json');
$driveHandler = new DriveHandler($_SESSION['credentials']);
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$file = $driveHandler->GetFile($_GET['file_id']);
echo $file;
} else {
/**
* This is a HTTP PUT or POST - save file back to drive
*/
$handle = fopen('php://input', 'r');
$contents = stream_get_contents($handle);
fclose($handle);
$contentData = json_decode($contents);
$newFile = $driveHandler->SaveFile($contentData->resource_id, $contentData);
echo json_encode($newFile->id);
}
| zzangtest123-google-drive-sdk-samples | php/svc.php | PHP | asf20 | 1,968 |
<?php
/**
* Include to output configuration errors.
*
* @author Ryan Boyd <rboyd@google.com>
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
echo <<<HTML
<html>
<head>
<title>Checking DrEdit Configuration</title>
<style type="text/css">
.success { color: green }
.failure {
color: white;
background-color: red;
font-weight: bold;
}
.instructions { color: darkgray }
</style>
</head>
<body>
HTML;
if (count($dbErrors) > 0) {
echo '<span class="failure">DB check failure</span> ';
echo '<ul>';
foreach ($dbErrors as $dbError) {
echo '<li>' . $dbError . '</li>';
}
echo '</ul>';
echo '<span class="instructions">';
echo "Database should be created with: <pre>";
echo "-- Script\n";
echo "-- \n";
readfile('create_db.sql');
echo "</pre>";
echo '</span></span>';
}
if (count($oauthErrors) > 0) {
echo '<span class="failure">OAuth check failure</span> ';
echo '<ul>';
foreach ($oauthErrors as $oauthError) {
echo '<li>' . $oauthError . '</li>';
}
echo '</ul>';
}
echo '</body></html>';
?>
| zzangtest123-google-drive-sdk-samples | php/output_config_errors.php | PHP | asf20 | 1,625 |
<?php
/**
* Include for web requests which ensures that all required configuration
* for DrEdit PHP is complete, including the database and OAuth config.
*
* @author Ryan Boyd <rboyd@google.com>
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once 'config.php';
/**
* Check that a database connection can be made to the database configured in
* Config::DB_PDO_CONNECT. Verify that the required fields are present in the
* database schema
*
* @return aray Array of error strings or empty if no errors
*/
function CheckDatabase() {
$errorArray = array();
try {
$dbh = new PDO(Config::DB_PDO_CONNECT,
Config::DB_PDO_USER,
Config::DB_PDO_PASSWORD);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$requiredFields = array(
'id' => false,
'first_name' => false,
'last_name' => false,
'email' => false,
'refresh_token' => false);
$selectStmt = $dbh->prepare('DESCRIBE users');
if ($selectStmt->execute()) {
while ($row = $selectStmt->fetch()) {
$fieldName = $row['Field'];
$requiredFields[ $fieldName ] = true;
}
}
foreach ($requiredFields as $requiredFieldName => $requiredFieldValue) {
if ($requiredFieldValue !== true) {
$errorArray[] = $requiredFieldName . ' is not defined in the database';
}
}
} catch (Exception $ex) {
$errorArray[] = "Cannot connect to database '" .
Config::DB_PDO_CONNECT . "'" .
". Error message: '" .
$ex->getMessage() . "'";
}
return $errorArray;
}
/**
* Check that the OAuth CLIENT_ID, CLIENT_SECRET, FULL_AUTH_URL, and
* REDIRECT_URI are configured in Config.
*
* @return aray Array of error strings or empty if no errors
*/
function CheckOauthConfig() {
$errorArray = array();
if (Config::CLIENT_ID == '') {
$errorArray[] = 'Config::CLIENT_ID must be set in config.php';
}
if (Config::CLIENT_SECRET == '') {
$errorArray[] = 'Config::CLIENT_SECRET must be set in config.php';
}
if (Config::REDIRECT_URI == '') {
$errorArray[] = 'Config::REDIRECT_URI must be set in config.php';
}
if (strpos(Config::FULL_AUTH_URL, Config::CLIENT_ID) === null) {
$errorArray[] = 'Config::FULL_AUTH_URL must be set in config.php.' .
'It must reference your Config::CLIENT_ID';
}
return $errorArray;
}
$dbErrors = CheckDatabase();
$oauthErrors = CheckOauthConfig();
if (count($dbErrors) > 0 || count($oauthErrors) > 0) {
/**
* Output the errors and stop processing
*/
include 'output_config_errors.php';
exit;
}
?>
| zzangtest123-google-drive-sdk-samples | php/check_config.php | PHP | asf20 | 3,147 |
<?php
/**
* Configuration for DrEdit PHP. Developers need to define the OAuth
* and databse configuration in constants.
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Configuration for DrEdit PHP. Developers need to define the OAuth
* and databse configuration in constants.
*
* @author Ryan Boyd <rboyd@google.com>
*/
class Config {
/**
* Define your application ID obtained from the APIs Console project.
* APIs console is accessible from https://code.google.com/apis/console. These
* values are specific for your application.
*
* Example APP_ID = '892677078282'
*/
const APP_ID = '';
/*
* Define your OAuth 2.0 configuration from APIs Console project. The
* APIs console is accessible from https://code.google.com/apis/console. These
* values are specific for your application.
*/
/**
* OAuth 2.0 client ID
*
* Example CLIENT_ID = '892677078282.apps.googleusercontent.com'
*/
const CLIENT_ID = '';
/**
* OAuth 2.0 client secret
*/
const CLIENT_SECRET = '';
/*
* Define your redirect URI. This should be the root of the web application
* where the index.php file would be served from.
*
* Example REDIRECT_URI = 'http://dredit.saasyapp.com/'
*/
const REDIRECT_URI = '';
/**
* Define the correct OAuth 2.0 authorization server URL for the application.
* This URL is where DrEdit PHP will redirect a user who arrives at the web
* UI without a valid authorization code. This will also occur when the user
* clicks on the DrEdit icon on the Chrome New Tab Page.
*
* Documentation available here: https://developers.google.com/accounts/docs/OAuth2WebServer#formingtheurl
*
* Example FULL_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/drive.file+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email&client_id=892677078282.apps.googleusercontent.com&response_type=code&access_type=offline&redirect_uri=http://dredit.saasyapp.com&state={"action":"create"}'
*
* Note: the state is set as {"action":"create"}
*/
const FULL_AUTH_URL = '';
/*
* Database configuration. Any PDO database can be used as long as minimal
* SELECT/INSERT/UPDATE SQL syntax is supported. See auth.php for queries.
*/
/**
* PDO connection string. Pre-defined value is to use a local MySQL database
* called 'dredit'.
*/
const DB_PDO_CONNECT = 'mysql:host=localhost;dbname=dredit';
/**
* PDO database username
*/
const DB_PDO_USER = '';
/**
* PDO database password
*/
const DB_PDO_PASSWORD = '';
}
| zzangtest123-google-drive-sdk-samples | php/config.php | PHP | asf20 | 3,194 |
<?php
/**
* Main entry point for web requests to the DrEdit PHP application. Checks
* authentication and authorization using auth_handler.php, checks configuration
* using check_config.php, and then spawns the output_editor.php to load the web
* interface.
*
* @author Ryan Boyd <rboyd@google.com>
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Type of request: webui, webapi
*/
$requestType = 'webui';
/*
* Set configuration for client_id, client_secret and various OAuth endpoints
*/
require_once 'config.php';
/*
* Check the configuration
*/
require_once 'check_config.php';
/*
* Perform all authorization and authentication logic - exchanging auth
* code for access token, retrieving user profile info, looking up
* pre-existing refresh token in database, updating it (if applicable),
* and more.
*/
require_once 'auth_handler.php';
$authHandler = new AuthHandler($requestType);
$authHandler->VerifyAuth();
/*
* If an authorization 'code' is set, then we assume the user came from
* Google Drive and check to see if the 'state' parameter exists, with
* the mode and potially specified file IDs (on open) or a folder parentId
* (on create).
*/
if (isset($_GET['code'])) {
/*
* State should always be defined
*/
if (isset($_GET['state'])) {
$state = json_decode(stripslashes($_GET['state']));
$_SESSION['mode'] = $state->action;
if (isset($state->ids)){
$_SESSION['fileIds'] = $state->ids;
} else {
$_SESSION['fileIds'] = array();
}
if (isset($state->parentId)) {
$_SESSION['parentId'] = $state->parentId;
} else {
$_SESSION['parentId'] = null;
}
} else {
$error = 'Code defined, but no state. Condition shouldn\'t exist.';
throw new Exception($error);
}
}
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
/*
* User information should be set in the session via auth_handler.php
*/
if (isset($_SESSION['userInfo'])) {
$userInfo = $_SESSION['userInfo'];
/*
* Retrieve the user's picture from UserInfo. Google allows
* adding an imgmax query param to the picture to get a max
* size (any any dimension) of the indicated size. Reduces
* bandwidth and improves rendering time.
*/
if ($userInfo->picture == null) {
$userPicture = null;
} else {
$userPicture = $userInfo->picture . '?imgmax=50';
}
$userName = $userInfo->given_name;
$alertModalText = $authHandler->GetAlertModalText();
include 'output_editor.php';
} else {
/*
* User came direct to app, redirect for oauth
*/
header('Location: ' . Config::FULL_AUTH_URL);
}
}
| zzangtest123-google-drive-sdk-samples | php/index.php | PHP | asf20 | 3,183 |
'use strict';
var EditorState = {
CLEAN:0, // NO CHANGES
DIRTY:1, // UNSAVED CHANGES
SAVE:2, // SAVE IN PROGRESS
LOAD:3, // LOADING
READONLY:4
};
google.load('picker', '1');
//gapi.load('drive-share');
angular.module('app', ['app.filters', 'app.services', 'app.directives'])
.constant('saveInterval', 15000)
.constant('appId', [[YOUR_APP_ID]]) // Change this by your Application ID
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/edit/:id', {templateUrl:'partials/editor.html', controller:EditorCtrl})
.when('/create/:folderId', {templateUrl:'partials/editor.html', controller:EditorCtrl})
.otherwise({redirectTo:'/edit/'});
}]);
| zzangtest123-google-drive-sdk-samples | java/war/js/app.js | JavaScript | asf20 | 723 |
'use strict';
function UserCtrl($scope, backend) {
$scope.user = null;
$scope.login = function () {
backend.user().then(function (response) {
$scope.user = response.data;
});
}
$scope.login();
}
function EditorCtrl($scope, $location, $routeParams, $timeout, editor, doc, autosaver) {
console.log($routeParams);
$scope.editor = editor;
$scope.doc = doc;
$scope.$on('saved',
function (event) {
$location.path('/edit/' + doc.resource_id);
});
if ($routeParams.id) {
editor.load($routeParams.id);
} else {
// New doc, but defer to next event cycle to ensure init
$timeout(function () {
editor.create($routeParams.folderId);
},
1);
}
}
function ShareCtrl($scope, appId, doc) {
/*var sharingClient;
var init = function() {
sharingClient = new gapi.drive.share.ShareClient(appId);
}
gapi.load('drive-share', init);
$scope.enabled = function() {
return doc.resource_id != null;
};
$scope.share = function() {
sharingClient.setItemIds([doc.resource_id]);
sharingClient.showSettingsDialog();
}*/
}
function MenuCtrl($scope, $location, appId) {
var onFilePicked = function (data) {
$scope.$apply(function () {
if (data.action == 'picked') {
var id = data.docs[0].id;
$location.path('/edit/' + id);
}
});
};
$scope.open = function () {
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes('text/plain');
var picker = new google.picker.PickerBuilder()
.setAppId(appId)
.addView(view)
.setCallback(angular.bind(this, onFilePicked))
.build();
picker.setVisible(true);
};
$scope.create = function () {
this.editor.create();
};
$scope.save = function () {
this.editor.save(true);
}
}
function RenameCtrl($scope, doc) {
$('#rename-dialog').on('show',
function () {
$scope.$apply(function () {
$scope.newFileName = doc.info.title;
});
});
$scope.save = function () {
doc.info.title = $scope.newFileName;
$('#rename-dialog').modal('hide');
};
}
function AboutCtrl($scope, backend) {
$('#about-dialog').on('show',
function () {
backend.about().then(function (result) {
$scope.info = result.data;
});
});
} | zzangtest123-google-drive-sdk-samples | java/war/js/controllers.js | JavaScript | asf20 | 2,552 |
'use strict';
/* Filters */
angular.module('app.filters', [])
.filter('saveStateFormatter',
function () {
return function (state) {
if (state == EditorState.DIRTY) {
return 'You have unsaved changes';
} else if (state == EditorState.SAVE) {
return 'Saving...';
} else if (state == EditorState.LOAD) {
return 'Loading...';
} else if (state == EditorState.READONLY) {
return "Read only"
} else {
return 'All changes saved';
}
};
})
.filter('bytes',
function () {
return function (bytes) {
bytes = parseInt(bytes);
if (isNaN(bytes)) {
return "...";
}
var units = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'];
var p = bytes > 0 ? Math.floor(Math.log(bytes) / Math.LN2 / 10) : 0;
var u = Math.round(bytes / Math.pow(2, 10 * p));
return u + units[p];
}
});
| zzangtest123-google-drive-sdk-samples | java/war/js/filters.js | JavaScript | asf20 | 1,084 |
'use strict';
var module = angular.module('app.services', []);
var ONE_HOUR_IN_MS = 1000 * 60 * 60;
// Shared model for current document
module.factory('doc',
function ($rootScope) {
var service = $rootScope.$new(true);
service.dirty = false;
service.lastSave = 0;
service.timeSinceLastSave = function () {
return new Date().getTime() - this.lastSave;
};
service.$watch('info',
function (newValue, oldValue) {
if (oldValue != null && newValue === oldValue) {
service.dirty = true;
}
},
true);
return service;
});
module.factory('editor',
function (doc, backend, $q, $rootScope, $log) {
var editor = null;
var EditSession = require("ace/edit_session").EditSession;
var service = {
loading:false,
saving:false,
rebind:function (element) {
editor = ace.edit(element);
},
snapshot:function () {
doc.dirty = false;
var data = angular.extend({}, doc.info);
data.resource_id = doc.resource_id;
if (doc.info.editable) {
data.content = editor.getSession().getValue();
}
return data;
},
create:function (folderId) {
if (!folderId) {
folderId = "root";
}
$log.info("Creating new doc");
this.updateEditor({
content:'',
labels:{
starred:false
},
parents:[{id: folderId}],
editable:true,
title:'Untitled document',
description:'',
mimeType:'text/plain',
resource_id:null
});
},
load:function (id, reload) {
$log.info("Loading resource", id, doc.resource_id);
if (!reload && doc.info && id == doc.resource_id) {
return $q.when(doc.info);
}
this.loading = true;
return backend.load(id).then(angular.bind(this,
function (result) {
this.loading = false;
this.updateEditor(result.data);
$rootScope.$broadcast('loaded', doc.info);
return result;
}), angular.bind(this,
function (result) {
$log.warn("Error loading", result);
this.loading = false;
$rootScope.$broadcast('error', {
action:'load',
message:"An error occured while loading the file"
});
return result;
}));
},
save:function (newRevision) {
$log.info("Saving file", newRevision);
if (this.saving || this.loading) {
throw 'Save called from incorrect state';
}
this.saving = true;
var file = this.snapshot();
// Force revision if first save of the session
newRevision = newRevision || doc.timeSinceLastSave() > ONE_HOUR_IN_MS;
var promise = backend.save(file, newRevision);
promise.then(angular.bind(this,
function (result) {
$log.info("Saved file", result);
this.saving = false;
doc.resource_id = result.data;
doc.lastSave = new Date().getTime();
$rootScope.$broadcast('saved', doc.info);
return doc.info;
}), angular.bind(this,
function (result) {
this.saving = false;
doc.dirty = true;
$rootScope.$broadcast('error', {
action:'save',
message:"An error occured while saving the file"
});
return result;
}));
return promise;
},
updateEditor:function (fileInfo) {
$log.info("Updating editor", fileInfo);
var session = new EditSession(fileInfo.content);
session.on('change', function () {
doc.dirty = true;
$rootScope.$apply();
});
fileInfo.content = null;
doc.lastSave = 0;
doc.info = fileInfo;
doc.resource_id = fileInfo.id;
editor.setSession(session);
editor.setReadOnly(!doc.info.editable);
editor.focus();
},
state:function () {
if (this.loading) {
return EditorState.LOAD;
} else if (this.saving) {
return EditorState.SAVE;
} else if (doc.dirty) {
return EditorState.DIRTY;
} else if (!doc.info.editable) {
return EditorState.READONLY;
}
return EditorState.CLEAN;
}
};
return service;
});
module.factory('backend',
function ($http, $log) {
var jsonTransform = function (data, headers) {
return angular.fromJson(data);
};
var service = {
user:function () {
return $http.get('/user', {transformResponse:jsonTransform});
},
about:function () {
return $http.get('/about', {transformResponse:jsonTransform});
},
load:function (id) {
return $http.get('/svc', {
transformResponse:jsonTransform,
params:{
'file_id':id
}
});
},
save:function (fileInfo, newRevision) {
$log.info('Saving', fileInfo);
return $http({
url:'/svc',
method:fileInfo.resource_id ? 'PUT' : 'POST',
headers:{
'Content-Type':'application/json'
},
params:{
'newRevision':newRevision
},
transformResponse:jsonTransform,
data:JSON.stringify(fileInfo)
});
}
};
return service;
});
module.factory('autosaver',
function (editor, saveInterval, $timeout) {
var saveFn = function () {
if (editor.state() == EditorState.DIRTY) {
editor.save(false);
}
};
var createTimeout = function () {
return $timeout(saveFn, saveInterval).then(createTimeout);
}
return createTimeout();
});
| zzangtest123-google-drive-sdk-samples | java/war/js/services.js | JavaScript | asf20 | 7,293 |
'use strict';
var module = angular.module('app.directives', []);
module.directive('aceEditor',
function (editor) {
return {
retrict:'A',
link:function (scope, element) {
editor.rebind(element[0]);
}
};
});
module.directive('star',
function () {
return {
restrict:'E',
replace:true,
scope:{
val:'=value',
// Value bound to
eventFn:'&click'
// Optional expression evaluated on click
},
link:function (scope, element) {
element.bind('click',
function () {
scope.$apply(function () {
scope.val = !scope.val;
});
scope.$eval(scope.eventFn, scope.val);
});
},
template:'<i class="star" ng-class="{\'icon-star\' : val, \'icon-star-empty\' : !val}" ng-click="toggle()"></i>'
}
});
module.directive('alert',
function ($rootScope) {
return {
restrict:'E',
replace:true,
link:function (scope, element) {
$rootScope.$on('error',
function (event, data) {
scope.message = data.message;
element.show();
});
scope.close = function () {
element.hide();
};
},
template:'<div class="hide alert alert-error">' +
' <span class="close" ng-click="close()">×</span>' +
' {{message}}' +
'</div>'
}
}) | zzangtest123-google-drive-sdk-samples | java/war/js/directives.js | JavaScript | asf20 | 1,774 |
<div class="container-fluid">
<div id="doc-bar" class="row-fluid">
<span class="span4">
<h3 ng-show="doc.info.editable" class="doc-title"
data-toggle="modal" href="#rename-dialog">{{doc.info.title}}</h3>
<h3 ng-hide="doc.info.editable" class="doc-title">{{doc.info.title}}</h3>
<star value="doc.info.labels.starred" click="editor.dirty(true)"></star></span>
<span class="span4">{{editor.state() | saveStateFormatter }}</span>
<span class="span4" ng-controller="ShareCtrl"><a class="btn pull-right" href click="share"> Share</a></span>
</div>
<div class="navbar subnav">
<ul ng-controller="MenuCtrl" class="nav">
<li class="dropdown">
<a href class="dropdown-toggle" data-toggle="dropdown">
File <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a target="_blank" href="#/edit">New</a></li>
<li><a ng-click="open()" href>Open</a></li>
<li>
<a ng-show="doc.info.editable" data-toggle="modal" href="#rename-dialog">Rename</a>
<span ng-hide="doc.info.editable">Rename</span>
</li>
<li><a ng-click="save()" href>Save</a></li>
</ul>
</li>
<li><a href="#about-dialog" data-toggle="modal">About</a></li>
</ul>
</div>
</div>
<div class="modal hide" id="rename-dialog" ng-controller="RenameCtrl">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Rename File</h3>
</div>
<div class="modal-body">
<form>
<label>Enter a new file name:</label>
<input type="text" ng-model="newFileName" autofocus required/>
</form>
</div>
<div class="modal-footer">
<a href class="btn" data-dismiss="modal">Cancel</a>
<a href ng-click="save()" class="btn btn-primary">Save</a>
</div>
</div>
<div class="modal hide" id="about-dialog" ng-controller="AboutCtrl">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>About</h3>
</div>
<div class="modal-body">
<div><b>Total Drive Quota:</b> {{info.quotaBytesTotal | bytes}}</div>
<div><b>Drive Quota Used:</b> {{info.quotaBytesUsed | bytes}}</div>
</div>
<div class="modal-footer">
<a href class="btn btn-primary" data-dismiss="modal">Close</a>
</div>
</div> | zzangtest123-google-drive-sdk-samples | java/war/partials/editor.html | HTML | asf20 | 2,381 |
/* app css stylesheet */
#editor {
position: absolute;
top: 120px;
bottom: 0px;
left: 0px;
right: 0px;
}
#doc-bar {
line-height: 27px;
}
.doc-title {
display:inline;
padding-right: 12px;
}
.star {
font-size: 22px;
color: black;
}
.icon-star {
color: yellow;
-webkit-text-stroke: 1px black;
}
.profile-picture {
width: 22px;
}
#error {
position: absolute;
bottom: 10px;
right: 10px;
}
body {
height: 100%;
}
.subnav {
margin-bottom: 0px;
}
.subnav .nav > li > a {
color: #333;
padding-top: 2px;
padding-bottom: 2px;
}
.subnav .nav > li > a:hover {
background-color: #F5F5F5;
color: #333;
}
.dropdown-menu span {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #333333;
white-space: nowrap;
}
| zzangtest123-google-drive-sdk-samples | java/war/css/app.css | CSS | asf20 | 792 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
var directive = {};
var service = { value: {} };
var DEPENDENCIES = {
'angular.js': 'http://code.angularjs.org/angular-' + angular.version.full + '.min.js',
'angular-resource.js': 'http://code.angularjs.org/angular-resource-' + angular.version.full + '.min.js',
'angular-sanitize.js': 'http://code.angularjs.org/angular-sanitize-' + angular.version.full + '.min.js',
'angular-cookies.js': 'http://code.angularjs.org/angular-cookies-' + angular.version.full + '.min.js'
};
function escape(text) {
return text.
replace(/\&/g, '&').
replace(/\</g, '<').
replace(/\>/g, '>').
replace(/"/g, '"');
}
/**
* http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
* http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
*/
function setHtmlIe8SafeWay(element, html) {
var newElement = angular.element('<pre>' + html + '</pre>');
element.html('');
element.append(newElement.contents());
return element;
}
directive.jsFiddle = function(getEmbeddedTemplate, escape, script) {
return {
terminal: true,
link: function(scope, element, attr) {
var name = '',
stylesheet = '<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">\n',
fields = {
html: '',
css: '',
js: ''
};
angular.forEach(attr.jsFiddle.split(' '), function(file, index) {
var fileType = file.split('.')[1];
if (fileType == 'html') {
if (index == 0) {
fields[fileType] +=
'<div ng-app' + (attr.module ? '="' + attr.module + '"' : '') + '>\n' +
getEmbeddedTemplate(file, 2);
} else {
fields[fileType] += '\n\n\n <!-- CACHE FILE: ' + file + ' -->\n' +
' <script type="text/ng-template" id="' + file + '">\n' +
getEmbeddedTemplate(file, 4) +
' </script>\n';
}
} else {
fields[fileType] += getEmbeddedTemplate(file) + '\n';
}
});
fields.html += '</div>\n';
setHtmlIe8SafeWay(element,
'<form class="jsfiddle" method="post" action="http://jsfiddle.net/api/post/library/pure/" target="_blank">' +
hiddenField('title', 'AngularJS Example: ' + name) +
hiddenField('css', '</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> \n' +
stylesheet +
script.angular +
(attr.resource ? script.resource : '') +
'<style>\n' +
fields.css) +
hiddenField('html', fields.html) +
hiddenField('js', fields.js) +
'<button class="btn btn-primary"><i class="icon-white icon-pencil"></i> Edit Me</button>' +
'</form>');
function hiddenField(name, value) {
return '<input type="hidden" name="' + name + '" value="' + escape(value) + '">';
}
}
}
};
directive.code = function() {
return {restrict: 'E', terminal: true};
};
directive.prettyprint = ['reindentCode', function(reindentCode) {
return {
restrict: 'C',
terminal: true,
compile: function(element) {
element.html(window.prettyPrintOne(reindentCode(element.html()), undefined, true));
}
};
}];
directive.ngSetText = ['getEmbeddedTemplate', function(getEmbeddedTemplate) {
return {
restrict: 'CA',
priority: 10,
compile: function(element, attr) {
setHtmlIe8SafeWay(element, escape(getEmbeddedTemplate(attr.ngSetText)));
}
}
}]
directive.ngHtmlWrap = ['reindentCode', 'templateMerge', function(reindentCode, templateMerge) {
return {
compile: function(element, attr) {
var properties = {
head: '',
module: '',
body: element.text()
},
html = "<!doctype html>\n<html ng-app{{module}}>\n <head>\n{{head:4}} </head>\n <body>\n{{body:4}} </body>\n</html>";
angular.forEach((attr.ngHtmlWrap || '').split(' '), function(dep) {
if (!dep) return;
dep = DEPENDENCIES[dep] || dep;
var ext = dep.split(/\./).pop();
if (ext == 'css') {
properties.head += '<link rel="stylesheet" href="' + dep + '" type="text/css">\n';
} else if(ext == 'js') {
properties.head += '<script src="' + dep + '"></script>\n';
} else {
properties.module = '="' + dep + '"';
}
});
setHtmlIe8SafeWay(element, escape(templateMerge(html, properties)));
}
}
}];
directive.ngSetHtml = ['getEmbeddedTemplate', function(getEmbeddedTemplate) {
return {
restrict: 'CA',
priority: 10,
compile: function(element, attr) {
setHtmlIe8SafeWay(element, getEmbeddedTemplate(attr.ngSetHtml));
}
}
}];
directive.ngEvalJavascript = ['getEmbeddedTemplate', function(getEmbeddedTemplate) {
return {
compile: function (element, attr) {
var script = getEmbeddedTemplate(attr.ngEvalJavascript);
try {
if (window.execScript) { // IE
window.execScript(script || '""'); // IE complains when evaling empty string
} else {
window.eval(script);
}
} catch (e) {
if (window.console) {
window.console.log(script, '\n', e);
} else {
window.alert(e);
}
}
}
};
}];
directive.ngEmbedApp = ['$templateCache', '$browser', '$rootScope', '$location', function($templateCache, $browser, docsRootScope, $location) {
return {
terminal: true,
link: function(scope, element, attrs) {
var modules = [];
modules.push(['$provide', function($provide) {
$provide.value('$templateCache', $templateCache);
$provide.value('$anchorScroll', angular.noop);
$provide.value('$browser', $browser);
$provide.provider('$location', function() {
this.$get = ['$rootScope', function($rootScope) {
docsRootScope.$on('$locationChangeSuccess', function(event, oldUrl, newUrl) {
$rootScope.$broadcast('$locationChangeSuccess', oldUrl, newUrl);
});
return $location;
}];
this.html5Mode = angular.noop;
});
$provide.decorator('$timeout', ['$rootScope', '$delegate', function($rootScope, $delegate) {
return angular.extend(function(fn, delay) {
if (delay && delay > 50) {
return setTimeout(function() {
$rootScope.$apply(fn);
}, delay);
} else {
return $delegate.apply(this, arguments);
}
}, $delegate);
}]);
$provide.decorator('$rootScope', ['$delegate', function(embedRootScope) {
docsRootScope.$watch(function() {
embedRootScope.$digest();
});
return embedRootScope;
}]);
}]);
if (attrs.ngEmbedApp) modules.push(attrs.ngEmbedApp);
element.bind('click', function(event) {
if (event.target.attributes.getNamedItem('ng-click')) {
event.preventDefault();
}
});
angular.bootstrap(element, modules);
}
};
}];
service.reindentCode = function() {
return function (text, spaces) {
if (!text) return text;
var lines = text.split(/\r?\n/);
var prefix = ' '.substr(0, spaces || 0);
var i;
// remove any leading blank lines
while (lines.length && lines[0].match(/^\s*$/)) lines.shift();
// remove any trailing blank lines
while (lines.length && lines[lines.length - 1].match(/^\s*$/)) lines.pop();
var minIndent = 999;
for (i = 0; i < lines.length; i++) {
var line = lines[0];
var reindentCode = line.match(/^\s*/)[0];
if (reindentCode !== line && reindentCode.length < minIndent) {
minIndent = reindentCode.length;
}
}
for (i = 0; i < lines.length; i++) {
lines[i] = prefix + lines[i].substring(minIndent);
}
lines.push('');
return lines.join('\n');
}
};
service.templateMerge = ['reindentCode', function(indentCode) {
return function(template, properties) {
return template.replace(/\{\{(\w+)(?:\:(\d+))?\}\}/g, function(_, key, indent) {
var value = properties[key];
if (indent) {
value = indentCode(value, indent);
}
return value == undefined ? '' : value;
});
};
}];
service.getEmbeddedTemplate = ['reindentCode', function(reindentCode) {
return function (id) {
var element = document.getElementById(id);
if (!element) {
return null;
}
return reindentCode(angular.element(element).html(), 0);
}
}];
angular.module('bootstrapPrettify', []).directive(directive).factory(service);
// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* some functions for browser-side pretty printing of code contained in html.
*
* <p>
* For a fairly comprehensive set of languages see the
* <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a>
* file that came with this source. At a minimum, the lexer should work on a
* number of languages including C and friends, Java, Python, Bash, SQL, HTML,
* XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
* and a subset of Perl, but, because of commenting conventions, doesn't work on
* Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
* <p>
* Usage: <ol>
* <li> include this source file in an html page via
* {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
* <li> define style rules. See the example page for examples.
* <li> mark the {@code <pre>} and {@code <code>} tags in your source with
* {@code class=prettyprint.}
* You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
* printer needs to do more substantial DOM manipulations to support that, so
* some css styles may not be preserved.
* </ol>
* That's it. I wanted to keep the API as simple as possible, so there's no
* need to specify which language the code is in, but if you wish, you can add
* another class to the {@code <pre>} or {@code <code>} element to specify the
* language, as in {@code <pre class="prettyprint lang-java">}. Any class that
* starts with "lang-" followed by a file extension, specifies the file type.
* See the "lang-*.js" files in this directory for code that implements
* per-language file handlers.
* <p>
* Change log:<br>
* cbeust, 2006/08/22
* <blockquote>
* Java annotations (start with "@") are now captured as literals ("lit")
* </blockquote>
* @requires console
*/
// JSLint declarations
/*global console, document, navigator, setTimeout, window, define */
/**
* Split {@code prettyPrint} into multiple timeouts so as not to interfere with
* UI events.
* If set to {@code false}, {@code prettyPrint()} is synchronous.
*/
window['PR_SHOULD_USE_CONTINUATION'] = true;
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function?} opt_whenDone if specified, called when the last entry
* has been finished.
*/
var prettyPrintOne;
/**
* Pretty print a chunk of code.
*
* @param {string} sourceCodeHtml code as html
* @return {string} code as html, but prettier
*/
var prettyPrint;
(function () {
var win = window;
// Keyword lists for various languages.
// We use things that coerce to strings to make them compact when minified
// and to defeat aggressive optimizers that fold large string constants.
var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
"double,enum,extern,float,goto,int,long,register,short,signed,sizeof," +
"static,struct,switch,typedef,union,unsigned,void,volatile"];
var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
"new,operator,private,protected,public,this,throw,true,try,typeof"];
var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," +
"concept,concept_map,const_cast,constexpr,decltype," +
"dynamic_cast,explicit,export,friend,inline,late_check," +
"mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast," +
"template,typeid,typename,using,virtual,where"];
var JAVA_KEYWORDS = [COMMON_KEYWORDS,
"abstract,boolean,byte,extends,final,finally,implements,import," +
"instanceof,null,native,package,strictfp,super,synchronized,throws," +
"transient"];
var CSHARP_KEYWORDS = [JAVA_KEYWORDS,
"as,base,by,checked,decimal,delegate,descending,dynamic,event," +
"fixed,foreach,from,group,implicit,in,interface,internal,into,is,let," +
"lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," +
"sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," +
"var,virtual,where"];
var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
"for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
"throw,true,try,unless,until,when,while,yes";
var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
"debugger,eval,export,function,get,null,set,undefined,var,with," +
"Infinity,NaN"];
var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
"goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
"sub,undef,unless,until,use,wantarray,while,BEGIN,END";
var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
"elif,except,exec,finally,from,global,import,in,is,lambda," +
"nonlocal,not,or,pass,print,raise,try,with,yield," +
"False,True,None"];
var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
"def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
"rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
"BEGIN,END"];
var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
"function,in,local,set,then,until"];
var ALL_KEYWORDS = [
CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS +
PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
// token style names. correspond to css classes
/**
* token style for a string literal
* @const
*/
var PR_STRING = 'str';
/**
* token style for a keyword
* @const
*/
var PR_KEYWORD = 'kwd';
/**
* token style for a comment
* @const
*/
var PR_COMMENT = 'com';
/**
* token style for a type
* @const
*/
var PR_TYPE = 'typ';
/**
* token style for a literal value. e.g. 1, null, true.
* @const
*/
var PR_LITERAL = 'lit';
/**
* token style for a punctuation string.
* @const
*/
var PR_PUNCTUATION = 'pun';
/**
* token style for plain text.
* @const
*/
var PR_PLAIN = 'pln';
/**
* token style for an sgml tag.
* @const
*/
var PR_TAG = 'tag';
/**
* token style for a markup declaration such as a DOCTYPE.
* @const
*/
var PR_DECLARATION = 'dec';
/**
* token style for embedded source.
* @const
*/
var PR_SOURCE = 'src';
/**
* token style for an sgml attribute name.
* @const
*/
var PR_ATTRIB_NAME = 'atn';
/**
* token style for an sgml attribute value.
* @const
*/
var PR_ATTRIB_VALUE = 'atv';
/**
* A class that indicates a section of markup that is not code, e.g. to allow
* embedding of line numbers within code listings.
* @const
*/
var PR_NOCODE = 'nocode';
/**
* A set of tokens that can precede a regular expression literal in
* javascript
* http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
* has the full list, but I've removed ones that might be problematic when
* seen in languages that don't support regular expression literals.
*
* <p>Specifically, I've removed any keywords that can't precede a regexp
* literal in a syntactically legal javascript program, and I've removed the
* "in" keyword since it's not a keyword in many languages, and might be used
* as a count of inches.
*
* <p>The link above does not accurately describe EcmaScript rules since
* it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
* very well in practice.
*
* @private
* @const
*/
var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
// CAVEAT: this does not properly handle the case where a regular
// expression immediately follows another since a regular expression may
// have flags for case-sensitivity and the like. Having regexp tokens
// adjacent is not valid in any language I'm aware of, so I'm punting.
// TODO: maybe style special characters inside a regexp as punctuation.
/**
* Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
* matches the union of the sets of strings matched by the input RegExp.
* Since it matches globally, if the input strings have a start-of-input
* anchor (/^.../), it is ignored for the purposes of unioning.
* @param {Array.<RegExp>} regexs non multiline, non-global regexs.
* @return {RegExp} a global regex.
*/
function combinePrefixPatterns(regexs) {
var capturedGroupIndex = 0;
var needToFoldCase = false;
var ignoreCase = false;
for (var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.ignoreCase) {
ignoreCase = true;
} else if (/[a-z]/i.test(regex.source.replace(
/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
needToFoldCase = true;
ignoreCase = false;
break;
}
}
var escapeCharToCodeUnit = {
'b': 8,
't': 9,
'n': 0xa,
'v': 0xb,
'f': 0xc,
'r': 0xd
};
function decodeEscape(charsetPart) {
var cc0 = charsetPart.charCodeAt(0);
if (cc0 !== 92 /* \\ */) {
return cc0;
}
var c1 = charsetPart.charAt(1);
cc0 = escapeCharToCodeUnit[c1];
if (cc0) {
return cc0;
} else if ('0' <= c1 && c1 <= '7') {
return parseInt(charsetPart.substring(1), 8);
} else if (c1 === 'u' || c1 === 'x') {
return parseInt(charsetPart.substring(2), 16);
} else {
return charsetPart.charCodeAt(1);
}
}
function encodeEscape(charCode) {
if (charCode < 0x20) {
return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
}
var ch = String.fromCharCode(charCode);
return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
? "\\" + ch : ch;
}
function caseFoldCharset(charSet) {
var charsetParts = charSet.substring(1, charSet.length - 1).match(
new RegExp(
'\\\\u[0-9A-Fa-f]{4}'
+ '|\\\\x[0-9A-Fa-f]{2}'
+ '|\\\\[0-3][0-7]{0,2}'
+ '|\\\\[0-7]{1,2}'
+ '|\\\\[\\s\\S]'
+ '|-'
+ '|[^-\\\\]',
'g'));
var ranges = [];
var inverse = charsetParts[0] === '^';
var out = ['['];
if (inverse) { out.push('^'); }
for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
var p = charsetParts[i];
if (/\\[bdsw]/i.test(p)) { // Don't muck with named groups.
out.push(p);
} else {
var start = decodeEscape(p);
var end;
if (i + 2 < n && '-' === charsetParts[i + 1]) {
end = decodeEscape(charsetParts[i + 2]);
i += 2;
} else {
end = start;
}
ranges.push([start, end]);
// If the range might intersect letters, then expand it.
// This case handling is too simplistic.
// It does not deal with non-latin case folding.
// It works for latin source code identifiers though.
if (!(end < 65 || start > 122)) {
if (!(end < 65 || start > 90)) {
ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
}
if (!(end < 97 || start > 122)) {
ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
}
}
}
}
// [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
// -> [[1, 12], [14, 14], [16, 17]]
ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });
var consolidatedRanges = [];
var lastRange = [];
for (var i = 0; i < ranges.length; ++i) {
var range = ranges[i];
if (range[0] <= lastRange[1] + 1) {
lastRange[1] = Math.max(lastRange[1], range[1]);
} else {
consolidatedRanges.push(lastRange = range);
}
}
for (var i = 0; i < consolidatedRanges.length; ++i) {
var range = consolidatedRanges[i];
out.push(encodeEscape(range[0]));
if (range[1] > range[0]) {
if (range[1] + 1 > range[0]) { out.push('-'); }
out.push(encodeEscape(range[1]));
}
}
out.push(']');
return out.join('');
}
function allowAnywhereFoldCaseAndRenumberGroups(regex) {
// Split into character sets, escape sequences, punctuation strings
// like ('(', '(?:', ')', '^'), and runs of characters that do not
// include any of the above.
var parts = regex.source.match(
new RegExp(
'(?:'
+ '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
+ '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
+ '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
+ '|\\\\[0-9]+' // a back-reference or octal escape
+ '|\\\\[^ux0-9]' // other escape sequence
+ '|\\(\\?[:!=]' // start of a non-capturing group
+ '|[\\(\\)\\^]' // start/end of a group, or line start
+ '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
+ ')',
'g'));
var n = parts.length;
// Maps captured group numbers to the number they will occupy in
// the output or to -1 if that has not been determined, or to
// undefined if they need not be capturing in the output.
var capturedGroups = [];
// Walk over and identify back references to build the capturedGroups
// mapping.
for (var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
// groups are 1-indexed, so max group index is count of '('
++groupIndex;
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue) {
if (decimalValue <= groupIndex) {
capturedGroups[decimalValue] = -1;
} else {
// Replace with an unambiguous escape sequence so that
// an octal escape sequence does not turn into a backreference
// to a capturing group from an earlier regex.
parts[i] = encodeEscape(decimalValue);
}
}
}
}
// Renumber groups and reduce capturing groups to non-capturing groups
// where possible.
for (var i = 1; i < capturedGroups.length; ++i) {
if (-1 === capturedGroups[i]) {
capturedGroups[i] = ++capturedGroupIndex;
}
}
for (var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
++groupIndex;
if (!capturedGroups[groupIndex]) {
parts[i] = '(?:';
}
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue && decimalValue <= groupIndex) {
parts[i] = '\\' + capturedGroups[decimalValue];
}
}
}
// Remove any prefix anchors so that the output will match anywhere.
// ^^ really does mean an anchored match though.
for (var i = 0; i < n; ++i) {
if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
}
// Expand letters to groups to handle mixing of case-sensitive and
// case-insensitive patterns if necessary.
if (regex.ignoreCase && needToFoldCase) {
for (var i = 0; i < n; ++i) {
var p = parts[i];
var ch0 = p.charAt(0);
if (p.length >= 2 && ch0 === '[') {
parts[i] = caseFoldCharset(p);
} else if (ch0 !== '\\') {
// TODO: handle letters in numeric escapes.
parts[i] = p.replace(
/[a-zA-Z]/g,
function (ch) {
var cc = ch.charCodeAt(0);
return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
});
}
}
}
return parts.join('');
}
var rewritten = [];
for (var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.global || regex.multiline) { throw new Error('' + regex); }
rewritten.push(
'(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
}
return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
}
/**
* Split markup into a string of source code and an array mapping ranges in
* that string to the text nodes in which they appear.
*
* <p>
* The HTML DOM structure:</p>
* <pre>
* (Element "p"
* (Element "b"
* (Text "print ")) ; #1
* (Text "'Hello '") ; #2
* (Element "br") ; #3
* (Text " + 'World';")) ; #4
* </pre>
* <p>
* corresponds to the HTML
* {@code <p><b>print </b>'Hello '<br> + 'World';</p>}.</p>
*
* <p>
* It will produce the output:</p>
* <pre>
* {
* sourceCode: "print 'Hello '\n + 'World';",
* // 1 2
* // 012345678901234 5678901234567
* spans: [0, #1, 6, #2, 14, #3, 15, #4]
* }
* </pre>
* <p>
* where #1 is a reference to the {@code "print "} text node above, and so
* on for the other text nodes.
* </p>
*
* <p>
* The {@code} spans array is an array of pairs. Even elements are the start
* indices of substrings, and odd elements are the text nodes (or BR elements)
* that contain the text for those substrings.
* Substrings continue until the next index or the end of the source.
* </p>
*
* @param {Node} node an HTML DOM subtree containing source-code.
* @param {boolean} isPreformatted true if white-space in text nodes should
* be considered significant.
* @return {Object} source code and the text nodes in which they occur.
*/
function extractSourceSpans(node, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var chunks = [];
var length = 0;
var spans = [];
var k = 0;
function walk(node) {
switch (node.nodeType) {
case 1: // Element
if (nocode.test(node.className)) { return; }
for (var child = node.firstChild; child; child = child.nextSibling) {
walk(child);
}
var nodeName = node.nodeName.toLowerCase();
if ('br' === nodeName || 'li' === nodeName) {
chunks[k] = '\n';
spans[k << 1] = length++;
spans[(k++ << 1) | 1] = node;
}
break;
case 3: case 4: // Text
var text = node.nodeValue;
if (text.length) {
if (!isPreformatted) {
text = text.replace(/[ \t\r\n]+/g, ' ');
} else {
text = text.replace(/\r\n?/g, '\n'); // Normalize newlines.
}
// TODO: handle tabs here?
chunks[k] = text;
spans[k << 1] = length;
length += text.length;
spans[(k++ << 1) | 1] = node;
}
break;
}
}
walk(node);
return {
sourceCode: chunks.join('').replace(/\n$/, ''),
spans: spans
};
}
/**
* Apply the given language handler to sourceCode and add the resulting
* decorations to out.
* @param {number} basePos the index of sourceCode within the chunk of source
* whose decorations are already present on out.
*/
function appendDecorations(basePos, sourceCode, langHandler, out) {
if (!sourceCode) { return; }
var job = {
sourceCode: sourceCode,
basePos: basePos
};
langHandler(job);
out.push.apply(out, job.decorations);
}
var notWs = /\S/;
/**
* Given an element, if it contains only one child element and any text nodes
* it contains contain only space characters, return the sole child element.
* Otherwise returns undefined.
* <p>
* This is meant to return the CODE element in {@code <pre><code ...>} when
* there is a single child element that contains all the non-space textual
* content, but not to return anything where there are multiple child elements
* as in {@code <pre><code>...</code><code>...</code></pre>} or when there
* is textual content.
*/
function childContentWrapper(element) {
var wrapper = undefined;
for (var c = element.firstChild; c; c = c.nextSibling) {
var type = c.nodeType;
wrapper = (type === 1) // Element Node
? (wrapper ? element : c)
: (type === 3) // Text Node
? (notWs.test(c.nodeValue) ? element : wrapper)
: wrapper;
}
return wrapper === element ? undefined : wrapper;
}
/** Given triples of [style, pattern, context] returns a lexing function,
* The lexing function interprets the patterns to find token boundaries and
* returns a decoration list of the form
* [index_0, style_0, index_1, style_1, ..., index_n, style_n]
* where index_n is an index into the sourceCode, and style_n is a style
* constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
* all characters in sourceCode[index_n-1:index_n].
*
* The stylePatterns is a list whose elements have the form
* [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
*
* Style is a style constant like PR_PLAIN, or can be a string of the
* form 'lang-FOO', where FOO is a language extension describing the
* language of the portion of the token in $1 after pattern executes.
* E.g., if style is 'lang-lisp', and group 1 contains the text
* '(hello (world))', then that portion of the token will be passed to the
* registered lisp handler for formatting.
* The text before and after group 1 will be restyled using this decorator
* so decorators should take care that this doesn't result in infinite
* recursion. For example, the HTML lexer rule for SCRIPT elements looks
* something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
* '<script>foo()<\/script>', which would cause the current decorator to
* be called with '<script>' which would not match the same rule since
* group 1 must not be empty, so it would be instead styled as PR_TAG by
* the generic tag rule. The handler registered for the 'js' extension would
* then be called with 'foo()', and finally, the current decorator would
* be called with '<\/script>' which would not match the original rule and
* so the generic tag rule would identify it as a tag.
*
* Pattern must only match prefixes, and if it matches a prefix, then that
* match is considered a token with the same style.
*
* Context is applied to the last non-whitespace, non-comment token
* recognized.
*
* Shortcut is an optional string of characters, any of which, if the first
* character, gurantee that this pattern and only this pattern matches.
*
* @param {Array} shortcutStylePatterns patterns that always start with
* a known character. Must have a shortcut string.
* @param {Array} fallthroughStylePatterns patterns that will be tried in
* order if the shortcut ones fail. May have shortcuts.
*
* @return {function (Object)} a
* function that takes source code and returns a list of decorations.
*/
function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
var shortcuts = {};
var tokenizer;
(function () {
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
var allRegexs = [];
var regexKeys = {};
for (var i = 0, n = allPatterns.length; i < n; ++i) {
var patternParts = allPatterns[i];
var shortcutChars = patternParts[3];
if (shortcutChars) {
for (var c = shortcutChars.length; --c >= 0;) {
shortcuts[shortcutChars.charAt(c)] = patternParts;
}
}
var regex = patternParts[1];
var k = '' + regex;
if (!regexKeys.hasOwnProperty(k)) {
allRegexs.push(regex);
regexKeys[k] = null;
}
}
allRegexs.push(/[\0-\uffff]/);
tokenizer = combinePrefixPatterns(allRegexs);
})();
var nPatterns = fallthroughStylePatterns.length;
/**
* Lexes job.sourceCode and produces an output array job.decorations of
* style classes preceded by the position at which they start in
* job.sourceCode in order.
*
* @param {Object} job an object like <pre>{
* sourceCode: {string} sourceText plain text,
* basePos: {int} position of job.sourceCode in the larger chunk of
* sourceCode.
* }</pre>
*/
var decorate = function (job) {
var sourceCode = job.sourceCode, basePos = job.basePos;
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
* @type {Array.<number|string>}
*/
var decorations = [basePos, PR_PLAIN];
var pos = 0; // index into sourceCode
var tokens = sourceCode.match(tokenizer) || [];
var styleCache = {};
for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
var token = tokens[ti];
var style = styleCache[token];
var match = void 0;
var isEmbedded;
if (typeof style === 'string') {
isEmbedded = false;
} else {
var patternParts = shortcuts[token.charAt(0)];
if (patternParts) {
match = token.match(patternParts[1]);
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
match = token.match(patternParts[1]);
if (match) {
style = patternParts[0];
break;
}
}
if (!match) { // make sure that we make progress
style = PR_PLAIN;
}
}
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
if (isEmbedded && !(match && typeof match[1] === 'string')) {
isEmbedded = false;
style = PR_SOURCE;
}
if (!isEmbedded) { styleCache[token] = style; }
}
var tokenStart = pos;
pos += token.length;
if (!isEmbedded) {
decorations.push(basePos + tokenStart, style);
} else { // Treat group 1 as an embedded block of source code.
var embeddedSource = match[1];
var embeddedSourceStart = token.indexOf(embeddedSource);
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
if (match[2]) {
// If embeddedSource can be blank, then it would match at the
// beginning which would cause us to infinitely recurse on the
// entire token, so we catch the right context in match[2].
embeddedSourceEnd = token.length - match[2].length;
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
}
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(
basePos + tokenStart,
token.substring(0, embeddedSourceStart),
decorate, decorations);
// Decorate the embedded source
appendDecorations(
basePos + tokenStart + embeddedSourceStart,
embeddedSource,
langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(
basePos + tokenStart + embeddedSourceEnd,
token.substring(embeddedSourceEnd),
decorate, decorations);
}
}
job.decorations = decorations;
};
return decorate;
}
/** returns a function that produces a list of decorations from source text.
*
* This code treats ", ', and ` as string delimiters, and \ as a string
* escape. It does not recognize perl's qq() style strings.
* It has no special handling for double delimiter escapes as in basic, or
* the tripled delimiters used in python, but should work on those regardless
* although in those cases a single string literal may be broken up into
* multiple adjacent string literals.
*
* It recognizes C, C++, and shell style comments.
*
* @param {Object} options a set of optional parameters.
* @return {function (Object)} a function that examines the source code
* in the input job and builds the decoration list.
*/
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"']);
} else if (options['multiLineStrings']) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`']);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push(
[PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'']);
}
if (options['verbatimStrings']) {
// verbatim-string-literal production from the C# grammar. See issue 93.
fallthroughStylePatterns.push(
[PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
}
var hc = options['hashComments'];
if (hc) {
if (options['cStyleComments']) {
if (hc > 1) { // multiline hash comments
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
} else {
// Stop C preprocessor declarations at an unclosed open comment
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,
null, '#']);
}
// #include <stdio.h>
fallthroughStylePatterns.push(
[PR_STRING,
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
null]);
} else {
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
}
}
if (options['cStyleComments']) {
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
if (options['regexLiterals']) {
/**
* @const
*/
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'/(?=[^/*])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C]'
// escape sequences (\x5C),
+ '|\\x5C[\\s\\S]'
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
var types = options['types'];
if (types) {
fallthroughStylePatterns.push([PR_TYPE, types]);
}
var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
if (keywords.length) {
fallthroughStylePatterns.push(
[PR_KEYWORD,
new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
null]);
}
shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
[PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
[PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
[PR_LITERAL,
new RegExp(
'^(?:'
// A hex number
+ '0x[a-f0-9]+'
// or an octal or decimal number,
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
// possibly in scientific notation
+ '(?:e[+\\-]?\\d+)?'
+ ')'
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'),
null, '0123456789'],
// Don't treat escaped quotes in bash as starting strings. See issue 144.
[PR_PLAIN, /^\\[\s\S]?/, null],
[PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#\\]*/, null]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
}
var decorateSource = sourceDecorator({
'keywords': ALL_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'multiLineStrings': true,
'regexLiterals': true
});
/**
* Given a DOM subtree, wraps it in a list, and puts each line into its own
* list item.
*
* @param {Node} node modified in place. Its content is pulled into an
* HTMLOListElement, and each line is moved into a separate list item.
* This requires cloning elements, so the input might not have unique
* IDs after numbering.
* @param {boolean} isPreformatted true iff white-space in text nodes should
* be treated as significant.
*/
function numberLines(node, opt_startLineNum, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var lineBreak = /\r\n?|\n/;
var document = node.ownerDocument;
var li = document.createElement('li');
while (node.firstChild) {
li.appendChild(node.firstChild);
}
// An array of lines. We split below, so this is initialized to one
// un-split line.
var listItems = [li];
function walk(node) {
switch (node.nodeType) {
case 1: // Element
if (nocode.test(node.className)) { break; }
if ('br' === node.nodeName) {
breakAfter(node);
// Discard the <BR> since it is now flush against a </LI>.
if (node.parentNode) {
node.parentNode.removeChild(node);
}
} else {
for (var child = node.firstChild; child; child = child.nextSibling) {
walk(child);
}
}
break;
case 3: case 4: // Text
if (isPreformatted) {
var text = node.nodeValue;
var match = text.match(lineBreak);
if (match) {
var firstLine = text.substring(0, match.index);
node.nodeValue = firstLine;
var tail = text.substring(match.index + match[0].length);
if (tail) {
var parent = node.parentNode;
parent.insertBefore(
document.createTextNode(tail), node.nextSibling);
}
breakAfter(node);
if (!firstLine) {
// Don't leave blank text nodes in the DOM.
node.parentNode.removeChild(node);
}
}
}
break;
}
}
// Split a line after the given node.
function breakAfter(lineEndNode) {
// If there's nothing to the right, then we can skip ending the line
// here, and move root-wards since splitting just before an end-tag
// would require us to create a bunch of empty copies.
while (!lineEndNode.nextSibling) {
lineEndNode = lineEndNode.parentNode;
if (!lineEndNode) { return; }
}
function breakLeftOf(limit, copy) {
// Clone shallowly if this node needs to be on both sides of the break.
var rightSide = copy ? limit.cloneNode(false) : limit;
var parent = limit.parentNode;
if (parent) {
// We clone the parent chain.
// This helps us resurrect important styling elements that cross lines.
// E.g. in <i>Foo<br>Bar</i>
// should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
var parentClone = breakLeftOf(parent, 1);
// Move the clone and everything to the right of the original
// onto the cloned parent.
var next = limit.nextSibling;
parentClone.appendChild(rightSide);
for (var sibling = next; sibling; sibling = next) {
next = sibling.nextSibling;
parentClone.appendChild(sibling);
}
}
return rightSide;
}
var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
// Walk the parent chain until we reach an unattached LI.
for (var parent;
// Check nodeType since IE invents document fragments.
(parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
copiedListItem = parent;
}
// Put it on the list of lines for later processing.
listItems.push(copiedListItem);
}
// Split lines while there are lines left to split.
for (var i = 0; // Number of lines that have been split so far.
i < listItems.length; // length updated by breakAfter calls.
++i) {
walk(listItems[i]);
}
// Make sure numeric indices show correctly.
if (opt_startLineNum === (opt_startLineNum|0)) {
listItems[0].setAttribute('value', opt_startLineNum);
}
var ol = document.createElement('ol');
ol.className = 'linenums';
var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
for (var i = 0, n = listItems.length; i < n; ++i) {
li = listItems[i];
// Stick a class on the LIs so that stylesheets can
// color odd/even rows, or any other row pattern that
// is co-prime with 10.
li.className = 'L' + ((i + offset) % 10);
if (!li.firstChild) {
li.appendChild(document.createTextNode('\xA0'));
}
ol.appendChild(li);
}
node.appendChild(ol);
}
/**
* Breaks {@code job.sourceCode} around style boundaries in
* {@code job.decorations} and modifies {@code job.sourceNode} in place.
* @param {Object} job like <pre>{
* sourceCode: {string} source as plain text,
* spans: {Array.<number|Node>} alternating span start indices into source
* and the text node or element (e.g. {@code <BR>}) corresponding to that
* span.
* decorations: {Array.<number|string} an array of style classes preceded
* by the position at which they start in job.sourceCode in order
* }</pre>
* @private
*/
function recombineTagsAndDecorations(job) {
var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
var newlineRe = /\n/g;
var source = job.sourceCode;
var sourceLength = source.length;
// Index into source after the last code-unit recombined.
var sourceIndex = 0;
var spans = job.spans;
var nSpans = spans.length;
// Index into spans after the last span which ends at or before sourceIndex.
var spanIndex = 0;
var decorations = job.decorations;
var nDecorations = decorations.length;
// Index into decorations after the last decoration which ends at or before
// sourceIndex.
var decorationIndex = 0;
// Remove all zero-length decorations.
decorations[nDecorations] = sourceLength;
var decPos, i;
for (i = decPos = 0; i < nDecorations;) {
if (decorations[i] !== decorations[i + 2]) {
decorations[decPos++] = decorations[i++];
decorations[decPos++] = decorations[i++];
} else {
i += 2;
}
}
nDecorations = decPos;
// Simplify decorations.
for (i = decPos = 0; i < nDecorations;) {
var startPos = decorations[i];
// Conflate all adjacent decorations that use the same style.
var startDec = decorations[i + 1];
var end = i + 2;
while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
end += 2;
}
decorations[decPos++] = startPos;
decorations[decPos++] = startDec;
i = end;
}
nDecorations = decorations.length = decPos;
var sourceNode = job.sourceNode;
var oldDisplay;
if (sourceNode) {
oldDisplay = sourceNode.style.display;
sourceNode.style.display = 'none';
}
try {
var decoration = null;
while (spanIndex < nSpans) {
var spanStart = spans[spanIndex];
var spanEnd = spans[spanIndex + 2] || sourceLength;
var decEnd = decorations[decorationIndex + 2] || sourceLength;
var end = Math.min(spanEnd, decEnd);
var textNode = spans[spanIndex + 1];
var styledText;
if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s
// Don't introduce spans around empty text nodes.
&& (styledText = source.substring(sourceIndex, end))) {
// This may seem bizarre, and it is. Emitting LF on IE causes the
// code to display with spaces instead of line breaks.
// Emitting Windows standard issue linebreaks (CRLF) causes a blank
// space to appear at the beginning of every line but the first.
// Emitting an old Mac OS 9 line separator makes everything spiffy.
if (isIE8OrEarlier) {
styledText = styledText.replace(newlineRe, '\r');
}
textNode.nodeValue = styledText;
var document = textNode.ownerDocument;
var span = document.createElement('span');
span.className = decorations[decorationIndex + 1];
var parentNode = textNode.parentNode;
parentNode.replaceChild(span, textNode);
span.appendChild(textNode);
if (sourceIndex < spanEnd) { // Split off a text node.
spans[spanIndex + 1] = textNode
// TODO: Possibly optimize by using '' if there's no flicker.
= document.createTextNode(source.substring(end, spanEnd));
parentNode.insertBefore(textNode, span.nextSibling);
}
}
sourceIndex = end;
if (sourceIndex >= spanEnd) {
spanIndex += 2;
}
if (sourceIndex >= decEnd) {
decorationIndex += 2;
}
}
} finally {
if (sourceNode) {
sourceNode.style.display = oldDisplay;
}
}
}
/** Maps language-specific file extensions to handlers. */
var langHandlerRegistry = {};
/** Register a language handler for the given file extensions.
* @param {function (Object)} handler a function from source code to a list
* of decorations. Takes a single argument job which describes the
* state of the computation. The single parameter has the form
* {@code {
* sourceCode: {string} as plain text.
* decorations: {Array.<number|string>} an array of style classes
* preceded by the position at which they start in
* job.sourceCode in order.
* The language handler should assigned this field.
* basePos: {int} the position of source in the larger source chunk.
* All positions in the output decorations array are relative
* to the larger source chunk.
* } }
* @param {Array.<string>} fileExtensions
*/
function registerLangHandler(handler, fileExtensions) {
for (var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if (win['console']) {
console['warn']('cannot override language handler %s', ext);
}
}
}
function langHandlerForExtension(extension, source) {
if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
// Treat it as markup if the first non whitespace character is a < and
// the last non-whitespace character is a >.
extension = /^\s*</.test(source)
? 'default-markup'
: 'default-code';
}
return langHandlerRegistry[extension];
}
registerLangHandler(decorateSource, ['default-code']);
registerLangHandler(
createSimpleLexer(
[],
[
[PR_PLAIN, /^[^<?]+/],
[PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
[PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/],
// Unescaped content in an unknown language
['lang-', /^<\?([\s\S]+?)(?:\?>|$)/],
['lang-', /^<%([\s\S]+?)(?:%>|$)/],
[PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
// Unescaped content in javascript. (Or possibly vbscript).
['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
// Contains unescaped stylesheet content
['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i]
]),
['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
registerLangHandler(
createSimpleLexer(
[
[PR_PLAIN, /^[\s]+/, null, ' \t\r\n'],
[PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
],
[
[PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
[PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
[PR_PUNCTUATION, /^[=<>\/]+/],
['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i],
['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i],
['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i],
['lang-css', /^style\s*=\s*\"([^\"]+)\"/i],
['lang-css', /^style\s*=\s*\'([^\']+)\'/i],
['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i]
]),
['in.tag']);
registerLangHandler(
createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
registerLangHandler(sourceDecorator({
'keywords': CPP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'types': C_TYPES
}), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
registerLangHandler(sourceDecorator({
'keywords': 'null,true,false'
}), ['json']);
registerLangHandler(sourceDecorator({
'keywords': CSHARP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'verbatimStrings': true,
'types': C_TYPES
}), ['cs']);
registerLangHandler(sourceDecorator({
'keywords': JAVA_KEYWORDS,
'cStyleComments': true
}), ['java']);
registerLangHandler(sourceDecorator({
'keywords': SH_KEYWORDS,
'hashComments': true,
'multiLineStrings': true
}), ['bsh', 'csh', 'sh']);
registerLangHandler(sourceDecorator({
'keywords': PYTHON_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'tripleQuotedStrings': true
}), ['cv', 'py']);
registerLangHandler(sourceDecorator({
'keywords': PERL_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': true
}), ['perl', 'pl', 'pm']);
registerLangHandler(sourceDecorator({
'keywords': RUBY_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': true
}), ['rb']);
registerLangHandler(sourceDecorator({
'keywords': JSCRIPT_KEYWORDS,
'cStyleComments': true,
'regexLiterals': true
}), ['js']);
registerLangHandler(sourceDecorator({
'keywords': COFFEE_KEYWORDS,
'hashComments': 3, // ### style block comments
'cStyleComments': true,
'multilineStrings': true,
'tripleQuotedStrings': true,
'regexLiterals': true
}), ['coffee']);
registerLangHandler(
createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
function applyDecorator(job) {
var opt_langExtension = job.langExtension;
try {
// Extract tags, and convert the source code to plain text.
var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
/** Plain text. @type {string} */
var source = sourceAndSpans.sourceCode;
job.sourceCode = source;
job.spans = sourceAndSpans.spans;
job.basePos = 0;
// Apply the appropriate language handler
langHandlerForExtension(opt_langExtension, source)(job);
// Integrate the decorations and tags back into the source code,
// modifying the sourceNode in place.
recombineTagsAndDecorations(job);
} catch (e) {
if (win['console']) {
console['log'](e && e['stack'] ? e['stack'] : e);
}
}
}
/**
* @param sourceCodeHtml {string} The HTML to pretty print.
* @param opt_langExtension {string} The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param opt_numberLines {number|boolean} True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
*/
function prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
// PATCHED: http://code.google.com/p/google-code-prettify/issues/detail?id=213
var container = document.createElement('div');
// This could cause images to load and onload listeners to fire.
// E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
// We assume that the inner HTML is from a trusted source.
container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
container = container.firstChild;
if (opt_numberLines) {
numberLines(container, opt_numberLines, true);
}
var job = {
langExtension: opt_langExtension,
numberLines: opt_numberLines,
sourceNode: container,
pre: 1
};
applyDecorator(job);
return container.innerHTML;
}
function prettyPrint(opt_whenDone) {
function byTagName(tn) { return document.getElementsByTagName(tn); }
// fetch a list of nodes to rewrite
var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
var elements = [];
for (var i = 0; i < codeSegments.length; ++i) {
for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
elements.push(codeSegments[i][j]);
}
}
codeSegments = null;
var clock = Date;
if (!clock['now']) {
clock = { 'now': function () { return +(new Date); } };
}
// The loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
var prettyPrintingJob;
var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
var prettyPrintRe = /\bprettyprint\b/;
var prettyPrintedRe = /\bprettyprinted\b/;
var preformattedTagNameRe = /pre|xmp/i;
var codeRe = /^code$/i;
var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
function doWork() {
var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
clock['now']() + 250 /* ms */ :
Infinity);
for (; k < elements.length && clock['now']() < endTime; k++) {
var cs = elements[k];
var className = cs.className;
if (prettyPrintRe.test(className)
// Don't redo this if we've already done it.
// This allows recalling pretty print to just prettyprint elements
// that have been added to the page since last call.
&& !prettyPrintedRe.test(className)) {
// make sure this is not nested in an already prettified element
var nested = false;
for (var p = cs.parentNode; p; p = p.parentNode) {
var tn = p.tagName;
if (preCodeXmpRe.test(tn)
&& p.className && prettyPrintRe.test(p.className)) {
nested = true;
break;
}
}
if (!nested) {
// Mark done. If we fail to prettyprint for whatever reason,
// we shouldn't try again.
cs.className += ' prettyprinted';
// If the classes includes a language extensions, use it.
// Language extensions can be specified like
// <pre class="prettyprint lang-cpp">
// the language extension "cpp" is used to find a language handler
// as passed to PR.registerLangHandler.
// HTML5 recommends that a language be specified using "language-"
// as the prefix instead. Google Code Prettify supports both.
// http://dev.w3.org/html5/spec-author-view/the-code-element.html
var langExtension = className.match(langExtensionRe);
// Support <pre class="prettyprint"><code class="language-c">
var wrapper;
if (!langExtension && (wrapper = childContentWrapper(cs))
&& codeRe.test(wrapper.tagName)) {
langExtension = wrapper.className.match(langExtensionRe);
}
if (langExtension) { langExtension = langExtension[1]; }
var preformatted;
if (preformattedTagNameRe.test(cs.tagName)) {
preformatted = 1;
} else {
var currentStyle = cs['currentStyle'];
var whitespace = (
currentStyle
? currentStyle['whiteSpace']
: (document.defaultView
&& document.defaultView.getComputedStyle)
? document.defaultView.getComputedStyle(cs, null)
.getPropertyValue('white-space')
: 0);
preformatted = whitespace
&& 'pre' === whitespace.substring(0, 3);
}
// Look for a class like linenums or linenums:<n> where <n> is the
// 1-indexed number of the first line.
var lineNums = cs.className.match(/\blinenums\b(?::(\d+))?/);
lineNums = lineNums
? lineNums[1] && lineNums[1].length ? +lineNums[1] : true
: false;
if (lineNums) { numberLines(cs, lineNums, preformatted); }
// do the pretty printing
prettyPrintingJob = {
langExtension: langExtension,
sourceNode: cs,
numberLines: lineNums,
pre: preformatted
};
applyDecorator(prettyPrintingJob);
}
}
}
if (k < elements.length) {
// finish up in a continuation
setTimeout(doWork, 250);
} else if (opt_whenDone) {
opt_whenDone();
}
}
doWork();
}
/**
* Contains functions for creating and registering new language handlers.
* @type {Object}
*/
var PR = win['PR'] = {
'createSimpleLexer': createSimpleLexer,
'registerLangHandler': registerLangHandler,
'sourceDecorator': sourceDecorator,
'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
'PR_COMMENT': PR_COMMENT,
'PR_DECLARATION': PR_DECLARATION,
'PR_KEYWORD': PR_KEYWORD,
'PR_LITERAL': PR_LITERAL,
'PR_NOCODE': PR_NOCODE,
'PR_PLAIN': PR_PLAIN,
'PR_PUNCTUATION': PR_PUNCTUATION,
'PR_SOURCE': PR_SOURCE,
'PR_STRING': PR_STRING,
'PR_TAG': PR_TAG,
'PR_TYPE': PR_TYPE,
'prettyPrintOne': win['prettyPrintOne'] = prettyPrintOne,
'prettyPrint': win['prettyPrint'] = prettyPrint
};
// Make PR available via the Asynchronous Module Definition (AMD) API.
// Per https://github.com/amdjs/amdjs-api/wiki/AMD:
// The Asynchronous Module Definition (AMD) API specifies a
// mechanism for defining modules such that the module and its
// dependencies can be asynchronously loaded.
// ...
// To allow a clear indicator that a global define function (as
// needed for script src browser loading) conforms to the AMD API,
// any global define function SHOULD have a property called "amd"
// whose value is an object. This helps avoid conflict with any
// other existing JavaScript code that could have defined a define()
// function that does not conform to the AMD API.
if (typeof define === "function" && define['amd']) {
define("google-code-prettify", [], function () {
return PR;
});
}
})();
})(window, window.angular);
angular.element(document).find('head').append('<style type="text/css">.com{color:#93a1a1;}.lit{color:#195f91;}.pun,.opn,.clo{color:#93a1a1;}.fun{color:#dc322f;}.str,.atv{color:#D14;}.kwd,.linenums .tag{color:#1e347b;}.typ,.atn,.dec,.var{color:teal;}.pln{color:#48484c;}.prettyprint{padding:8px;background-color:#f7f7f9;border:1px solid #e1e1e8;}.prettyprint.linenums{-webkit-box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;-moz-box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;}ol.linenums{margin:0 0 0 33px;}ol.linenums li{padding-left:12px;color:#bebec5;line-height:18px;text-shadow:0 1px 0 #fff;}</style>'); | zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-bootstrap-prettify-1.0.0.js | JavaScript | asf20 | 67,929 |
/**
* Configuration for jstd scenario adapter
*/
var jstdScenarioAdapter = {
relativeUrlPrefix: '/build/docs/'
};
| zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/jstd-scenario-adapter-config-1.0.0.js | JavaScript | asf20 | 120 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
var directive = {};
directive.dropdownToggle =
['$document', '$location', '$window',
function ($document, $location, $window) {
var openElement = null, close;
return {
restrict: 'C',
link: function(scope, element, attrs) {
scope.$watch(function(){return $location.path();}, function() {
close && close();
});
element.parent().bind('click', function(event) {
close && close();
});
element.bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
var iWasOpen = false;
if (openElement) {
iWasOpen = openElement === element;
close();
}
if (!iWasOpen){
element.parent().addClass('open');
openElement = element;
close = function (event) {
event && event.preventDefault();
event && event.stopPropagation();
$document.unbind('click', close);
element.parent().removeClass('open');
close = null;
openElement = null;
}
$document.bind('click', close);
}
});
}
};
}];
directive.tabbable = function() {
return {
restrict: 'C',
compile: function(element) {
var navTabs = angular.element('<ul class="nav nav-tabs"></ul>'),
tabContent = angular.element('<div class="tab-content"></div>');
tabContent.append(element.contents());
element.append(navTabs).append(tabContent);
},
controller: ['$scope', '$element', function($scope, $element) {
var navTabs = $element.contents().eq(0),
ngModel = $element.controller('ngModel') || {},
tabs = [],
selectedTab;
ngModel.$render = function() {
var $viewValue = this.$viewValue;
if (selectedTab ? (selectedTab.value != $viewValue) : $viewValue) {
if(selectedTab) {
selectedTab.paneElement.removeClass('active');
selectedTab.tabElement.removeClass('active');
selectedTab = null;
}
if($viewValue) {
for(var i = 0, ii = tabs.length; i < ii; i++) {
if ($viewValue == tabs[i].value) {
selectedTab = tabs[i];
break;
}
}
if (selectedTab) {
selectedTab.paneElement.addClass('active');
selectedTab.tabElement.addClass('active');
}
}
}
};
this.addPane = function(element, attr) {
var li = angular.element('<li><a href></a></li>'),
a = li.find('a'),
tab = {
paneElement: element,
paneAttrs: attr,
tabElement: li
};
tabs.push(tab);
attr.$observe('value', update)();
attr.$observe('title', function(){ update(); a.text(tab.title); })();
function update() {
tab.title = attr.title;
tab.value = attr.value || attr.title;
if (!ngModel.$setViewValue && (!ngModel.$viewValue || tab == selectedTab)) {
// we are not part of angular
ngModel.$viewValue = tab.value;
}
ngModel.$render();
}
navTabs.append(li);
li.bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
if (ngModel.$setViewValue) {
$scope.$apply(function() {
ngModel.$setViewValue(tab.value);
ngModel.$render();
});
} else {
// we are not part of angular
ngModel.$viewValue = tab.value;
ngModel.$render();
}
});
return function() {
tab.tabElement.remove();
for(var i = 0, ii = tabs.length; i < ii; i++ ) {
if (tab == tabs[i]) {
tabs.splice(i, 1);
}
}
};
}
}]
};
};
directive.tabPane = function() {
return {
require: '^tabbable',
restrict: 'C',
link: function(scope, element, attrs, tabsCtrl) {
element.bind('$remove', tabsCtrl.addPane(element, attrs));
}
};
};
angular.module('bootstrap', []).directive(directive);
})(window, window.angular);
| zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-bootstrap-1.0.0.js | JavaScript | asf20 | 4,516 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngResource
* @description
*/
/**
* @ngdoc object
* @name ngResource.$resource
* @requires $http
*
* @description
* A factory which creates a resource object that lets you interact with
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
*
* The returned resource object has action methods which provide high-level behaviors without
* the need to interact with the low level {@link ng.$http $http} service.
*
* @param {string} url A parameterized URL template with parameters prefixed by `:` as in
* `/user/:username`.
*
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
* `actions` methods.
*
* Each key value in the parameter object is first bound to url template if present and then any
* excess keys are appended to the url search query after the `?`.
*
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
* URL `/path/greet?salutation=Hello`.
*
* If the parameter value is prefixed with `@` then the value of that parameter is extracted from
* the data object (useful for non-GET operations).
*
* @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the
* default set of resource actions. The declaration should be created in the following format:
*
* {action1: {method:?, params:?, isArray:?},
* action2: {method:?, params:?, isArray:?},
* ...}
*
* Where:
*
* - `action` – {string} – The name of action. This name becomes the name of the method on your
* resource object.
* - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`,
* and `JSONP`
* - `params` – {object=} – Optional set of pre-bound parameters for this action.
* - isArray – {boolean=} – If true then the returned object for this action is an array, see
* `returns` section.
*
* @returns {Object} A resource "class" object with methods for the default set of resource actions
* optionally extended with custom `actions`. The default set contains these actions:
*
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'remove': {method:'DELETE'},
* 'delete': {method:'DELETE'} };
*
* Calling these methods invoke an {@link ng.$http} with the specified http method,
* destination and parameters. When the data is returned from the server then the object is an
* instance of the resource class `save`, `remove` and `delete` actions are available on it as
* methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read,
* update, delete) on server-side data like this:
* <pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It is important to realize that invoking a $resource object method immediately returns an
* empty reference (object or array depending on `isArray`). Once the data is returned from the
* server the existing reference is populated with the actual data. This is a useful trick since
* usually the resource is assigned to a model which is then rendered by the view. Having an empty
* object results in no rendering, once the data arrives from the server then the object is
* populated with the data and the view automatically re-renders itself showing the new data. This
* means that in most case one never has to write a callback function for the action methods.
*
* The action methods on the class object or instance object can be invoked with the following
* parameters:
*
* - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
* - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
* - non-GET instance actions: `instance.$action([parameters], [success], [error])`
*
*
* @example
*
* # Credit card resource
*
* <pre>
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'01234', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
* </pre>
*
* The object returned from this function execution is a resource "class" which has "static" method
* for each action in the definition.
*
* Calling these methods invoke `$http` on the `url` template with the given `method` and `params`.
* When the data is returned from the server then the object is an instance of the resource type and
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
* operations (create, read, update, delete) on server-side data.
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It's worth noting that the success callback for `get`, `query` and other method gets passed
* in the response that came from the server as well as $http header getter function, so one
* could rewrite the above example and get access to http headers as:
*
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
u.abc = true;
u.$save(function(u, putResponseHeaders) {
//u => saved user object
//putResponseHeaders => $http header getter
});
});
</pre>
* # Buzz client
Let's look at what a buzz client created with the `$resource` service looks like:
<doc:example>
<doc:source jsfiddle="false">
<script>
function BuzzController($resource) {
this.userId = 'googlebuzz';
this.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt:'json', callback:'JSON_CALLBACK'},
{get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}}
);
}
BuzzController.prototype = {
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
},
expandReplies: function(activity) {
activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id});
}
};
BuzzController.$inject = ['$resource'];
</script>
<div ng-controller="BuzzController">
<input ng-model="userId"/>
<button ng-click="fetch()">fetch</button>
<hr/>
<div ng-repeat="item in activities.data.items">
<h1 style="font-size: 15px;">
<img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a>
</h1>
{{item.object.content | html}}
<div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;">
<img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}}
</div>
</div>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
angular.module('ngResource', ['ng']).
factory('$resource', ['$http', '$parse', function($http, $parse) {
var DEFAULT_ACTIONS = {
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
var noop = angular.noop,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy,
isFunction = angular.isFunction,
getter = function(obj, path) {
return $parse(path)(obj);
};
/**
* We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace((pctEncodeSpaces ? null : /%20/g), '+');
}
function Route(template, defaults) {
this.template = template = template + '#';
this.defaults = defaults || {};
var urlParams = this.urlParams = {};
forEach(template.split(/\W/), function(param){
if (param && template.match(new RegExp("[^\\\\]:" + param + "\\W"))) {
urlParams[param] = true;
}
});
this.template = template.replace(/\\:/g, ':');
}
Route.prototype = {
url: function(params) {
var self = this,
url = this.template,
encodedVal;
params = params || {};
forEach(this.urlParams, function(_, urlParam){
encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || "");
url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1");
});
url = url.replace(/\/?#$/, '');
var query = [];
forEach(params, function(value, key){
if (!self.urlParams[key]) {
query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value));
}
});
query.sort();
url = url.replace(/\/*$/, '');
return url + (query.length ? '?' + query.join('&') : '');
}
};
function ResourceFactory(url, paramDefaults, actions) {
var route = new Route(url);
actions = extend({}, DEFAULT_ACTIONS, actions);
function extractParams(data){
var ids = {};
forEach(paramDefaults || {}, function(value, key){
ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value;
});
return ids;
}
function Resource(value){
copy(value || {}, this);
}
forEach(actions, function(action, name) {
var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH';
Resource[name] = function(a1, a2, a3, a4) {
var params = {};
var data;
var success = noop;
var error = null;
switch(arguments.length) {
case 4:
error = a4;
success = a3;
//fallthrough
case 3:
case 2:
if (isFunction(a2)) {
if (isFunction(a1)) {
success = a1;
error = a2;
break;
}
success = a2;
error = a3;
//fallthrough
} else {
params = a1;
data = a2;
success = a3;
break;
}
case 1:
if (isFunction(a1)) success = a1;
else if (hasBody) data = a1;
else params = a1;
break;
case 0: break;
default:
throw "Expected between 0-4 arguments [params, data, success, error], got " +
arguments.length + " arguments.";
}
var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data));
$http({
method: action.method,
url: route.url(extend({}, extractParams(data), action.params || {}, params)),
data: data
}).then(function(response) {
var data = response.data;
if (data) {
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item));
});
} else {
copy(data, value);
}
}
(success||noop)(value, response.headers);
}, error);
return value;
};
Resource.bind = function(additionalParamDefaults){
return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
};
Resource.prototype['$' + name] = function(a1, a2, a3) {
var params = extractParams(this),
success = noop,
error;
switch(arguments.length) {
case 3: params = a1; success = a2; error = a3; break;
case 2:
case 1:
if (isFunction(a1)) {
success = a1;
error = a2;
} else {
params = a1;
success = a2 || noop;
}
case 0: break;
default:
throw "Expected between 1-3 arguments [params, success, error], got " +
arguments.length + " arguments.";
}
var data = hasBody ? this : undefined;
Resource[name].call(this, params, data, success, error);
};
});
return Resource;
}
return ResourceFactory;
}]);
})(window, window.angular);
| zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-resource-1.0.0.js | JavaScript | asf20 | 15,889 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document, undefined) {
'use strict';
////////////////////////////////////
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
function fromCharCode(code) {return String.fromCharCode(code);}
var Error = window.Error,
/** holds major version number for IE or NaN for real browsers */
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isObject(obj) && isNumber(obj.length)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value) };
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while(index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
*/
function extend(dst) {
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new (extend(function() {}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || identity)(value);
};
</pre>
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){return typeof value == 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){return typeof value != 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){return value != null && typeof value == 'object';}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){return typeof value == 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){return typeof value == 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
return toString.apply(value) == '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) == '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){return typeof value == 'function';}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) === '[object File]';
}
function isBoolean(value) {
return typeof value == 'boolean';
}
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
}
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.bind && node.find)); // we have a bind and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj = {}, items = str.split(","), i;
for ( i = 0; i < items.length; i++ )
obj[ items[i] ] = true;
return obj;
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
var size = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
return indexOf(array, obj) != -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index = indexOf(array, value);
if (index >=0)
array.splice(index, 1);
return value;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw Error("Can't copy equivalent objects or arrays");
if (isArray(source)) {
while(destination.length) {
destination.pop();
}
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties pass `===` comparison.
* * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
*
* During a property comparision, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only be identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if ((length = o1.length) == o2.length) {
for(key=0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() == o2.getTime();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
keySet = {};
for(key in o1) {
if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) {
return false;
}
keySet[key] = true;
}
for(key in o2) {
if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are are prebound to the function. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (/^\$+/.test(key)) {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch(e) {}
return jqLite('<div>').append(element).html().
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
}
/////////////////////////////////////////////////
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if (keyValue) {
key_value = keyValue.split('=');
key = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace((pctEncodeSpaces ? null : /%20/g), '+');
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp on optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap on application. Only
* one directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* ot the root of the page.
*
* In the example below if the `ngApp` directive would not be placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 = {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements = [element],
appElement,
module,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement = element;
module = (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement = element;
module = attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
element = jqLite(element);
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(
['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator){
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
JQLitePatchJQueryRemove('remove', true);
JQLitePatchJQueryRemove('empty');
JQLitePatchJQueryRemove('html');
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error of the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configure information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Option configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider.directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which needs to be performed when the injector with
* with the current module is finished loading.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
}
}
});
};
});
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.0.0', // all of these placeholder strings will be replaced by rake's
major: 1, // compile task
minor: 0,
dot: 0,
codeName: 'temporal-domination'
};
function publishExternalAPI(angular){
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0}
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$route: $RouteProvider,
$routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/bind/)
* - [children()](http://api.jquery.com/children/)
* - [clone()](http://api.jquery.com/clone/)
* - [contents()](http://api.jquery.com/contents/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name.
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [html()](http://api.jquery.com/html/)
* - [next()](http://api.jquery.com/next/)
* - [parent()](http://api.jquery.com/parent/)
* - [prepend()](http://api.jquery.com/prepend/)
* - [prop()](http://api.jquery.com/prop/)
* - [ready()](http://api.jquery.com/ready/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [toggleClass()](http://api.jquery.com/toggleClass/)
* - [unbind()](http://api.jquery.com/unbind/)
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite:
*
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = JQLite.cache = {},
jqName = JQLite.expando = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); });
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function JQLitePatchJQueryRemove(name, dispatchThis) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch() {
var list = [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children,
fns, events;
while(list.length) {
set = list.shift();
for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
element = jqLite(set[setIndex]);
if (fireEvent) {
events = element.data('events');
if ( (fns = events && events.$destroy) ) {
forEach(fns, function(fn){
fn.handler();
});
}
} else {
fireEvent = !fireEvent;
}
for(childIndex = 0, childLength = (children = element.children()).length;
childIndex < childLength;
childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
throw Error('selectors not implemented');
}
return new JQLite(element);
}
if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
this.remove(); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element){
JQLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteUnbind(element, type, fn) {
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type], fn);
}
}
}
function JQLiteRemoveData(element) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
JQLiteUnbind(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function JQLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
}
}
function JQLiteData(element, key, value) {
var data = JQLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
JQLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
data[key] = value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function JQLiteHasClass(element, selector) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function JQLiteRemoveClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
: [ elements ];
for(var i=0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function JQLiteController(element, name) {
return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
function JQLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if(element[0].nodeType == 9) {
element = element.find('html');
}
while (element.length) {
if (value = element.data(name)) return value;
element = element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
JQLite(window).bind('load', trigger); // fallback to window.onload for others
},
toString: function() {
var value = [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form'.split(','), function(value) {
BOOLEAN_ELEMENTS[uppercase(value)] = true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: JQLiteData,
inheritedData: JQLiteInheritedData,
scope: function(element) {
return JQLiteInheritedData(element, '$scope');
},
controller: JQLiteController ,
injector: function(element) {
return JQLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name)|| noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: extend((msie < 9)
? function(element, value) {
if (element.nodeType == 1 /** Element */) {
if (isUndefined(value))
return element.innerText;
element.innerText = value;
} else {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue = value;
}
}
: function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent = value;
}, {$dv:''}),
val: function(element, value) {
if (isUndefined(value)) {
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
// JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=0; i < this.length; i++) {
if (fn === JQLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
if (this.length)
return fn(this[0], arg1, arg2);
}
} else {
// we are a write, so apply to all children
for(i=0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
return fn.$dv;
};
});
function createEventHandler(element, events) {
var eventHandler = function (event, type) {
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <= 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault = null;
event.stopPropagation = null;
event.isDefaultPrevented = null;
} else {
// It shouldn't affect normal browsers (native methods are defined on prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
bind: function bindFn(element, type, fn){
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!events) JQLiteExpandoStore(element, 'events', events = {});
if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
var counter = 0;
events.mouseenter = [];
events.mouseleave = [];
bindFn(element, 'mouseover', function(event) {
counter++;
if (counter == 1) {
handle(event, 'mouseenter');
}
});
bindFn(element, 'mouseout', function(event) {
counter --;
if (counter == 0) {
handle(event, 'mouseleave');
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
eventFns = events[type]
}
eventFns.push(fn);
});
},
unbind: JQLiteUnbind,
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element){
if (element.nodeName != '#text')
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes;
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType === 1)
element.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index = child;
}
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode)[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
JQLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
return element.nextSibling;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2) {
var value;
for(var i=0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value == undefined ? this : value;
};
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
}
} else {
key = obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array){
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] = value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
return value;
}
};
/**
* A map where multiple values can be added to the same key such that they form a queue.
* @returns {HashQueueMap}
*/
function HashQueueMap() {}
HashQueueMap.prototype = {
/**
* Same as array push, but using an array as the value for the hash
*/
push: function(key, value) {
var array = this[key = hashKey(key)];
if (!array) {
this[key] = [value];
} else {
array.push(value);
}
},
/**
* Same as array shift, but using an array as the value for the hash
*/
shift: function(key) {
var array = this[key = hashKey(key)];
if (array) {
if (array.length == 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick of your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(.+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn')
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following ways are all valid way of annotating function with injection arguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $inject.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $inject.invoke(explicit);
*
* // inline
* $inject.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
* parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
* tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. The function arguments come form the function annotation.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
* all of the arguments to the constructor function as specified by the constructor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is used by the injector
* to determine which services need to be injected into the function when the function is invoked. There are three
* ways in which the function can be annotated with the needed dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
* the function into a string using `toString()` method and extracting the argument names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
* are supported.
*
* # The `$injector` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
* services to be injected into the function.
* <pre>
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
* inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
* minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tempFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
* above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
* The providers share the same name as the instance they create with the `Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow for configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation = 'Hello';
*
* this.salutation = function(text) {
* salutation = text;
* };
*
* this.$get = function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* });
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* )};
*
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
* `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
* into configuration function (other modules) and it is not interceptable by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service instance creation. The
* returned instance may be the original instance, or a new instance which delegates to the
* original instance.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instanciated. The function is called using the {@link AUTO.$injector#invoke
* injector.invoke} method and is therefore fully injectable. Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*/
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = createInternalInjector(providerCache, function() {
throw Error("Unknown provider: " + path.join(' <- '));
}),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
}
}
function provider(name, provider_) {
if (isFunction(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, value) { return factory(name, valueFn(value)); }
function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks = [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
if (isString(module)) {
var moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
try {
for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = invokeArgs[0] == '$injector'
? providerInjector
: providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isFunction(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isArray(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + String(module[module.length - 1]);
throw e;
}
} else {
assertArgFn(module, 'module');
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (typeof serviceName !== 'string') {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw Error('Circular dependency: ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals){
var args = [],
$inject = annotate(fn),
length, i,
key;
for(i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key, path)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
switch (self ? -1 : args.length) {
case 0: return fn();
case 1: return fn(args[0]);
case 2: return fn(args[0], args[1]);
case 3: return fn(args[0], args[1], args[2]);
case 4: return fn(args[0], args[1], args[2], args[3]);
case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
default: return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals);
return isObject(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result = null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) === 'a') result = element;
});
return result;
}
function scroll() {
var hash = $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $locaiton.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function() {return $location.hash();}, function() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}];
}
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
baseElement = document.find('base');
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// setter
if (url) {
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
if (replace) location.replace(url);
else location.href = url;
}
return self;
// getter
} else {
// the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href;
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cokkie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
if (lastCookies.length > 20) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " +
"were already set (" + lastCookies.length + " > 20 )");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1));
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be defered.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchroniously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a defered task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider(){
this.$get = ['$window', '$log', '$sniffer', '$document',
function( $window, $log, $sniffer, $document){
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects.
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache.
* - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key) — Removes a key-value pair from the cache.
* - `{void}` `removeAll() — Removes all cached values.
* - `{void}` `destroy() — Removes references to this cache from $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw Error('cacheId ' + cacheId + ' taken');
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
return caches[cacheId] = {
put: function(key, value) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
},
get: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry = lruHash[key];
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* Cache used for storing html templates.
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
*
* The compilation is a process of walking the DOM tree and trying to match DOM elements to
* {@link ng.$compileProvider.directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original template.
*
<doc:example module="compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}
</script>
<div ng-controller="Ctrl">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
* @param {number} maxPriority only apply directives lower then given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the linking function returns the element of the template. It is either the original element
* passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element = $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directive with compiler
*
* @param {string} name name of the directive.
* @param {function} directiveFactory An injectable directive factory function.
* @returns {ng.$compileProvider} Self for chaining.
*/
$CompileProvider.$inject = ['$provide'];
function $CompileProvider($provide) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ';
/**
* @ngdoc function
* @name ng.$compileProvider.directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register directives with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more
* info.
*/
this.directive = function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directive');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
var booleanKey = getBooleanAttrName(this.$$element[0], key),
$$observers = this.$$observers;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not interpolated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
};
return compile;
//================================
function compile($compileNode, transcludeFn, maxPriority) {
if (!($compileNode instanceof jqLite)) {
// jquery always rewraps, where as we need to preserve the original selector so that we can modify it.
$compileNode = jqLite($compileNode);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNode, function(node, index){
if (node.nodeType == 3 /* text node */) {
$compileNode[index] = jqLite(node).wrap('<span>').parent()[0];
}
});
var compositeLinkFn = compileNodes($compileNode, transcludeFn, $compileNode, maxPriority);
return function(scope, cloneConnectFn){
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode = cloneConnectFn
? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!!
: $compileNode;
$linkNode.data('$scope', scope);
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
return $linkNode;
};
}
function wrongMode(localName, mode) {
throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch(e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
* rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} max directive priority
* @returns {?function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) {
var linkFns = [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for(var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, maxPriority);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
: null;
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal)
? null
: compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn;
for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = nodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new(isObject(nodeLinkFn.scope));
jqLite(node).data('$scope', childScope);
} else {
childScope = scope;
}
childTranscludeFn = nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
nodeLinkFn(childLinkFn, childScope, node, $rootElement,
(function(transcludeFn) {
return function(cloneFn) {
var transcludeScope = scope.$new();
return transcludeFn(transcludeScope, cloneFn).
bind('$destroy', bind(transcludeScope, transcludeScope.$destroy));
};
})(childTranscludeFn || transcludeFn)
);
} else {
nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
}
}
}
}
/**
* Looks for directives on the given node ands them to the directive collection which is sorted.
*
* @param node node to search
* @param directives an array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs the shared attrs object which is used to populate the normalized attributes.
* @param {number=} max directive priority
*/
function collectDirectives(node, directives, attrs, maxPriority) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch(nodeType) {
case 1: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
// iterate over the attributes
for (var attr, name, nName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
attr = nAttrs[j];
if (attr.specified) {
name = attr.name;
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
attrs[nName] = value = trim((msie && name == 'href')
? decodeURIComponent(node.getAttribute(name, 2))
: attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority);
}
}
// use class as directive
className = node.className;
if (isString(className)) {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case 3: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Once the directives have been collected their compile functions is executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached..
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement} $rootElement If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace widgets on it.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) {
var terminalPriority = -Number.MAX_VALUE,
preLinkFns = [],
postLinkFns = [],
newScopeDirective = null,
newIsolatedScopeDirective = null,
templateDirective = null,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
transcludeDirective,
childTranscludeFn = transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, $compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolatedScopeDirective = directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (directiveValue = directive.controller) {
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
terminalPriority = directive.priority;
if (directiveValue == 'element') {
$template = jqLite(compileNode);
$compileNode = templateAttrs.$$element =
jqLite('<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->');
compileNode = $compileNode[0];
replaceWith($rootElement, jqLite($template[0]), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority);
} else {
$template = jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directiveValue = directive.template) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
$template = jqLite('<div>' + trim(directiveValue) + '</div>').contents();
compileNode = $template[0];
if (directive.replace) {
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
}
replaceWith($rootElement, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that were already applied and those that weren't
// - collect directives from the template, add them to the second group and sort them
// - append the second group with new directives to the first group
directives = directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length - (i + 1)),
newTemplateAttrs
)
);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace,
childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post) {
if (pre) {
pre.require = directive.require;
preLinkFns.push(pre);
}
if (post) {
post.require = directive.require;
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod = 'data', optional = false;
if (isString(require)) {
while((value = require.charAt(0)) == '^' || value == '?') {
require = require.substr(1);
if (value == '^') {
retrievalMethod = 'inheritedData';
}
optional = optional || value == '?';
}
value = $element[retrievalMethod]('$' + require + 'Controller');
if (!value && !optional) {
throw Error("No controller: " + require);
}
return value;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller;
if (compileNode === linkNode) {
attrs = templateAttrs;
} else {
attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
}
$element = attrs.$$element;
if (newScopeDirective && isObject(newScopeDirective.scope)) {
var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/;
var parentScope = scope.$parent || scope;
forEach(newScopeDirective.scope, function(definiton, scopeName) {
var match = definiton.match(LOCAL_REGEXP) || [],
attrName = match[2]|| scopeName,
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
switch (mode) {
case '@': {
attrs.$observe(attrName, function(value) {
scope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = parentScope;
break;
}
case '=': {
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
' (directive: ' + newScopeDirective.name + ')');
};
lastValue = scope[scopeName] = parentGet(parentScope);
scope.$watch(function() {
var parentValue = parentGet(parentScope);
if (parentValue !== scope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !== lastValue) {
// parent changed and it has precedence
lastValue = scope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, lastValue = scope[scopeName]);
}
}
return parentValue;
});
break;
}
case '&': {
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(parentScope, locals);
}
break;
}
default: {
throw Error('Invalid isolate scope definition for directive ' +
newScopeDirective.name + ': ' + definiton);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
};
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
$element.data(
'$' + directive.name + 'Controller',
$controller(controller, locals));
});
}
// PRELINKING
for(i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for(i = 0, ii = postLinkFns.length; i < ii; i++) {
try {
linkFn = postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority) {
var match = false;
if (hasDirectives.hasOwnProperty(name)) {
for(var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i<ii; i++) {
try {
directive = directives[i];
if ( (maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
tDirectives.push(directive);
match = true;
}
} catch(e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key]) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
$rootElement, replace, childTranscludeFn) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
// The fact that we have to copy and patch the directive seems wrong!
derivedSyncDirective = extend({}, origAsyncDirective, {
controller: null, templateUrl: null, transclude: null
});
$compileNode.html('');
$http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
if (replace) {
$template = jqLite('<div>' + trim(content) + '</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives, tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn);
afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn);
while(linkQueue.length) {
var controller = linkQueue.pop(),
linkRootElement = linkQueue.pop(),
beforeTemplateLinkNode = linkQueue.pop(),
scope = linkQueue.pop(),
linkNode = compileNode;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
}, scope, linkNode, $rootElement, controller);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw Error('Failed to load template: ' + config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw Error('Multiple directives [' + previousDirective.name + ', ' +
directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function(scope, node) {
var parent = node.parent(),
bindings = parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings), 'ng-binding');
scope.$watch(interpolateFn, function(value) {
node[0].nodeValue = value;
});
})
});
}
}
function addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
directives.push({
priority: 100,
compile: valueFn(function(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (name === 'class') {
// we need to interpolate classes again, in the case the element was replaced
// and therefore the two class attrs got merged - we want to interpolate the result
interpolateFn = $interpolate(attr[name], true);
}
attr[name] = undefined;
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function(value) {
attr.$set(name, value);
});
})
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
* but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, $element, newNode) {
var oldNode = $element[0],
parent = oldNode.parentNode,
i, ii;
if ($rootElement) {
for(i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == oldNode) {
$rootElement[i] = newNode;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, oldNode);
}
newNode[jqLite.expando] = oldNode[jqLite.expando];
$element[0] = newNode;
}
}];
}
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:DiRective
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
* @description
*
* A shared object between directive compile / linking functions which contains normalized DOM element
* attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
* since all of these are treated as equivalent in Angular:
*
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(constructor, locals) {
if(isString(constructor)) {
var name = constructor;
constructor = controllers.hasOwnProperty(name)
? controllers[name]
: getter(locals.$scope, name, true) || getter($window, name, true);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
function $DocumentProvider(){
this.$get = ['$window', function(window){
return jqLite(window.document);
}];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler}
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log){
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
/**
* @ngdoc function
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Deafults to `{{` and `}}`.
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @prop {string=} value new value to set the starting symbol to.
*/
this.startSymbol = function(value){
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @prop {string=} value new value to set the ending symbol to.
*/
this.endSymbol = function(value){
if (value) {
endSymbol = value;
return this;
} else {
return startSymbol;
}
};
this.$get = ['$parse', function($parse) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
<pre>
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @returns {function(context)} an interpolation function which is used to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
return function(text, mustHaveExpression) {
var startIndex,
endIndex,
index = 0,
parts = [],
length = text.length,
hasInterpolation = false,
fn,
exp,
concat = [];
while(index < length) {
if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
(index != startIndex) && parts.push(text.substring(index, startIndex));
parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
fn.exp = exp;
index = endIndex + endSymbolLength;
hasInterpolation = true;
} else {
// we did not find anything, so we have to add the remainder to the parts array
(index != length) && parts.push(text.substring(index));
index = length;
}
}
if (!(length = parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length = 1;
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
};
fn.exp = text;
fn.parts = parts;
return fn;
}
};
}];
}
var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH = PATH_MATCH,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function stripHash(url) {
return url.split('#')[0];
}
function matchUrl(url, obj) {
var match = URL_MATCH.exec(url);
match = {
protocol: match[1],
host: match[3],
port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol = match.protocol;
obj.$$host = match.host;
obj.$$port = match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
match.hash.indexOf(hashPrefix) !== 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) +
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) == basePath) {
return url;
// convert html5 url -> hashbang url
} else {
var search = match.search && '?' + match.search || '',
hash = match.hash && '#' + match.hash || '',
pathPrefix = pathPrefixFromBase(basePath),
path = match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
}
return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} url HTML5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix, appBaseUrl) {
pathPrefix = pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(newAbsoluteUrl) {
var match = matchUrl(newAbsoluteUrl, this);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
}
this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
this.$$search = parseKeyValue(match.search);
this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
pathPrefix + this.$$url;
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is disabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and search)
*/
function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
}
basePath = match.path + (match.search ? '?' + match.search : '');
match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
if (match[1]) {
this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
} else {
this.$$path = '';
}
this.$$search = parseKeyValue(match[3]);
this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
LocationUrl.prototype = {
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|object<string,string>=} search New search params - string or hash object
* @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If the value is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
} else {
this.$$search = isString(search) ? parseKeyValue(search) : search;
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
LocationHashbangUrl.apply(this, arguments);
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
}
}
}
LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider(){
var hashPrefix = '',
html5Mode = false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {string=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isDefined(mode)) {
html5Mode = mode;
return this;
} else {
return html5Mode;
}
};
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
basePath,
pathPrefix,
initUrl = $browser.url(),
initUrlParts = matchUrl(initUrl),
appBaseUrl;
if (html5Mode) {
basePath = $browser.baseHref() || '/';
pathPrefix = pathPrefixFromBase(basePath);
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
pathPrefix + '/';
if ($sniffer.history) {
$location = new LocationUrl(
convertToHtml5Url(initUrl, basePath, hashPrefix),
pathPrefix, appBaseUrl);
} else {
$location = new LocationHashbangInHtml5Url(
convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
}
} else {
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
(initUrlParts.path || '') +
(initUrlParts.search ? ('?' + initUrlParts.search) : '') +
'#' + hashPrefix + '/';
$location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
}
$rootElement.bind('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !== 'a') {
if (elm[0] === $rootElement[0]) return;
elm = elm.parent();
}
var absHref = elm.prop('href'),
rewrittenUrl = $location.$$rewriteAppUrl(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
event.preventDefault();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() != initUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() != newUrl) {
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl = $browser.url();
if (!changeCounter || oldUrl != $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), $location.$$replace);
$location.$$replace = false;
afterLocationChange(oldUrl);
}
});
}
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
}
}];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @example
<doc:example>
<doc:source>
<script>
function LogCtrl($log) {
this.$log = $log;
this.message = 'Hello World!';
}
</script>
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $LogProvider(){
this.$get = ['$window', function($window){
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2);
}
}
}];
}
var OPERATORS = {
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);},
'-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
'=':noop,
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, csp){
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2];
if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName;
while (index < text.length) {
var ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while(peekIndex < text.length) {
var ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
if(json){
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain =
function() { throwError("is not valid json", {text:text, index:0}); };
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self, locals) {
return fn(self, locals, right);
};
}
function binaryFn(left, fn, right) {
return function(self, locals) {
return fn(self, locals, left, right);
};
}
function statements() {
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1
? statements[0]
: function(self, locals){
var value;
for ( var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while(true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, locals, input){
var args = [input];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = logicalOR();
return function(self, locals){
return left.assign(self, right(self, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==','!='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp);
return extend(
function(self, locals) {
return getter(object(self, locals), locals);
},
{
assign:function(self, value, locals) {
return setter(object(self, locals), field, value);
}
}
);
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function(self, locals){
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = o[i];
if (v && v.then) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) { p.$$v = val; });
}
v = v.$$v;
}
return v;
}, {
assign:function(self, value, locals){
return obj(self, locals)[indexFn(self, locals)] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(self, locals){
var args = [],
context = contextGetter ? contextGetter(self, locals) : self;
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
var fnPtr = fn(self, locals) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
if (peekToken().text != ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function(self, locals){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
};
}
function object () {
var keyValues = [];
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
} while (expect(','));
}
consume('}');
return function(self, locals){
var object = {};
for ( var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
var value = keyValue.value(self, locals);
object[keyValue.key] = value;
}
return object;
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accesible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accesbile by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4) {
return function(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
};
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
: function(scope, locals) {
var i = 0, val
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n';
});
code += 'return s;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() { return code; };
}
return getterFnCache[path] = fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against (Topically a scope object).
* * `locals`: local variables context object, useful for overriding values in `context`.
*
* The return function also has an `assign` property, if the expression is assignable, which
* allows one to set values to expressions.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] = parser(exp, false, $filter, $sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise apis are to
* asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` and `scope` are
* // available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* );
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of
* [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as apis
* that can be used for signaling the successful or unsuccessful completion of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
* or rejected calls one of the success or error callbacks asynchronously as soon as the result
* is available. The callbacks are called with a single argument the result or rejection reason.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback` or `errorCallback`.
*
*
* # Chaining promises
*
* Because calling `then` api of a promise returns a new derived promise, it is easily possible
* to create a chain of promises:
*
* <pre>
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and it's value will be
* // the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful apis like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - $q promises are recognized by the templating engine in angular, which means that in templates
* you can treat promises attached to a scope as if they were the resulting values.
* - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
var pending = [],
value, deferred;
deferred = {
resolve: function(val) {
if (pending) {
var callbacks = pending;
pending = undefined;
value = ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
value.then(callback[0], callback[1]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
promise: {
then: function(callback, errback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((callback || defaultCallback)(value));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((errback || defaultErrback)(reason));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback]);
} else {
value.then(wrappedCallback, wrappedErrback);
}
return result.promise;
}
}
};
return deferred;
};
var ref = function(value) {
if (value && value.then) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* <pre>
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
result.resolve((errback || defaultErrback)(reason));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with on object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value coresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
var when = function(value, callback, errback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>} promises An array of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value coresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
function all(promises) {
var deferred = defer(),
counter = promises.length,
results = [];
if (counter) {
forEach(promises, function(promise, index) {
ref(promise).then(function(value) {
if (index in results) return;
results[index] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (index in results) return;
deferred.reject(reason);
});
});
} else {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* @ngdoc object
* @name ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link ng.$route $route} for an example.
*/
function $RouteProvider(){
var routes = {};
/**
* @ngdoc method
* @name ng.$routeProvider#when
* @methodOf ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exacly match the
* route definition.
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{function()=}` – Controller fn that should be associated with newly
* created scope.
* - `template` – `{string=}` – html template as a string that should be used by
* {@link ng.directive:ngView ngView} or
* {@link ng.directive:ngInclude ngInclude} directives.
* this property takes precedence over `templateUrl`.
* - `templateUrl` – `{string=}` – path to an html template that should be used by
* {@link ng.directive:ngView ngView}.
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, they will be
* resolved and converted to a value before the controller is instantiated and the
* `$aftreRouteChange` event is fired. The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is resolved
* before its value is injected into the controller.
*
* - `redirectTo` – {(string|function())=} – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
routes[path] = extend({reloadOnSearch: true}, route);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length-1] == '/')
? path.substr(0, path.length-1)
: path +'/';
routes[redirectPath] = {redirectTo: path};
}
return this;
};
/**
* @ngdoc method
* @name ng.$routeProvider#otherwise
* @methodOf ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
* @returns {Object} self
*/
this.otherwise = function(params) {
this.when(null, params);
return this;
};
this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) {
/**
* @ngdoc object
* @name ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
* directive and the {@link ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link ng.directive:script inlined templates}
to get it working on jsfiddle as well.
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeStart
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occurs.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeSuccess
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ng.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeError
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name ng.$route#$routeUpdate
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var matcher = switchRouteMatcher,
forceReload = false,
$route = {
routes: routes,
/**
* @ngdoc method
* @name ng.$route#reload
* @methodOf ng.$route
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ng.directive:ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
forceReload = true;
$rootScope.$evalAsync(updateRoute);
}
};
$rootScope.$on('$locationChangeSuccess', updateRoute);
return $route;
/////////////////////////////////////////////////////
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should construct the route matching
// regex only once and then reuse it
var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$',
params = [],
dst = {};
forEach(when.split(/\W/), function(param) {
if (param) {
var paramRegExp = new RegExp(":" + param + "([\\W])");
if (regex.match(paramRegExp)) {
regex = regex.replace(paramRegExp, "([^\\/]*)$1");
params.push(param);
}
}
});
var match = on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] = match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$route === last.$route
&& equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
last.params = next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload = false;
$rootScope.$broadcast('$routeChangeStart', next, last);
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
.replace();
}
}
}
$q.when(next).
then(function() {
if (next) {
var keys = [],
values = [],
template;
forEach(next.resolve || {}, function(value, key) {
keys.push(key);
values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value));
});
if (isDefined(template = next.template)) {
} else if (isDefined(template = next.templateUrl)) {
template = $http.get(template, {cache: $templateCache}).
then(function(response) { return response.data; });
}
if (isDefined(template)) {
keys.push('$template');
values.push(template);
}
return $q.all(values).then(function(values) {
var locals = {};
forEach(values, function(value, index) {
locals[keys[index]] = value;
});
return locals;
});
}
}).
// after route change
then(function(locals) {
if (next == $route.current) {
if (next) {
next.locals = locals;
copy(next.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', next, last);
}
}, function(error) {
if (next == $route.current) {
$rootScope.$broadcast('$routeChangeError', next, last, error);
}
});
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = matcher($location.path(), path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string||'').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
/**
* @ngdoc object
* @name ng.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination of the
* {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
* are extracted when the {@link ng.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get = valueFn({});
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope ware heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive from speed as well as memory:
* - no closures, instead ups prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the begging (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using array would be slow since inserts in meddle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of digest iteration the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider(){
var TTL = 10;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse',
function( $injector, $exceptionHandler, $parse) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
angular.injector(['ng']).invoke(function($rootScope) {
var scope = $rootScope.$new();
scope.salutation = 'Hello';
scope.name = 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function() {
this.greeting = this.salutation + ' ' + this.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name = 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
});
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be provided
* for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this['this'] = this.$root = this;
this.$$asyncQueue = [];
this.$$listeners = {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
Scope.prototype = {
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
* the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate if true then the scoped does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not se parent scope properties.
* When creating widgets it is useful for the widget to not accidently read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isFunction(isolate)) {
// TODO: remove at some point
throw Error('API-CHANGE: Use $controller to instantiate controllers.');
}
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class
// name in the debugger.
Child.prototype = this;
child = new Child();
child.$id = nextUid();
}
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$$asyncQueue = [];
child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
* should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression' are not equal (with the exception of the initial run
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison
* {@link angular.copy} function is used. It also means that watching complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detected. The rerun iteration
* limit is 100 to prevent infinity loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
*
* @param {boolean=} objectEquality Compare object for equality rather then for refference.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
// in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop, 'listener');
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
* Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
* `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loop. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
*
* Usually you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider.directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
* {@link ng.$compileProvider.directive directives}) will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to simulate the scope
* life-cycle.
*
* # Example
* <pre>
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
counter = counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg;
beginPhase('$digest');
do {
dirty = false;
current = target;
do {
asyncQueue = current.$$asyncQueue;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(value) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString())
: watch.exp;
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if(dirty && !(ttl--)) {
clearPhase();
throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Remove the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it chance to
* perform any necessary cleanup.
*/
$destroy: function() {
if ($rootScope == this) return; // we can't remove the root node;
var parent = this.$parent;
this.$broadcast('$destroy');
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope returning the result. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluating engular expressions.
*
* # Example
* <pre>
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* </pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
*
* - it will execute in the current script execution context (before any DOM rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life-cycle
* of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
* was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listen on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
* event life cycle.
*
* @param {string} name Event name to listen on.
* @param {function(event)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*
* The event listener function format is: `function(event)`. The `event` object passed into the
* listener has the following attributes
*
* - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
* - `currentScope` - {Scope}: the current scope which is handling the event.
* - `name` - {string}: Name of the event.
* - `stopPropagation` - {function=}: calling `stopPropagation` function will cancel further event propagation
* (available only for events that were `$emit`-ed).
* - `preventDefault` - {function}: calling `preventDefault` sets `defaultPrevented` flag to true.
* - `defaultPrevented` - {boolean}: true if `preventDefault` was called.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
arrayRemove(namedListeners, listener);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and calls all registered
* listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i=0, length=namedListeners.length; i<length; i++) {
try {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//traverse upwards
scope = scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes of the current scope and
* calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1);
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
forEach(current.$$listeners[name], function(listener) {
try {
listener.apply(null, listenerArgs);
} catch(e) {
$exceptionHandler(e);
}
});
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
return event;
}
};
var $rootScope = new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw Error($rootScope.$$phase + ' already in progress');
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function compileToFn(exp, name) {
var fn = $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's uniqueue we can easily tell it apart from other values
*/
function initWatchVal() {}
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', function($window) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
history: !!($window.history && $window.history.pushState && !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = $window.document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without triggering alerts
csp: false
};
}];
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overriden, removed or mocked for testing.
*
* All expressions are evaluated with respect to current scope so they don't
* suffer from window globality.
*
* @example
<doc:example>
<doc:source>
<input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $WindowProvider(){
this.$get = valueFn(window);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data = fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $config = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data, true);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'
},
post: {'Content-Type': 'application/json;charset=utf-8'},
put: {'Content-Type': 'application/json;charset=utf-8'}
}
};
var providerResponseInterceptors = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http'),
responseInterceptors = [];
forEach(providerResponseInterceptors, function(interceptor) {
responseInterceptors.push(
isString(interceptor)
? $injector.get(interceptor)
: $injector.invoke(interceptor)
);
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBacked
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patters this doesn't matter much, for advanced usage,
* it is important to familiarize yourself with these apis and guarantees they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an http request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with status
* // code outside of the <200, 400) range
* });
* </pre>
*
* Since the returned value of calling the $http function is a Promise object, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the api signature and type info below for more
* details.
*
*
* # Shortcut methods
*
* Since all invocation of the $http service require definition of the http method and url and
* POST and PUT requests require response body/data to be provided as well, shortcut methods
* were created to simplify using the api:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain http headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `X-Requested-With: XMLHttpRequest`
* - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from this configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with name equal to the lower-cased http method name, e.g.
* `$httpProvider.defaults.headers.get['My-Header']='value'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar
* fassion as described above.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform functions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - if the `data` property of the request config object contains an object, serialize it into
* JSON format.
*
* Response transformations:
*
* - if XSRF prefix is detected, strip it (see Security Considerations section below)
* - if json response is detected, deserialize it using a JSON parser
*
* To override these transformation locally, specify transform functions as `transformRequest`
* and/or `transformResponse` properties of the config object. To globally override the default
* transforms, override the `$httpProvider.defaults.transformRequest` and
* `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`.
*
*
* # Caching
*
* To enable caching set the configuration property `cache` to `true`. When the cache is
* enabled, `$http` stores the response from the server in local cache. Next time the
* response is served from the cache without sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same url that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response for the first request.
*
*
* # Response interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of synchronous or
* asynchronous preprocessing of received responses, it is desirable to be able to intercept
* responses for http requests before they are handed over to the application code that
* initiated these requests. The response interceptors leverage the {@link ng.$q
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
*
* The interceptors are service factories that are registered with the $httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor — a function that
* takes a {@link ng.$q promise} and returns the original or a new promise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability} allows third party web-site to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
* an unauthorized site can gain your user's private data. Angular provides following mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that
* runs on your domain could read the cookie, your server can be assured that the XHR came from
* JavaScript running on your domain.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have read the token. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript making
* up its own tokens). We recommend that the token is a digest of your site's authentication
* cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
* `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server.
* - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number}` – timeout in milliseconds.
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example>
<file name="index.html">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(config) {
config.method = uppercase(config.method);
var reqTransformFn = config.transformRequest || $config.transformRequest,
respTransformFn = config.transformResponse || $config.transformResponse,
defHeaders = $config.headers,
reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']},
defHeaders.common, defHeaders[lowercase(config.method)], config.headers),
reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn),
promise;
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
// send request
promise = sendReq(config, reqData, reqHeaders);
// transform future response
promise = promise.then(transformResponse, transformResponse);
// apply interceptors
forEach(responseInterceptors, function(interceptor) {
promise = interceptor(promise);
});
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response, {
data: transformData(response.data, response.headers, respTransformFn)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = $config;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if (config.cache && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache : defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (cachedResp) {
if (cachedResp.then) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the backend
if (!cachedResp) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString)]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
$rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value == null || value == undefined) return;
if (isObject(value)) {
value = toJson(value);
}
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
}];
}
var XHR = window.XMLHttpRequest || function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
var status;
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the
// response is in the cache. the promise api will ensure that to the app code the api is
// always async
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
completeRequest(
callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders());
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
xhr.send(post || '');
if (timeout > 0) {
$browserDefer(function() {
status = -1;
xhr.abort();
}, timeout);
}
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1];
// fix status code for file protocol (it's always 0)
status = (protocol == 'file') ? (response ? 200 : 404) : status;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status == 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
}
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider(){
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a the timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, who's execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {*} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup = function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
promise.then(cleanup, cleanup);
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
* achieve this a filter definition consists of a factory function which is annotated with dependencies and is
* responsible for creating a the filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
* Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression | [ filter_name ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}];
////////////////////////////////////////
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @example
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"å><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng-repeat="friend in friends | filter:search">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression) {
if (!(array instanceof Array)) return array;
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
var search = function(obj, text){
if (text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
return false;
case "array":
for ( var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression = {$:expression};
case "object":
for (var key in expression) {
if (key == '$') {
(function() {
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function() {
var path = key;
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
}
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
if (numStr.indexOf('e') !== -1) {
formatedText = numStr;
} else {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize);
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var offset = date.getTimezoneOffset();
return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2);
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h o''clock"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ).
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array containing only a specified number of elements in an array. The elements
* are taken from either the beginning or the end of the source array, as specified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `limit` number is
* positive, `limit` number of items from the beginning of the source array are copied.
* If the number is negative, `limit` number of items from the end of the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit`
* elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.limit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="limit">
<p>Output: {{ numbers | limitTo:limit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit = int(limit);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more informaton about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate = '-age';
}
</script>
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
<tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
if (!(array instanceof Array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = $parse(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy = [];
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") v1 = v1.toLowerCase();
if (t1 == "string") v2 = v2.toLowerCase();
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
}
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/*
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* <a href="" ng-click="model.$save()">Save</a>
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
// turn <a href ng-click="..">link</a> into a link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!attr.href) {
attr.$set('href', '');
}
return function(scope, element) {
element.bind('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe('');
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng-init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngMultiple
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngMultiple` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
<select id="select" ng-multiple="checked">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element SELECT
* @param {expression} ngMultiple Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function(value) {
attr.$set(attrName, !!value);
});
};
}
};
};
});
// ng-src, ng-href are interpolated
forEach(['src', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect
if (msie) element.prop(attrName, value);
});
}
};
};
});
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containg forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
*
* @property {Object} $error Is an object hash, containing references to all invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`),
* - values are arrays of controls or forms that are invalid with given error.
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form = this,
parentForm = element.parent().controller('form') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
errors = form.$error = {};
// init state
form.$name = attrs.name;
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
form.$addControl = function(control) {
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] = control;
}
};
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
};
form.$setValidity = function(validationToken, isValid, control) {
var queue = errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid = true;
form.$invalid = false;
}
errors[validationToken] = false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] = queue = [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid = false;
form.$invalid = true;
}
};
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In angular forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in application specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
* is because of the following form submission rules coming from the html spec:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType = 'guest';
}
</script>
<form name="myForm" ng-controller="Ctrl">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveDir = {
name: 'form',
restrict: 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
formElement.bind('submit', function(event) {
event.preventDefault();
});
}
var parentFormCtrl = formElement.parent().controller('form'),
alias = attr.name || attr.ngForm;
if (alias) {
scope[alias] = controller;
}
if (parentFormCtrl) {
formElement.bind('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
scope[alias] = undefined;
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
var formDirective = valueFn(formDirectiveDir);
var ngFormDirective = valueFn(extend(copy(formDirectiveDir), {restrict: 'EAC'}));
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\w*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less then `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value = 12;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<span class="error" ng-show="myForm.list.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'http://google.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'me@example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('me@example.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color = 'blue';
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" value="green"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngTrueValue The value to which the expression should be set when selected.
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = trim(element.val());
if (ctrl.$viewValue !== value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.bind('input', listener);
} else {
var timeout;
element.bind('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
});
// if user paste into input using mouse, we need "change" event to catch it
element.bind('change', listener);
}
ctrl.$render = function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator;
var validate = function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
if (pattern.match(/^\/(.*)\/$/)) {
pattern = new RegExp(pattern.substr(1, pattern.length - 2));
patternValidator = function(value) {
return validate(pattern, value)
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength = int(attr.ngMinlength);
var minLengthValidator = function(value) {
if (!isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength = int(attr.ngMaxlength);
var maxLengthValidator = function(value) {
if (!isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min = parseFloat(attr.min);
var minValidator = function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator = function(value) {
if (isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator = function(value) {
if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.bind('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue = attr.ngTrueValue,
falseValue = attr.ngFalseValue;
if (!isString(trueValue)) trueValue = true;
if (!isString(falseValue)) falseValue = false;
element.bind('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
ctrl.$formatters.push(function(value) {
return value === trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller="Ctrl">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function() {
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
$browser);
}
}
};
}];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
* all of these functions to sanitize / convert the value as well as validate.
*
* @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
* these functions to convert the value as well as validate.
*
* @property {Object} $error An bject hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS update, value formatting and parsing. It
* specifically does not contain any logic which deals with DOM rendering or listening to
* DOM events. The `NgModelController` is meant to be extended by other directives where, the
* directive provides DOM manipulation and the `NgModelController` provides the data-binding.
*
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* <example module="customControl">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable = element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$name = $attr.name;
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign;
if (!ngModelSet) {
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
' (' + startingTag($element) + ')');
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*/
this.$render = noop;
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
$error = this.$error = {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control changes validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
this.$setValidity = function(validationErrorKey, isValid) {
if ($error[validationErrorKey] === !isValid) return;
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid = true;
this.$invalid = false;
}
} else {
toggleValidCss(false);
this.$invalid = true;
this.$valid = false;
invalidCount++;
}
$error[validationErrorKey] = !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `formatters` and if resulted value is valid, updates the model and
* calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue = function(value) {
this.$viewValue = value;
// change to dirty
if (this.$pristine) {
this.$dirty = true;
this.$pristine = false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value = fn(value);
});
if (this.$modelValue !== value) {
this.$modelValue = value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
})
}
};
// model -> value
var ctrl = this;
$scope.$watch(ngModelGet, function(value) {
// ignore change from view
if (ctrl.$modelValue === value) return;
var formatters = ctrl.$formatters,
idx = formatters.length;
ctrl.$modelValue = value;
while(idx--) {
value = formatters[idx](value);
}
if (ctrl.$viewValue !== value) {
ctrl.$viewValue = value;
ctrl.$render();
}
});
}];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* Is directive that tells Angular to do two-way data binding. It works together with `input`,
* `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
*
* `ngModel` is responsible for:
*
* - binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require,
* - providing validation behavior (i.e. required, number, email, url),
* - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective = function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
element.bind('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller="Controller">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* debug = {{confirmed}}<br />
* counter = {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function() {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective = valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between comma-seperated string into an array of strings.
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['igor', 'misko', 'vojta'];
}
</script>
<form name="myForm" ng-controller="Ctrl">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<tt>names = {{names}}</tt><br/>
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList || ',';
var parse = function(viewValue) {
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value) && !equals(parse(ctrl.$viewValue), value)) {
return value.join(', ');
}
return undefined;
});
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function(value) {
attr.$set('value', value, false);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when
* it's desirable to put bindings into template that is momentarily displayed by the browser in its
* raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the
* bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function(value) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text should be replaced with the template in ngBindTemplate.
* Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtmlUnsafe
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
* {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
* restrictive and when you absolutely trust the source of the content you are binding to.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlUnsafeDirective = [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function(value) {
element.html(value || '');
});
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
scope.$watch(attr[name], function(newVal, oldVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && (newVal !== oldVal)) {
if (isObject(oldVal) && !isArray(oldVal))
oldVal = map(oldVal, function(v, k) { if (v) return k });
element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal);
}
if (isObject(newVal) && !isArray(newVal))
newVal = map(newVal, function(v, k) { if (v) return k });
if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); }
}, true);
});
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an
* expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the classes
* new classes are added.
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.my-class {
color: red;
}
</file>
<file name="scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
*
* @description
* The `ngClassOdd` and `ngClassEven` works exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but typically a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser view.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], .ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* alternatively, the css rule (above) must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the `{@link ng.$route}`
* service.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
* constructor function.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update.
<doc:example>
<doc:source>
<script>
function SettingsController($scope) {
$scope.name = "John Smith";
$scope.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ];
$scope.greet = function() {
alert(this.name);
};
$scope.addContact = function() {
this.contacts.push({type:'email', value:'yourname@example.org'});
};
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
}
</script>
<div ng-controller="SettingsController">
Name: <input type="text" ng-model="name"/>
[ <a href="" ng-click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="clearContact(contact)">clear</a>
| <a href="" ng-click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
expect(element('.doc-example-live li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li:nth-child(2) input').val())
.toBe('john.smith@example.org');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('');
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live li:nth-child(3) input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective = [function() {
return {
scope: true,
controller: '@'
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
* @priority 1000
*
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
* This directive should be used on the root element of the application (typically the `<html>`
* element or other element with the {@link ng.directive:ngApp ngApp}
* directive).
*
* If enabled the performance of template expression evaluator will suffer slightly, so don't enable
* this mode unless you need it.
*
* @element html
*/
var ngCspDirective = ['$sniffer', function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp = true;
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.bind(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}];
}
);
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* dblclick. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page).
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if (this.text) {
this.list.push(this.text);
this.text = '';
}
};
}
</script>
<form ng-submit="submit()" ng-controller="Ctrl">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
element.bind('submit', function() {
scope.$apply(attrs.ngSubmit);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
* file:// access on some browsers).
*
* @scope
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example>
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url"></div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]').text()).toEqual('');
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile',
function($http, $templateCache, $anchorScroll, $compile) {
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, element) {
var changeCounter = 0,
childScope;
var clearContent = function() {
if (childScope) {
childScope.$destroy();
childScope = null;
}
element.html('');
};
scope.$watch(srcExp, function(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
if (childScope) childScope.$destroy();
childScope = scope.$new();
element.html(response);
$compile(element.contents())(childScope);
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter) clearContent();
});
} else clearContent();
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective = ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. You will see the use of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspoding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}
</script>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
var BRACE = /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp),
whensExpFns = {};
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, '{{' + numberExp + '-' + offset + '}}'));
});
scope.$watch(function() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!whens[value]) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function(newVal) {
element.text(newVal);
});
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
* * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
* * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
*
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng-repeat', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
var ngRepeatDirective = ngDirective({
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function(scope, iterStartElement, attr){
var expression = attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
lhs + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = match[2];
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is an array of objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
// We need an array of these objects since the same object can be returned from the iterator.
// We expect this to be a rare case.
var lastOrder = new HashQueueMap();
scope.$watch(function(scope){
var index, length,
collection = scope.$eval(rhs),
collectionLength = size(collection, true),
childScope,
// Same as lastOrder but it has the current state. It will become the
// lastOrder on the next iteration.
nextOrder = new HashQueueMap(),
key, value, // key/value of iteration
array, last, // last object information {scope, element, index}
cursor = iterStartElement; // current position of the node
if (!isArray(collection)) {
// if object, extract keys, sort them and use to determine order of iteration over obj props
array = [];
for(key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
array.push(key);
}
}
array.sort();
} else {
array = collection || [];
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = array.length; index < length; index++) {
key = (collection === array) ? index : array[index];
value = collection[key];
last = lastOrder.shift(value);
if (last) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = last.scope;
nextOrder.push(value, last);
if (index === last.index) {
// do nothing
cursor = last.element;
} else {
// existing item which got moved
last.index = index;
// This may be a noop, if the element is next, but I don't know of a good way to
// figure this out, since it would require extra DOM access, so let's just hope that
// the browsers realizes that it is noop, and treats it as such.
cursor.after(last.element);
cursor = last.element;
}
} else {
// new item which we don't know about
childScope = scope.$new();
}
childScope[valueIdent] = value;
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === (collectionLength - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
if (!last) {
linker(childScope, function(clone){
cursor.after(clone);
last = {
scope: childScope,
element: (cursor = clone),
index: index
};
nextOrder.push(value, last);
});
}
}
//shrink children
for (key in lastOrder) {
if (lastOrder.hasOwnProperty(key)) {
array = lastOrder[key];
while(array.length) {
value = array.pop();
value.element.remove();
value.scope.$destroy();
}
}
}
lastOrder = nextOrder;
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/>
Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngShowDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngShow, function(value){
element.css('display', toBoolean(value) ? '' : 'none');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` and `ngShow` directives hide or show a portion
* of the HTML conditionally.
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} truthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngHideDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngHide, function(value){
element.css('display', toBoolean(value) ? 'none' : '');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* Conditionally change the DOM structure.
*
* @usageContent
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* ...
* <ANY ng-switch-default>...</ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed.
* * `ngSwitchDefault`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</script>
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
</div>
</doc:source>
<doc:scenario>
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
});
it('should select deafault', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</doc:scenario>
</doc:example>
*/
var NG_SWITCH = 'ng-switch';
var ngSwitchDirective = valueFn({
restrict: 'EA',
compile: function(element, attr) {
var watchExpr = attr.ngSwitch || attr.on,
cases = {};
element.data(NG_SWITCH, cases);
return function(scope, element){
var selectedTransclude,
selectedElement,
selectedScope;
scope.$watch(watchExpr, function(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement = selectedScope = null;
}
if ((selectedTransclude = cases['!' + value] || cases['?'])) {
scope.$eval(attr.change);
selectedScope = scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement = caseElement;
element.append(caseElement);
});
}
});
};
}
});
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases = element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['!' + attrs.ngSwitchWhen] = transclude;
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases = element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['?'] = transclude;
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @element ANY
*
* @example
<doc:example module="transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { title:'bind' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller="Ctrl">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective = ngDirective({
controller: ['$transclude', '$element', function($transclude, $element) {
$transclude(function(clone) {
$element.append(clone);
});
}]
});
/**
* @ngdoc directive
* @name ng.directive:ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ng.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* @scope
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.template = {{$route.current.template}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngView#$viewContentLoaded
* @eventOf ng.directive:ngView
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
'$controller',
function($http, $templateCache, $route, $anchorScroll, $compile,
$controller) {
return {
restrict: 'ECA',
terminal: true,
link: function(scope, element, attr) {
var lastScope,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope = null;
}
}
function clearContent() {
element.html('');
destroyLastScope();
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (template) {
element.html(template);
destroyLastScope();
var link = $compile(element.contents()),
current = $route.current,
controller;
lastScope = current.scope = scope.$new();
if (current.controller) {
locals.$scope = lastScope;
controller = $controller(current.controller, locals);
element.contents().data('$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
// $anchorScroll might listen on event...
$anchorScroll();
} else {
clearContent();
}
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:script
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @restrict E
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for a `<select>` element using an array or an object obtained by evaluating the
* `ngOptions` expression.
*˝˝
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an option element can currently
* be bound to string values only.
*
* @param {string} name assignable expression to data-bind to.
* @param {string=} required The control is considered valid only if value is entered.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // red
}
</script>
<div ng-controller="MyCntrl">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective = valueFn({ terminal: true });
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/,
nullModelCtrl = {$setViewValue: noop};
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
}
self.addOption = function(value) {
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue == value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
}
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
}
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
if (children[i].value == '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.bind('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.children(), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.bind('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.children(), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + optionsExp + "'.");
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.bind('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index, groupIndex, length, groupLength;
if (multiple) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
key = optionElement.val();
if (keyName) locals[keyName] = key;
locals[valueName] = collection[key];
value.push(valueFn(scope, locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} else {
locals[valueName] = collection[key];
if (keyName) locals[keyName] = key;
value = valueFn(scope, locals);
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render = render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element;
if (multiple) {
selectedSet = new HashMap(modelValue);
} else if (modelValue === null || nullOption) {
// if we are not multiselect, and we are null then we have to add the nullOption
optionGroups[''].push({selected:modelValue === null, id:'', label:''});
selectedSet = true;
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
optionGroupName = groupByFn(scope, locals) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = selectedSet.remove(valueFn(scope, locals)) != undefined;
} else {
selected = modelValue === valueFn(scope, locals);
selectedSet = selectedSet || selected; // see if at least one item is selected
}
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
label: displayFn(scope, locals) || '', // what will be seen by the user
selected: selected // determine if we should be selected
});
}
if (!multiple && !selectedSet) {
// nothing was selected, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the beginning
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
if (existingOption.element.selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
}
}];
var optionDirective = ['$interpolate', function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
require: '^select',
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function (scope, element, attr, selectCtrl) {
if (selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function(newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.bind('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
}
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: true
});
//try to bind to jquery now so that one can write angular.element().read()
//but we will rebind on bootstrap again.
bindJQuery();
publishExternalAPI(angular);
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
})(window, document);
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}</style>'); | zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-1.0.0.js | JavaScript | asf20 | 473,115 |
/*!
* jQuery JavaScript Library v1.7.2
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Wed Mar 21 12:46:34 2012 -0700
*/
(function( window, undefined ) {
'use strict';
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( 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 = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// 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 a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
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;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// 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 ( length === i ) {
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({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// 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 ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// 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.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// 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.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && array[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.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 ) {
if ( typeof context === "string" ) {
var 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
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, 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 || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* 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( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
fired = true;
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
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;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
pixelMargin: true
};
// jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: 1,
change: 1,
focusin: 1
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
paddingMarginBorderVisibility, paddingMarginBorder,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
paddingMarginBorder = "padding:0;margin:0;border:";
positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" +
"<table " + style + "' cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
div.innerHTML = "";
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.width = div.style.padding = "1px";
div.style.border = 0;
div.style.overflow = "hidden";
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div style='width:5px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
}
div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
if ( window.getComputedStyle ) {
div.style.marginTop = "1%";
support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
}
if ( typeof container.style.zoom !== "undefined" ) {
container.style.zoom = 1;
}
body.removeChild( container );
marginDiv = div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery._data( elem, deferDataKey );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery._data( elem, queueDataKey ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
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 );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
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 = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
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, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
count++;
tmp.add( resolve );
}
}
resolve();
return defer.promise( object );
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
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 self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.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 ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!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 );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, l, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
for ( ; i < l; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// 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;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
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;
}
// 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
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = 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" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// 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: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
quick: selector && quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + 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;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// 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;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.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 ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, [ "events", "handle" ], true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
// 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( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// 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 ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( 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)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === 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( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
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 ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
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 that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
// Pregenerate a single jQuery object for reuse with .is()
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process events on disabled elements (#6911, #8165)
if ( cur.disabled !== true ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( 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;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady
},
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + 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.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// 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;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
// For mousenter/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;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
form._submit_attached = true;
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
jQuery.event.simulate( "change", this, event, true );
}
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
elem._change_attached = true;
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
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 this;
}
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 this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
var 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 ( var 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 );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
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 );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
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;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
Expr.match.globalPOS = origPOS;
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
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 : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.globalPOS,
// 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({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array (deprecated as of jQuery 1.7)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
if ( jQuery( cur ).is( selectors[ i ] ) ) {
ret.push({ selector: selectors[ i ], elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var 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.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
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() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery.clean( arguments );
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery.clean(arguments) );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
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 jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
null;
}
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
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( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || ( l > 1 && i < lastIndex ) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
type: "GET",
global: false,
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
// Clear flags for bubbling special change/submit events, they must
// be reattached when the newly cloned events are first activated
dest.removeAttribute( "_submit_attached" );
dest.removeAttribute( "_change_attached" );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType, script, j,
ret = [];
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div"),
safeChildNodes = safeFragment.childNodes,
remove;
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( div );
}
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Clear elements from DocumentFragment (safeFragment or otherwise)
// to avoid hoarding elements. Fixes #11356
if ( div ) {
div.parentNode.removeChild( div );
// Guard against -1 index exceptions in FF3.6
if ( safeChildNodes.length > 0 ) {
remove = safeChildNodes[ safeChildNodes.length - 1 ];
if ( remove && remove.parentNode ) {
remove.parentNode.removeChild( remove );
}
}
}
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
script = ret[i];
if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) {
scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script );
} else {
if ( script.nodeType === 1 ) {
var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( script );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var 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 );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnum = /^[\-+]?(?:\d*\.)?\d+$/i,
rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,
rrelNum = /^([\-+])=([\-+.\de]+)/,
rmargin = /^margin/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
// order is important!
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
};
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;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": 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: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// 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, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} 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 ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {},
ret, name;
// 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.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// DEPRECATED in 1.3, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle, width,
style = elem.style;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
// A tribute to the "awesome hack by Dean Edwards"
// WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
// which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) {
width = style.width;
style.width = ret;
ret = computedStyle.width;
style.width = width;
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( rnumnonpx.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
i = name === "width" ? 1 : 0,
len = 4;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i += 2 ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i += 2 ) {
val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0;
}
}
}
return val + "px";
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWidthOrHeight( elem, name, extra );
} else {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
}
}
},
set: function( elem, value ) {
return rnum.test( value ) ?
value + "px" :
value;
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "margin-right" );
} else {
return elem.style.marginRight;
}
});
}
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// 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,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* 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 = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// 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 = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// 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 );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// 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 ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
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;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// 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 ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// 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: {
context: true,
url: true
}
},
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 // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
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;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
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( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ 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" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// 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 ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// 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 If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// 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 || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// 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 ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// 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 ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
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 {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// 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
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.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 ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( (display === "" && jQuery.css(elem, "display") === "none") ||
!jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed( speed, easing, callback );
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
function doAnimation() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, e, hooks, replace,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
// first pass over propertys to expand / normalize
for ( p in prop ) {
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
replace = hooks.expand( prop[ name ] );
delete prop[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'p' from above because we have the correct "name"
for ( p in replace ) {
if ( ! ( p in prop ) ) {
prop[ p ] = replace[ p ];
}
}
}
}
for ( name in prop ) {
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.zoom = 1;
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test( val ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ val ]();
}
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ( (end || 1) / e.cur() ) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
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 ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
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.extend({
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
};
opt.duration = jQuery.fx.off ? 0 : 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( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p ) {
return p;
},
swing: function( p ) {
return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
if ( self.options.hide ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
} else if ( self.options.show ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.end );
}
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
}
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom( this.cur(), 0 );
},
// Each step of an animation
step: function( gotoEnd ) {
var p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function( index, value ) {
elem.style[ "overflow" + value ] = options.overflow[ index ];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery( elem ).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
complete.call( elem );
}
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ( (this.end - this.start) * this.pos );
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timer,
timers = jQuery.timers,
i = 0;
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();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Ensure props that can't be negative don't go there on undershoot easing
jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
// exclude marginTop, marginLeft, marginBottom and marginRight from this list
if ( prop.indexOf( "margin" ) ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var getOffset,
rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
getOffset = function( elem, doc, docElem, box ) {
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow( doc ),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
getOffset = function( elem, doc, docElem ) {
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var elem = this[0],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return null;
}
if ( elem === doc.body ) {
return jQuery.offset.bodyOffset( elem );
}
return getOffset( elem, doc, doc.documentElement );
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// 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 ) ) {
options = options.call( elem, i, 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({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
var clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name;
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( value ) {
return jQuery.access( this, function( elem, type, value ) {
var doc, docElemProp, orig, ret;
if ( jQuery.isWindow( elem ) ) {
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
doc = elem.document;
docElemProp = doc.documentElement[ clientProp ];
return jQuery.support.boxModel && docElemProp ||
doc.body && doc.body[ clientProp ] || docElemProp;
}
// Get document width or height
if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
doc = elem.documentElement;
// when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
// so we can't use max, as it'll choose the incorrect offset[Width/Height]
// instead we use the correct client[Width/Height]
// support:IE6
if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
return doc[ clientProp ];
}
return Math.max(
elem.body[ scrollProp ], doc[ scrollProp ],
elem.body[ offsetProp ], doc[ offsetProp ]
);
}
// Get width or height on the element
if ( value === undefined ) {
orig = jQuery.css( elem, type );
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
}
// Set the width or height on the element
jQuery( elem ).css( type, value );
}, type, value, arguments.length, null );
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use 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.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document){
var _jQuery = window.jQuery.noConflict(true);
////////////////////////////////////
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
function fromCharCode(code) {return String.fromCharCode(code);}
var Error = window.Error,
/** holds major version number for IE or NaN for real browsers */
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isObject(obj) && isNumber(obj.length)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value) };
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while(index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
*/
function extend(dst) {
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new (extend(function() {}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || identity)(value);
};
</pre>
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){return typeof value == 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){return typeof value != 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){return value != null && typeof value == 'object';}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){return typeof value == 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){return typeof value == 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
return toString.apply(value) == '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) == '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){return typeof value == 'function';}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) === '[object File]';
}
function isBoolean(value) {
return typeof value == 'boolean';
}
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
}
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.bind && node.find)); // we have a bind and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj = {}, items = str.split(","), i;
for ( i = 0; i < items.length; i++ )
obj[ items[i] ] = true;
return obj;
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
var size = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
return indexOf(array, obj) != -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index = indexOf(array, value);
if (index >=0)
array.splice(index, 1);
return value;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw Error("Can't copy equivalent objects or arrays");
if (isArray(source)) {
while(destination.length) {
destination.pop();
}
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties pass `===` comparison.
* * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
*
* During a property comparision, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only be identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if ((length = o1.length) == o2.length) {
for(key=0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() == o2.getTime();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
keySet = {};
for(key in o1) {
if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) {
return false;
}
keySet[key] = true;
}
for(key in o2) {
if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are are prebound to the function. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (/^\$+/.test(key)) {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch(e) {}
return jqLite('<div>').append(element).html().
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
}
/////////////////////////////////////////////////
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if (keyValue) {
key_value = keyValue.split('=');
key = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace((pctEncodeSpaces ? null : /%20/g), '+');
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp on optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap on application. Only
* one directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* ot the root of the page.
*
* In the example below if the `ngApp` directive would not be placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 = {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements = [element],
appElement,
module,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement = element;
module = (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement = element;
module = attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
element = jqLite(element);
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(
['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator){
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
JQLitePatchJQueryRemove('remove', true);
JQLitePatchJQueryRemove('empty');
JQLitePatchJQueryRemove('html');
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error of the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configure information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Option configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider.directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which needs to be performed when the injector with
* with the current module is finished loading.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
}
}
});
};
});
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.0.0', // all of these placeholder strings will be replaced by rake's
major: 1, // compile task
minor: 0,
dot: 0,
codeName: 'temporal-domination'
};
function publishExternalAPI(angular){
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0}
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$route: $RouteProvider,
$routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/bind/)
* - [children()](http://api.jquery.com/children/)
* - [clone()](http://api.jquery.com/clone/)
* - [contents()](http://api.jquery.com/contents/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name.
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [html()](http://api.jquery.com/html/)
* - [next()](http://api.jquery.com/next/)
* - [parent()](http://api.jquery.com/parent/)
* - [prepend()](http://api.jquery.com/prepend/)
* - [prop()](http://api.jquery.com/prop/)
* - [ready()](http://api.jquery.com/ready/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [toggleClass()](http://api.jquery.com/toggleClass/)
* - [unbind()](http://api.jquery.com/unbind/)
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite:
*
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = JQLite.cache = {},
jqName = JQLite.expando = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); });
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function JQLitePatchJQueryRemove(name, dispatchThis) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch() {
var list = [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children,
fns, events;
while(list.length) {
set = list.shift();
for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
element = jqLite(set[setIndex]);
if (fireEvent) {
events = element.data('events');
if ( (fns = events && events.$destroy) ) {
forEach(fns, function(fn){
fn.handler();
});
}
} else {
fireEvent = !fireEvent;
}
for(childIndex = 0, childLength = (children = element.children()).length;
childIndex < childLength;
childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
throw Error('selectors not implemented');
}
return new JQLite(element);
}
if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
this.remove(); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element){
JQLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteUnbind(element, type, fn) {
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type], fn);
}
}
}
function JQLiteRemoveData(element) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
JQLiteUnbind(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function JQLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
}
}
function JQLiteData(element, key, value) {
var data = JQLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
JQLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
data[key] = value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function JQLiteHasClass(element, selector) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function JQLiteRemoveClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
: [ elements ];
for(var i=0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function JQLiteController(element, name) {
return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
function JQLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if(element[0].nodeType == 9) {
element = element.find('html');
}
while (element.length) {
if (value = element.data(name)) return value;
element = element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
JQLite(window).bind('load', trigger); // fallback to window.onload for others
},
toString: function() {
var value = [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form'.split(','), function(value) {
BOOLEAN_ELEMENTS[uppercase(value)] = true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: JQLiteData,
inheritedData: JQLiteInheritedData,
scope: function(element) {
return JQLiteInheritedData(element, '$scope');
},
controller: JQLiteController ,
injector: function(element) {
return JQLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name)|| noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: extend((msie < 9)
? function(element, value) {
if (element.nodeType == 1 /** Element */) {
if (isUndefined(value))
return element.innerText;
element.innerText = value;
} else {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue = value;
}
}
: function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent = value;
}, {$dv:''}),
val: function(element, value) {
if (isUndefined(value)) {
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
// JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=0; i < this.length; i++) {
if (fn === JQLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
if (this.length)
return fn(this[0], arg1, arg2);
}
} else {
// we are a write, so apply to all children
for(i=0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
return fn.$dv;
};
});
function createEventHandler(element, events) {
var eventHandler = function (event, type) {
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <= 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault = null;
event.stopPropagation = null;
event.isDefaultPrevented = null;
} else {
// It shouldn't affect normal browsers (native methods are defined on prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
bind: function bindFn(element, type, fn){
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!events) JQLiteExpandoStore(element, 'events', events = {});
if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
var counter = 0;
events.mouseenter = [];
events.mouseleave = [];
bindFn(element, 'mouseover', function(event) {
counter++;
if (counter == 1) {
handle(event, 'mouseenter');
}
});
bindFn(element, 'mouseout', function(event) {
counter --;
if (counter == 0) {
handle(event, 'mouseleave');
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
eventFns = events[type]
}
eventFns.push(fn);
});
},
unbind: JQLiteUnbind,
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element){
if (element.nodeName != '#text')
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes;
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType === 1)
element.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index = child;
}
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode)[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
JQLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
return element.nextSibling;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2) {
var value;
for(var i=0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value == undefined ? this : value;
};
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
}
} else {
key = obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array){
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] = value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
return value;
}
};
/**
* A map where multiple values can be added to the same key such that they form a queue.
* @returns {HashQueueMap}
*/
function HashQueueMap() {}
HashQueueMap.prototype = {
/**
* Same as array push, but using an array as the value for the hash
*/
push: function(key, value) {
var array = this[key = hashKey(key)];
if (!array) {
this[key] = [value];
} else {
array.push(value);
}
},
/**
* Same as array shift, but using an array as the value for the hash
*/
shift: function(key) {
var array = this[key = hashKey(key)];
if (array) {
if (array.length == 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick of your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(.+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn')
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following ways are all valid way of annotating function with injection arguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $inject.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $inject.invoke(explicit);
*
* // inline
* $inject.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
* parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
* tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. The function arguments come form the function annotation.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
* all of the arguments to the constructor function as specified by the constructor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is used by the injector
* to determine which services need to be injected into the function when the function is invoked. There are three
* ways in which the function can be annotated with the needed dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
* the function into a string using `toString()` method and extracting the argument names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
* are supported.
*
* # The `$injector` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
* services to be injected into the function.
* <pre>
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
* inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
* minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tempFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
* above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
* The providers share the same name as the instance they create with the `Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow for configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation = 'Hello';
*
* this.salutation = function(text) {
* salutation = text;
* };
*
* this.$get = function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* });
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* )};
*
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
* `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
* into configuration function (other modules) and it is not interceptable by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service instance creation. The
* returned instance may be the original instance, or a new instance which delegates to the
* original instance.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instanciated. The function is called using the {@link AUTO.$injector#invoke
* injector.invoke} method and is therefore fully injectable. Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*/
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = createInternalInjector(providerCache, function() {
throw Error("Unknown provider: " + path.join(' <- '));
}),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
}
}
function provider(name, provider_) {
if (isFunction(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, value) { return factory(name, valueFn(value)); }
function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks = [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
if (isString(module)) {
var moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
try {
for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = invokeArgs[0] == '$injector'
? providerInjector
: providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isFunction(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isArray(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + String(module[module.length - 1]);
throw e;
}
} else {
assertArgFn(module, 'module');
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (typeof serviceName !== 'string') {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw Error('Circular dependency: ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals){
var args = [],
$inject = annotate(fn),
length, i,
key;
for(i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key, path)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
switch (self ? -1 : args.length) {
case 0: return fn();
case 1: return fn(args[0]);
case 2: return fn(args[0], args[1]);
case 3: return fn(args[0], args[1], args[2]);
case 4: return fn(args[0], args[1], args[2], args[3]);
case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
default: return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals);
return isObject(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result = null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) === 'a') result = element;
});
return result;
}
function scroll() {
var hash = $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $locaiton.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function() {return $location.hash();}, function() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}];
}
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
baseElement = document.find('base');
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// setter
if (url) {
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
if (replace) location.replace(url);
else location.href = url;
}
return self;
// getter
} else {
// the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href;
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cokkie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
if (lastCookies.length > 20) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " +
"were already set (" + lastCookies.length + " > 20 )");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1));
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be defered.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchroniously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a defered task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider(){
this.$get = ['$window', '$log', '$sniffer', '$document',
function( $window, $log, $sniffer, $document){
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects.
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache.
* - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key) — Removes a key-value pair from the cache.
* - `{void}` `removeAll() — Removes all cached values.
* - `{void}` `destroy() — Removes references to this cache from $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw Error('cacheId ' + cacheId + ' taken');
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
return caches[cacheId] = {
put: function(key, value) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
},
get: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry = lruHash[key];
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* Cache used for storing html templates.
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
*
* The compilation is a process of walking the DOM tree and trying to match DOM elements to
* {@link ng.$compileProvider.directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original template.
*
<doc:example module="compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}
</script>
<div ng-controller="Ctrl">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
* @param {number} maxPriority only apply directives lower then given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the linking function returns the element of the template. It is either the original element
* passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element = $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directive with compiler
*
* @param {string} name name of the directive.
* @param {function} directiveFactory An injectable directive factory function.
* @returns {ng.$compileProvider} Self for chaining.
*/
$CompileProvider.$inject = ['$provide'];
function $CompileProvider($provide) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ';
/**
* @ngdoc function
* @name ng.$compileProvider.directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register directives with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more
* info.
*/
this.directive = function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directive');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
var booleanKey = getBooleanAttrName(this.$$element[0], key),
$$observers = this.$$observers;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not interpolated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
};
return compile;
//================================
function compile($compileNode, transcludeFn, maxPriority) {
if (!($compileNode instanceof jqLite)) {
// jquery always rewraps, where as we need to preserve the original selector so that we can modify it.
$compileNode = jqLite($compileNode);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNode, function(node, index){
if (node.nodeType == 3 /* text node */) {
$compileNode[index] = jqLite(node).wrap('<span>').parent()[0];
}
});
var compositeLinkFn = compileNodes($compileNode, transcludeFn, $compileNode, maxPriority);
return function(scope, cloneConnectFn){
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode = cloneConnectFn
? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!!
: $compileNode;
$linkNode.data('$scope', scope);
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
return $linkNode;
};
}
function wrongMode(localName, mode) {
throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch(e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
* rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} max directive priority
* @returns {?function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) {
var linkFns = [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for(var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, maxPriority);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
: null;
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal)
? null
: compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn;
for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = nodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new(isObject(nodeLinkFn.scope));
jqLite(node).data('$scope', childScope);
} else {
childScope = scope;
}
childTranscludeFn = nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
nodeLinkFn(childLinkFn, childScope, node, $rootElement,
(function(transcludeFn) {
return function(cloneFn) {
var transcludeScope = scope.$new();
return transcludeFn(transcludeScope, cloneFn).
bind('$destroy', bind(transcludeScope, transcludeScope.$destroy));
};
})(childTranscludeFn || transcludeFn)
);
} else {
nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
}
}
}
}
/**
* Looks for directives on the given node ands them to the directive collection which is sorted.
*
* @param node node to search
* @param directives an array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs the shared attrs object which is used to populate the normalized attributes.
* @param {number=} max directive priority
*/
function collectDirectives(node, directives, attrs, maxPriority) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch(nodeType) {
case 1: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
// iterate over the attributes
for (var attr, name, nName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
attr = nAttrs[j];
if (attr.specified) {
name = attr.name;
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
attrs[nName] = value = trim((msie && name == 'href')
? decodeURIComponent(node.getAttribute(name, 2))
: attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority);
}
}
// use class as directive
className = node.className;
if (isString(className)) {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case 3: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Once the directives have been collected their compile functions is executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached..
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement} $rootElement If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace widgets on it.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) {
var terminalPriority = -Number.MAX_VALUE,
preLinkFns = [],
postLinkFns = [],
newScopeDirective = null,
newIsolatedScopeDirective = null,
templateDirective = null,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
transcludeDirective,
childTranscludeFn = transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, $compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolatedScopeDirective = directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (directiveValue = directive.controller) {
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
terminalPriority = directive.priority;
if (directiveValue == 'element') {
$template = jqLite(compileNode);
$compileNode = templateAttrs.$$element =
jqLite('<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->');
compileNode = $compileNode[0];
replaceWith($rootElement, jqLite($template[0]), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority);
} else {
$template = jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directiveValue = directive.template) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
$template = jqLite('<div>' + trim(directiveValue) + '</div>').contents();
compileNode = $template[0];
if (directive.replace) {
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
}
replaceWith($rootElement, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that were already applied and those that weren't
// - collect directives from the template, add them to the second group and sort them
// - append the second group with new directives to the first group
directives = directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length - (i + 1)),
newTemplateAttrs
)
);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace,
childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post) {
if (pre) {
pre.require = directive.require;
preLinkFns.push(pre);
}
if (post) {
post.require = directive.require;
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod = 'data', optional = false;
if (isString(require)) {
while((value = require.charAt(0)) == '^' || value == '?') {
require = require.substr(1);
if (value == '^') {
retrievalMethod = 'inheritedData';
}
optional = optional || value == '?';
}
value = $element[retrievalMethod]('$' + require + 'Controller');
if (!value && !optional) {
throw Error("No controller: " + require);
}
return value;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller;
if (compileNode === linkNode) {
attrs = templateAttrs;
} else {
attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
}
$element = attrs.$$element;
if (newScopeDirective && isObject(newScopeDirective.scope)) {
var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/;
var parentScope = scope.$parent || scope;
forEach(newScopeDirective.scope, function(definiton, scopeName) {
var match = definiton.match(LOCAL_REGEXP) || [],
attrName = match[2]|| scopeName,
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
switch (mode) {
case '@': {
attrs.$observe(attrName, function(value) {
scope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = parentScope;
break;
}
case '=': {
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
' (directive: ' + newScopeDirective.name + ')');
};
lastValue = scope[scopeName] = parentGet(parentScope);
scope.$watch(function() {
var parentValue = parentGet(parentScope);
if (parentValue !== scope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !== lastValue) {
// parent changed and it has precedence
lastValue = scope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, lastValue = scope[scopeName]);
}
}
return parentValue;
});
break;
}
case '&': {
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(parentScope, locals);
}
break;
}
default: {
throw Error('Invalid isolate scope definition for directive ' +
newScopeDirective.name + ': ' + definiton);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
};
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
$element.data(
'$' + directive.name + 'Controller',
$controller(controller, locals));
});
}
// PRELINKING
for(i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for(i = 0, ii = postLinkFns.length; i < ii; i++) {
try {
linkFn = postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority) {
var match = false;
if (hasDirectives.hasOwnProperty(name)) {
for(var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i<ii; i++) {
try {
directive = directives[i];
if ( (maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
tDirectives.push(directive);
match = true;
}
} catch(e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key]) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
$rootElement, replace, childTranscludeFn) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
// The fact that we have to copy and patch the directive seems wrong!
derivedSyncDirective = extend({}, origAsyncDirective, {
controller: null, templateUrl: null, transclude: null
});
$compileNode.html('');
$http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
if (replace) {
$template = jqLite('<div>' + trim(content) + '</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives, tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn);
afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn);
while(linkQueue.length) {
var controller = linkQueue.pop(),
linkRootElement = linkQueue.pop(),
beforeTemplateLinkNode = linkQueue.pop(),
scope = linkQueue.pop(),
linkNode = compileNode;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
}, scope, linkNode, $rootElement, controller);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw Error('Failed to load template: ' + config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw Error('Multiple directives [' + previousDirective.name + ', ' +
directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function(scope, node) {
var parent = node.parent(),
bindings = parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings), 'ng-binding');
scope.$watch(interpolateFn, function(value) {
node[0].nodeValue = value;
});
})
});
}
}
function addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
directives.push({
priority: 100,
compile: valueFn(function(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (name === 'class') {
// we need to interpolate classes again, in the case the element was replaced
// and therefore the two class attrs got merged - we want to interpolate the result
interpolateFn = $interpolate(attr[name], true);
}
attr[name] = undefined;
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function(value) {
attr.$set(name, value);
});
})
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
* but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, $element, newNode) {
var oldNode = $element[0],
parent = oldNode.parentNode,
i, ii;
if ($rootElement) {
for(i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == oldNode) {
$rootElement[i] = newNode;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, oldNode);
}
newNode[jqLite.expando] = oldNode[jqLite.expando];
$element[0] = newNode;
}
}];
}
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:DiRective
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
* @description
*
* A shared object between directive compile / linking functions which contains normalized DOM element
* attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
* since all of these are treated as equivalent in Angular:
*
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(constructor, locals) {
if(isString(constructor)) {
var name = constructor;
constructor = controllers.hasOwnProperty(name)
? controllers[name]
: getter(locals.$scope, name, true) || getter($window, name, true);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
function $DocumentProvider(){
this.$get = ['$window', function(window){
return jqLite(window.document);
}];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler}
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log){
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
/**
* @ngdoc function
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Deafults to `{{` and `}}`.
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @prop {string=} value new value to set the starting symbol to.
*/
this.startSymbol = function(value){
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @prop {string=} value new value to set the ending symbol to.
*/
this.endSymbol = function(value){
if (value) {
endSymbol = value;
return this;
} else {
return startSymbol;
}
};
this.$get = ['$parse', function($parse) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
<pre>
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @returns {function(context)} an interpolation function which is used to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
return function(text, mustHaveExpression) {
var startIndex,
endIndex,
index = 0,
parts = [],
length = text.length,
hasInterpolation = false,
fn,
exp,
concat = [];
while(index < length) {
if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
(index != startIndex) && parts.push(text.substring(index, startIndex));
parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
fn.exp = exp;
index = endIndex + endSymbolLength;
hasInterpolation = true;
} else {
// we did not find anything, so we have to add the remainder to the parts array
(index != length) && parts.push(text.substring(index));
index = length;
}
}
if (!(length = parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length = 1;
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
};
fn.exp = text;
fn.parts = parts;
return fn;
}
};
}];
}
var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH = PATH_MATCH,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function stripHash(url) {
return url.split('#')[0];
}
function matchUrl(url, obj) {
var match = URL_MATCH.exec(url);
match = {
protocol: match[1],
host: match[3],
port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol = match.protocol;
obj.$$host = match.host;
obj.$$port = match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
match.hash.indexOf(hashPrefix) !== 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) +
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) == basePath) {
return url;
// convert html5 url -> hashbang url
} else {
var search = match.search && '?' + match.search || '',
hash = match.hash && '#' + match.hash || '',
pathPrefix = pathPrefixFromBase(basePath),
path = match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
}
return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} url HTML5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix, appBaseUrl) {
pathPrefix = pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(newAbsoluteUrl) {
var match = matchUrl(newAbsoluteUrl, this);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
}
this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
this.$$search = parseKeyValue(match.search);
this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
pathPrefix + this.$$url;
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is disabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and search)
*/
function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
}
basePath = match.path + (match.search ? '?' + match.search : '');
match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
if (match[1]) {
this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
} else {
this.$$path = '';
}
this.$$search = parseKeyValue(match[3]);
this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
LocationUrl.prototype = {
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|object<string,string>=} search New search params - string or hash object
* @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If the value is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
} else {
this.$$search = isString(search) ? parseKeyValue(search) : search;
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
LocationHashbangUrl.apply(this, arguments);
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
}
}
}
LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider(){
var hashPrefix = '',
html5Mode = false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {string=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isDefined(mode)) {
html5Mode = mode;
return this;
} else {
return html5Mode;
}
};
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
basePath,
pathPrefix,
initUrl = $browser.url(),
initUrlParts = matchUrl(initUrl),
appBaseUrl;
if (html5Mode) {
basePath = $browser.baseHref() || '/';
pathPrefix = pathPrefixFromBase(basePath);
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
pathPrefix + '/';
if ($sniffer.history) {
$location = new LocationUrl(
convertToHtml5Url(initUrl, basePath, hashPrefix),
pathPrefix, appBaseUrl);
} else {
$location = new LocationHashbangInHtml5Url(
convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
}
} else {
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
(initUrlParts.path || '') +
(initUrlParts.search ? ('?' + initUrlParts.search) : '') +
'#' + hashPrefix + '/';
$location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
}
$rootElement.bind('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !== 'a') {
if (elm[0] === $rootElement[0]) return;
elm = elm.parent();
}
var absHref = elm.prop('href'),
rewrittenUrl = $location.$$rewriteAppUrl(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
event.preventDefault();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() != initUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() != newUrl) {
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl = $browser.url();
if (!changeCounter || oldUrl != $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), $location.$$replace);
$location.$$replace = false;
afterLocationChange(oldUrl);
}
});
}
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
}
}];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @example
<doc:example>
<doc:source>
<script>
function LogCtrl($log) {
this.$log = $log;
this.message = 'Hello World!';
}
</script>
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $LogProvider(){
this.$get = ['$window', function($window){
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2);
}
}
}];
}
var OPERATORS = {
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);},
'-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
'=':noop,
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, csp){
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2];
if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName;
while (index < text.length) {
var ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while(peekIndex < text.length) {
var ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
if(json){
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain =
function() { throwError("is not valid json", {text:text, index:0}); };
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self, locals) {
return fn(self, locals, right);
};
}
function binaryFn(left, fn, right) {
return function(self, locals) {
return fn(self, locals, left, right);
};
}
function statements() {
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1
? statements[0]
: function(self, locals){
var value;
for ( var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while(true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, locals, input){
var args = [input];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = logicalOR();
return function(self, locals){
return left.assign(self, right(self, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==','!='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp);
return extend(
function(self, locals) {
return getter(object(self, locals), locals);
},
{
assign:function(self, value, locals) {
return setter(object(self, locals), field, value);
}
}
);
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function(self, locals){
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = o[i];
if (v && v.then) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) { p.$$v = val; });
}
v = v.$$v;
}
return v;
}, {
assign:function(self, value, locals){
return obj(self, locals)[indexFn(self, locals)] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(self, locals){
var args = [],
context = contextGetter ? contextGetter(self, locals) : self;
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
var fnPtr = fn(self, locals) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
if (peekToken().text != ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function(self, locals){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
};
}
function object () {
var keyValues = [];
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
} while (expect(','));
}
consume('}');
return function(self, locals){
var object = {};
for ( var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
var value = keyValue.value(self, locals);
object[keyValue.key] = value;
}
return object;
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accesible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accesbile by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4) {
return function(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
};
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
: function(scope, locals) {
var i = 0, val
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n';
});
code += 'return s;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() { return code; };
}
return getterFnCache[path] = fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against (Topically a scope object).
* * `locals`: local variables context object, useful for overriding values in `context`.
*
* The return function also has an `assign` property, if the expression is assignable, which
* allows one to set values to expressions.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] = parser(exp, false, $filter, $sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise apis are to
* asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` and `scope` are
* // available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* );
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of
* [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as apis
* that can be used for signaling the successful or unsuccessful completion of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
* or rejected calls one of the success or error callbacks asynchronously as soon as the result
* is available. The callbacks are called with a single argument the result or rejection reason.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback` or `errorCallback`.
*
*
* # Chaining promises
*
* Because calling `then` api of a promise returns a new derived promise, it is easily possible
* to create a chain of promises:
*
* <pre>
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and it's value will be
* // the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful apis like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - $q promises are recognized by the templating engine in angular, which means that in templates
* you can treat promises attached to a scope as if they were the resulting values.
* - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
var pending = [],
value, deferred;
deferred = {
resolve: function(val) {
if (pending) {
var callbacks = pending;
pending = undefined;
value = ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
value.then(callback[0], callback[1]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
promise: {
then: function(callback, errback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((callback || defaultCallback)(value));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((errback || defaultErrback)(reason));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback]);
} else {
value.then(wrappedCallback, wrappedErrback);
}
return result.promise;
}
}
};
return deferred;
};
var ref = function(value) {
if (value && value.then) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* <pre>
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
result.resolve((errback || defaultErrback)(reason));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with on object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value coresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
var when = function(value, callback, errback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>} promises An array of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value coresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
function all(promises) {
var deferred = defer(),
counter = promises.length,
results = [];
if (counter) {
forEach(promises, function(promise, index) {
ref(promise).then(function(value) {
if (index in results) return;
results[index] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (index in results) return;
deferred.reject(reason);
});
});
} else {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* @ngdoc object
* @name ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link ng.$route $route} for an example.
*/
function $RouteProvider(){
var routes = {};
/**
* @ngdoc method
* @name ng.$routeProvider#when
* @methodOf ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exacly match the
* route definition.
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{function()=}` – Controller fn that should be associated with newly
* created scope.
* - `template` – `{string=}` – html template as a string that should be used by
* {@link ng.directive:ngView ngView} or
* {@link ng.directive:ngInclude ngInclude} directives.
* this property takes precedence over `templateUrl`.
* - `templateUrl` – `{string=}` – path to an html template that should be used by
* {@link ng.directive:ngView ngView}.
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, they will be
* resolved and converted to a value before the controller is instantiated and the
* `$aftreRouteChange` event is fired. The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is resolved
* before its value is injected into the controller.
*
* - `redirectTo` – {(string|function())=} – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
routes[path] = extend({reloadOnSearch: true}, route);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length-1] == '/')
? path.substr(0, path.length-1)
: path +'/';
routes[redirectPath] = {redirectTo: path};
}
return this;
};
/**
* @ngdoc method
* @name ng.$routeProvider#otherwise
* @methodOf ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
* @returns {Object} self
*/
this.otherwise = function(params) {
this.when(null, params);
return this;
};
this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) {
/**
* @ngdoc object
* @name ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
* directive and the {@link ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link ng.directive:script inlined templates}
to get it working on jsfiddle as well.
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeStart
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occurs.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeSuccess
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ng.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeError
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name ng.$route#$routeUpdate
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var matcher = switchRouteMatcher,
forceReload = false,
$route = {
routes: routes,
/**
* @ngdoc method
* @name ng.$route#reload
* @methodOf ng.$route
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ng.directive:ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
forceReload = true;
$rootScope.$evalAsync(updateRoute);
}
};
$rootScope.$on('$locationChangeSuccess', updateRoute);
return $route;
/////////////////////////////////////////////////////
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should construct the route matching
// regex only once and then reuse it
var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$',
params = [],
dst = {};
forEach(when.split(/\W/), function(param) {
if (param) {
var paramRegExp = new RegExp(":" + param + "([\\W])");
if (regex.match(paramRegExp)) {
regex = regex.replace(paramRegExp, "([^\\/]*)$1");
params.push(param);
}
}
});
var match = on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] = match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$route === last.$route
&& equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
last.params = next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload = false;
$rootScope.$broadcast('$routeChangeStart', next, last);
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
.replace();
}
}
}
$q.when(next).
then(function() {
if (next) {
var keys = [],
values = [],
template;
forEach(next.resolve || {}, function(value, key) {
keys.push(key);
values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value));
});
if (isDefined(template = next.template)) {
} else if (isDefined(template = next.templateUrl)) {
template = $http.get(template, {cache: $templateCache}).
then(function(response) { return response.data; });
}
if (isDefined(template)) {
keys.push('$template');
values.push(template);
}
return $q.all(values).then(function(values) {
var locals = {};
forEach(values, function(value, index) {
locals[keys[index]] = value;
});
return locals;
});
}
}).
// after route change
then(function(locals) {
if (next == $route.current) {
if (next) {
next.locals = locals;
copy(next.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', next, last);
}
}, function(error) {
if (next == $route.current) {
$rootScope.$broadcast('$routeChangeError', next, last, error);
}
});
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = matcher($location.path(), path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string||'').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
/**
* @ngdoc object
* @name ng.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination of the
* {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
* are extracted when the {@link ng.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get = valueFn({});
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope ware heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive from speed as well as memory:
* - no closures, instead ups prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the begging (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using array would be slow since inserts in meddle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of digest iteration the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider(){
var TTL = 10;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse',
function( $injector, $exceptionHandler, $parse) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
angular.injector(['ng']).invoke(function($rootScope) {
var scope = $rootScope.$new();
scope.salutation = 'Hello';
scope.name = 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function() {
this.greeting = this.salutation + ' ' + this.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name = 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
});
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be provided
* for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this['this'] = this.$root = this;
this.$$asyncQueue = [];
this.$$listeners = {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
Scope.prototype = {
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
* the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate if true then the scoped does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not se parent scope properties.
* When creating widgets it is useful for the widget to not accidently read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isFunction(isolate)) {
// TODO: remove at some point
throw Error('API-CHANGE: Use $controller to instantiate controllers.');
}
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class
// name in the debugger.
Child.prototype = this;
child = new Child();
child.$id = nextUid();
}
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$$asyncQueue = [];
child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
* should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression' are not equal (with the exception of the initial run
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison
* {@link angular.copy} function is used. It also means that watching complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detected. The rerun iteration
* limit is 100 to prevent infinity loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
*
* @param {boolean=} objectEquality Compare object for equality rather then for refference.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
// in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop, 'listener');
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
* Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
* `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loop. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
*
* Usually you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider.directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
* {@link ng.$compileProvider.directive directives}) will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to simulate the scope
* life-cycle.
*
* # Example
* <pre>
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
counter = counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg;
beginPhase('$digest');
do {
dirty = false;
current = target;
do {
asyncQueue = current.$$asyncQueue;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(value) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString())
: watch.exp;
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if(dirty && !(ttl--)) {
clearPhase();
throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Remove the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it chance to
* perform any necessary cleanup.
*/
$destroy: function() {
if ($rootScope == this) return; // we can't remove the root node;
var parent = this.$parent;
this.$broadcast('$destroy');
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope returning the result. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluating engular expressions.
*
* # Example
* <pre>
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* </pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
*
* - it will execute in the current script execution context (before any DOM rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life-cycle
* of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
* was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listen on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
* event life cycle.
*
* @param {string} name Event name to listen on.
* @param {function(event)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*
* The event listener function format is: `function(event)`. The `event` object passed into the
* listener has the following attributes
*
* - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
* - `currentScope` - {Scope}: the current scope which is handling the event.
* - `name` - {string}: Name of the event.
* - `stopPropagation` - {function=}: calling `stopPropagation` function will cancel further event propagation
* (available only for events that were `$emit`-ed).
* - `preventDefault` - {function}: calling `preventDefault` sets `defaultPrevented` flag to true.
* - `defaultPrevented` - {boolean}: true if `preventDefault` was called.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
arrayRemove(namedListeners, listener);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and calls all registered
* listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i=0, length=namedListeners.length; i<length; i++) {
try {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//traverse upwards
scope = scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes of the current scope and
* calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1);
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
forEach(current.$$listeners[name], function(listener) {
try {
listener.apply(null, listenerArgs);
} catch(e) {
$exceptionHandler(e);
}
});
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
return event;
}
};
var $rootScope = new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw Error($rootScope.$$phase + ' already in progress');
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function compileToFn(exp, name) {
var fn = $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's uniqueue we can easily tell it apart from other values
*/
function initWatchVal() {}
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', function($window) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
history: !!($window.history && $window.history.pushState && !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = $window.document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without triggering alerts
csp: false
};
}];
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overriden, removed or mocked for testing.
*
* All expressions are evaluated with respect to current scope so they don't
* suffer from window globality.
*
* @example
<doc:example>
<doc:source>
<input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $WindowProvider(){
this.$get = valueFn(window);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data = fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $config = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data, true);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'
},
post: {'Content-Type': 'application/json;charset=utf-8'},
put: {'Content-Type': 'application/json;charset=utf-8'}
}
};
var providerResponseInterceptors = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http'),
responseInterceptors = [];
forEach(providerResponseInterceptors, function(interceptor) {
responseInterceptors.push(
isString(interceptor)
? $injector.get(interceptor)
: $injector.invoke(interceptor)
);
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBacked
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patters this doesn't matter much, for advanced usage,
* it is important to familiarize yourself with these apis and guarantees they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an http request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with status
* // code outside of the <200, 400) range
* });
* </pre>
*
* Since the returned value of calling the $http function is a Promise object, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the api signature and type info below for more
* details.
*
*
* # Shortcut methods
*
* Since all invocation of the $http service require definition of the http method and url and
* POST and PUT requests require response body/data to be provided as well, shortcut methods
* were created to simplify using the api:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain http headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `X-Requested-With: XMLHttpRequest`
* - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from this configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with name equal to the lower-cased http method name, e.g.
* `$httpProvider.defaults.headers.get['My-Header']='value'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar
* fassion as described above.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform functions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - if the `data` property of the request config object contains an object, serialize it into
* JSON format.
*
* Response transformations:
*
* - if XSRF prefix is detected, strip it (see Security Considerations section below)
* - if json response is detected, deserialize it using a JSON parser
*
* To override these transformation locally, specify transform functions as `transformRequest`
* and/or `transformResponse` properties of the config object. To globally override the default
* transforms, override the `$httpProvider.defaults.transformRequest` and
* `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`.
*
*
* # Caching
*
* To enable caching set the configuration property `cache` to `true`. When the cache is
* enabled, `$http` stores the response from the server in local cache. Next time the
* response is served from the cache without sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same url that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response for the first request.
*
*
* # Response interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of synchronous or
* asynchronous preprocessing of received responses, it is desirable to be able to intercept
* responses for http requests before they are handed over to the application code that
* initiated these requests. The response interceptors leverage the {@link ng.$q
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
*
* The interceptors are service factories that are registered with the $httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor — a function that
* takes a {@link ng.$q promise} and returns the original or a new promise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability} allows third party web-site to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
* an unauthorized site can gain your user's private data. Angular provides following mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that
* runs on your domain could read the cookie, your server can be assured that the XHR came from
* JavaScript running on your domain.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have read the token. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript making
* up its own tokens). We recommend that the token is a digest of your site's authentication
* cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
* `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server.
* - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number}` – timeout in milliseconds.
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example>
<file name="index.html">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(config) {
config.method = uppercase(config.method);
var reqTransformFn = config.transformRequest || $config.transformRequest,
respTransformFn = config.transformResponse || $config.transformResponse,
defHeaders = $config.headers,
reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']},
defHeaders.common, defHeaders[lowercase(config.method)], config.headers),
reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn),
promise;
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
// send request
promise = sendReq(config, reqData, reqHeaders);
// transform future response
promise = promise.then(transformResponse, transformResponse);
// apply interceptors
forEach(responseInterceptors, function(interceptor) {
promise = interceptor(promise);
});
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response, {
data: transformData(response.data, response.headers, respTransformFn)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = $config;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if (config.cache && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache : defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (cachedResp) {
if (cachedResp.then) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the backend
if (!cachedResp) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString)]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
$rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value == null || value == undefined) return;
if (isObject(value)) {
value = toJson(value);
}
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
}];
}
var XHR = window.XMLHttpRequest || function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
var status;
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the
// response is in the cache. the promise api will ensure that to the app code the api is
// always async
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
completeRequest(
callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders());
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
xhr.send(post || '');
if (timeout > 0) {
$browserDefer(function() {
status = -1;
xhr.abort();
}, timeout);
}
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1];
// fix status code for file protocol (it's always 0)
status = (protocol == 'file') ? (response ? 200 : 404) : status;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status == 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
}
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider(){
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a the timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, who's execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {*} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup = function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
promise.then(cleanup, cleanup);
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
* achieve this a filter definition consists of a factory function which is annotated with dependencies and is
* responsible for creating a the filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
* Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression | [ filter_name ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}];
////////////////////////////////////////
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @example
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"å><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng-repeat="friend in friends | filter:search">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression) {
if (!(array instanceof Array)) return array;
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
var search = function(obj, text){
if (text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
return false;
case "array":
for ( var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression = {$:expression};
case "object":
for (var key in expression) {
if (key == '$') {
(function() {
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function() {
var path = key;
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
}
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
if (numStr.indexOf('e') !== -1) {
formatedText = numStr;
} else {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize);
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var offset = date.getTimezoneOffset();
return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2);
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h o''clock"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ).
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array containing only a specified number of elements in an array. The elements
* are taken from either the beginning or the end of the source array, as specified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `limit` number is
* positive, `limit` number of items from the beginning of the source array are copied.
* If the number is negative, `limit` number of items from the end of the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit`
* elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.limit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="limit">
<p>Output: {{ numbers | limitTo:limit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit = int(limit);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more informaton about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate = '-age';
}
</script>
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
<tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
if (!(array instanceof Array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = $parse(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy = [];
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") v1 = v1.toLowerCase();
if (t1 == "string") v2 = v2.toLowerCase();
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
}
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/*
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* <a href="" ng-click="model.$save()">Save</a>
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
// turn <a href ng-click="..">link</a> into a link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!attr.href) {
attr.$set('href', '');
}
return function(scope, element) {
element.bind('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe('');
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng-init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngMultiple
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngMultiple` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
<select id="select" ng-multiple="checked">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element SELECT
* @param {expression} ngMultiple Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function(value) {
attr.$set(attrName, !!value);
});
};
}
};
};
});
// ng-src, ng-href are interpolated
forEach(['src', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect
if (msie) element.prop(attrName, value);
});
}
};
};
});
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containg forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
*
* @property {Object} $error Is an object hash, containing references to all invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`),
* - values are arrays of controls or forms that are invalid with given error.
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form = this,
parentForm = element.parent().controller('form') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
errors = form.$error = {};
// init state
form.$name = attrs.name;
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
form.$addControl = function(control) {
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] = control;
}
};
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
};
form.$setValidity = function(validationToken, isValid, control) {
var queue = errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid = true;
form.$invalid = false;
}
errors[validationToken] = false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] = queue = [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid = false;
form.$invalid = true;
}
};
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In angular forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in application specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
* is because of the following form submission rules coming from the html spec:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType = 'guest';
}
</script>
<form name="myForm" ng-controller="Ctrl">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveDir = {
name: 'form',
restrict: 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
formElement.bind('submit', function(event) {
event.preventDefault();
});
}
var parentFormCtrl = formElement.parent().controller('form'),
alias = attr.name || attr.ngForm;
if (alias) {
scope[alias] = controller;
}
if (parentFormCtrl) {
formElement.bind('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
scope[alias] = undefined;
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
var formDirective = valueFn(formDirectiveDir);
var ngFormDirective = valueFn(extend(copy(formDirectiveDir), {restrict: 'EAC'}));
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\w*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less then `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value = 12;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<span class="error" ng-show="myForm.list.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'http://google.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'me@example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('me@example.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color = 'blue';
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" value="green"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngTrueValue The value to which the expression should be set when selected.
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = trim(element.val());
if (ctrl.$viewValue !== value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.bind('input', listener);
} else {
var timeout;
element.bind('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
});
// if user paste into input using mouse, we need "change" event to catch it
element.bind('change', listener);
}
ctrl.$render = function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator;
var validate = function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
if (pattern.match(/^\/(.*)\/$/)) {
pattern = new RegExp(pattern.substr(1, pattern.length - 2));
patternValidator = function(value) {
return validate(pattern, value)
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength = int(attr.ngMinlength);
var minLengthValidator = function(value) {
if (!isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength = int(attr.ngMaxlength);
var maxLengthValidator = function(value) {
if (!isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min = parseFloat(attr.min);
var minValidator = function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator = function(value) {
if (isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator = function(value) {
if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.bind('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue = attr.ngTrueValue,
falseValue = attr.ngFalseValue;
if (!isString(trueValue)) trueValue = true;
if (!isString(falseValue)) falseValue = false;
element.bind('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
ctrl.$formatters.push(function(value) {
return value === trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller="Ctrl">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function() {
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
$browser);
}
}
};
}];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
* all of these functions to sanitize / convert the value as well as validate.
*
* @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
* these functions to convert the value as well as validate.
*
* @property {Object} $error An bject hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS update, value formatting and parsing. It
* specifically does not contain any logic which deals with DOM rendering or listening to
* DOM events. The `NgModelController` is meant to be extended by other directives where, the
* directive provides DOM manipulation and the `NgModelController` provides the data-binding.
*
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* <example module="customControl">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable = element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$name = $attr.name;
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign;
if (!ngModelSet) {
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
' (' + startingTag($element) + ')');
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*/
this.$render = noop;
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
$error = this.$error = {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control changes validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
this.$setValidity = function(validationErrorKey, isValid) {
if ($error[validationErrorKey] === !isValid) return;
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid = true;
this.$invalid = false;
}
} else {
toggleValidCss(false);
this.$invalid = true;
this.$valid = false;
invalidCount++;
}
$error[validationErrorKey] = !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `formatters` and if resulted value is valid, updates the model and
* calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue = function(value) {
this.$viewValue = value;
// change to dirty
if (this.$pristine) {
this.$dirty = true;
this.$pristine = false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value = fn(value);
});
if (this.$modelValue !== value) {
this.$modelValue = value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
})
}
};
// model -> value
var ctrl = this;
$scope.$watch(ngModelGet, function(value) {
// ignore change from view
if (ctrl.$modelValue === value) return;
var formatters = ctrl.$formatters,
idx = formatters.length;
ctrl.$modelValue = value;
while(idx--) {
value = formatters[idx](value);
}
if (ctrl.$viewValue !== value) {
ctrl.$viewValue = value;
ctrl.$render();
}
});
}];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* Is directive that tells Angular to do two-way data binding. It works together with `input`,
* `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
*
* `ngModel` is responsible for:
*
* - binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require,
* - providing validation behavior (i.e. required, number, email, url),
* - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective = function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
element.bind('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller="Controller">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* debug = {{confirmed}}<br />
* counter = {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function() {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective = valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between comma-seperated string into an array of strings.
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['igor', 'misko', 'vojta'];
}
</script>
<form name="myForm" ng-controller="Ctrl">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<tt>names = {{names}}</tt><br/>
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList || ',';
var parse = function(viewValue) {
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value) && !equals(parse(ctrl.$viewValue), value)) {
return value.join(', ');
}
return undefined;
});
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function(value) {
attr.$set('value', value, false);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when
* it's desirable to put bindings into template that is momentarily displayed by the browser in its
* raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the
* bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function(value) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text should be replaced with the template in ngBindTemplate.
* Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtmlUnsafe
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
* {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
* restrictive and when you absolutely trust the source of the content you are binding to.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlUnsafeDirective = [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function(value) {
element.html(value || '');
});
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
scope.$watch(attr[name], function(newVal, oldVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && (newVal !== oldVal)) {
if (isObject(oldVal) && !isArray(oldVal))
oldVal = map(oldVal, function(v, k) { if (v) return k });
element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal);
}
if (isObject(newVal) && !isArray(newVal))
newVal = map(newVal, function(v, k) { if (v) return k });
if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); }
}, true);
});
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an
* expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the classes
* new classes are added.
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.my-class {
color: red;
}
</file>
<file name="scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
*
* @description
* The `ngClassOdd` and `ngClassEven` works exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but typically a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser view.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], .ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* alternatively, the css rule (above) must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the `{@link ng.$route}`
* service.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
* constructor function.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update.
<doc:example>
<doc:source>
<script>
function SettingsController($scope) {
$scope.name = "John Smith";
$scope.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ];
$scope.greet = function() {
alert(this.name);
};
$scope.addContact = function() {
this.contacts.push({type:'email', value:'yourname@example.org'});
};
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
}
</script>
<div ng-controller="SettingsController">
Name: <input type="text" ng-model="name"/>
[ <a href="" ng-click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="clearContact(contact)">clear</a>
| <a href="" ng-click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
expect(element('.doc-example-live li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li:nth-child(2) input').val())
.toBe('john.smith@example.org');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('');
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live li:nth-child(3) input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective = [function() {
return {
scope: true,
controller: '@'
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
* @priority 1000
*
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
* This directive should be used on the root element of the application (typically the `<html>`
* element or other element with the {@link ng.directive:ngApp ngApp}
* directive).
*
* If enabled the performance of template expression evaluator will suffer slightly, so don't enable
* this mode unless you need it.
*
* @element html
*/
var ngCspDirective = ['$sniffer', function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp = true;
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.bind(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}];
}
);
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* dblclick. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page).
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if (this.text) {
this.list.push(this.text);
this.text = '';
}
};
}
</script>
<form ng-submit="submit()" ng-controller="Ctrl">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
element.bind('submit', function() {
scope.$apply(attrs.ngSubmit);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
* file:// access on some browsers).
*
* @scope
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example>
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url"></div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]').text()).toEqual('');
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile',
function($http, $templateCache, $anchorScroll, $compile) {
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, element) {
var changeCounter = 0,
childScope;
var clearContent = function() {
if (childScope) {
childScope.$destroy();
childScope = null;
}
element.html('');
};
scope.$watch(srcExp, function(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
if (childScope) childScope.$destroy();
childScope = scope.$new();
element.html(response);
$compile(element.contents())(childScope);
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter) clearContent();
});
} else clearContent();
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective = ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. You will see the use of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspoding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}
</script>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
var BRACE = /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp),
whensExpFns = {};
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, '{{' + numberExp + '-' + offset + '}}'));
});
scope.$watch(function() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!whens[value]) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function(newVal) {
element.text(newVal);
});
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
* * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
* * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
*
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng-repeat', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
var ngRepeatDirective = ngDirective({
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function(scope, iterStartElement, attr){
var expression = attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
lhs + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = match[2];
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is an array of objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
// We need an array of these objects since the same object can be returned from the iterator.
// We expect this to be a rare case.
var lastOrder = new HashQueueMap();
scope.$watch(function(scope){
var index, length,
collection = scope.$eval(rhs),
collectionLength = size(collection, true),
childScope,
// Same as lastOrder but it has the current state. It will become the
// lastOrder on the next iteration.
nextOrder = new HashQueueMap(),
key, value, // key/value of iteration
array, last, // last object information {scope, element, index}
cursor = iterStartElement; // current position of the node
if (!isArray(collection)) {
// if object, extract keys, sort them and use to determine order of iteration over obj props
array = [];
for(key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
array.push(key);
}
}
array.sort();
} else {
array = collection || [];
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = array.length; index < length; index++) {
key = (collection === array) ? index : array[index];
value = collection[key];
last = lastOrder.shift(value);
if (last) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = last.scope;
nextOrder.push(value, last);
if (index === last.index) {
// do nothing
cursor = last.element;
} else {
// existing item which got moved
last.index = index;
// This may be a noop, if the element is next, but I don't know of a good way to
// figure this out, since it would require extra DOM access, so let's just hope that
// the browsers realizes that it is noop, and treats it as such.
cursor.after(last.element);
cursor = last.element;
}
} else {
// new item which we don't know about
childScope = scope.$new();
}
childScope[valueIdent] = value;
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === (collectionLength - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
if (!last) {
linker(childScope, function(clone){
cursor.after(clone);
last = {
scope: childScope,
element: (cursor = clone),
index: index
};
nextOrder.push(value, last);
});
}
}
//shrink children
for (key in lastOrder) {
if (lastOrder.hasOwnProperty(key)) {
array = lastOrder[key];
while(array.length) {
value = array.pop();
value.element.remove();
value.scope.$destroy();
}
}
}
lastOrder = nextOrder;
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/>
Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngShowDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngShow, function(value){
element.css('display', toBoolean(value) ? '' : 'none');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` and `ngShow` directives hide or show a portion
* of the HTML conditionally.
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} truthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngHideDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngHide, function(value){
element.css('display', toBoolean(value) ? 'none' : '');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* Conditionally change the DOM structure.
*
* @usageContent
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* ...
* <ANY ng-switch-default>...</ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed.
* * `ngSwitchDefault`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</script>
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
</div>
</doc:source>
<doc:scenario>
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
});
it('should select deafault', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</doc:scenario>
</doc:example>
*/
var NG_SWITCH = 'ng-switch';
var ngSwitchDirective = valueFn({
restrict: 'EA',
compile: function(element, attr) {
var watchExpr = attr.ngSwitch || attr.on,
cases = {};
element.data(NG_SWITCH, cases);
return function(scope, element){
var selectedTransclude,
selectedElement,
selectedScope;
scope.$watch(watchExpr, function(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement = selectedScope = null;
}
if ((selectedTransclude = cases['!' + value] || cases['?'])) {
scope.$eval(attr.change);
selectedScope = scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement = caseElement;
element.append(caseElement);
});
}
});
};
}
});
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases = element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['!' + attrs.ngSwitchWhen] = transclude;
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases = element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['?'] = transclude;
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @element ANY
*
* @example
<doc:example module="transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { title:'bind' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller="Ctrl">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective = ngDirective({
controller: ['$transclude', '$element', function($transclude, $element) {
$transclude(function(clone) {
$element.append(clone);
});
}]
});
/**
* @ngdoc directive
* @name ng.directive:ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ng.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* @scope
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.template = {{$route.current.template}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngView#$viewContentLoaded
* @eventOf ng.directive:ngView
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
'$controller',
function($http, $templateCache, $route, $anchorScroll, $compile,
$controller) {
return {
restrict: 'ECA',
terminal: true,
link: function(scope, element, attr) {
var lastScope,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope = null;
}
}
function clearContent() {
element.html('');
destroyLastScope();
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (template) {
element.html(template);
destroyLastScope();
var link = $compile(element.contents()),
current = $route.current,
controller;
lastScope = current.scope = scope.$new();
if (current.controller) {
locals.$scope = lastScope;
controller = $controller(current.controller, locals);
element.contents().data('$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
// $anchorScroll might listen on event...
$anchorScroll();
} else {
clearContent();
}
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:script
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @restrict E
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for a `<select>` element using an array or an object obtained by evaluating the
* `ngOptions` expression.
*˝˝
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an option element can currently
* be bound to string values only.
*
* @param {string} name assignable expression to data-bind to.
* @param {string=} required The control is considered valid only if value is entered.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // red
}
</script>
<div ng-controller="MyCntrl">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective = valueFn({ terminal: true });
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/,
nullModelCtrl = {$setViewValue: noop};
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
}
self.addOption = function(value) {
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue == value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
}
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
}
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
if (children[i].value == '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.bind('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.children(), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.bind('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.children(), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + optionsExp + "'.");
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.bind('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index, groupIndex, length, groupLength;
if (multiple) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
key = optionElement.val();
if (keyName) locals[keyName] = key;
locals[valueName] = collection[key];
value.push(valueFn(scope, locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} else {
locals[valueName] = collection[key];
if (keyName) locals[keyName] = key;
value = valueFn(scope, locals);
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render = render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element;
if (multiple) {
selectedSet = new HashMap(modelValue);
} else if (modelValue === null || nullOption) {
// if we are not multiselect, and we are null then we have to add the nullOption
optionGroups[''].push({selected:modelValue === null, id:'', label:''});
selectedSet = true;
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
optionGroupName = groupByFn(scope, locals) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = selectedSet.remove(valueFn(scope, locals)) != undefined;
} else {
selected = modelValue === valueFn(scope, locals);
selectedSet = selectedSet || selected; // see if at least one item is selected
}
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
label: displayFn(scope, locals) || '', // what will be seen by the user
selected: selected // determine if we should be selected
});
}
if (!multiple && !selectedSet) {
// nothing was selected, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the beginning
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
if (existingOption.element.selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
}
}];
var optionDirective = ['$interpolate', function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
require: '^select',
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function (scope, element, attr, selectCtrl) {
if (selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function(newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.bind('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
}
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: true
});
/**
* Setup file for the Scenario.
* Must be first in the compilation/bootstrap list.
*/
// Public namespace
angular.scenario = angular.scenario || {};
/**
* Defines a new output format.
*
* @param {string} name the name of the new output format
* @param {function()} fn function(context, runner) that generates the output
*/
angular.scenario.output = angular.scenario.output || function(name, fn) {
angular.scenario.output[name] = fn;
};
/**
* Defines a new DSL statement. If your factory function returns a Future
* it's returned, otherwise the result is assumed to be a map of functions
* for chaining. Chained functions are subject to the same rules.
*
* Note: All functions on the chain are bound to the chain scope so values
* set on "this" in your statement function are available in the chained
* functions.
*
* @param {string} name The name of the statement
* @param {function()} fn Factory function(), return a function for
* the statement.
*/
angular.scenario.dsl = angular.scenario.dsl || function(name, fn) {
angular.scenario.dsl[name] = function() {
function executeStatement(statement, args) {
var result = statement.apply(this, args);
if (angular.isFunction(result) || result instanceof angular.scenario.Future)
return result;
var self = this;
var chain = angular.extend({}, result);
angular.forEach(chain, function(value, name) {
if (angular.isFunction(value)) {
chain[name] = function() {
return executeStatement.call(self, value, arguments);
};
} else {
chain[name] = value;
}
});
return chain;
}
var statement = fn.apply(this, arguments);
return function() {
return executeStatement.call(this, statement, arguments);
};
};
};
/**
* Defines a new matcher for use with the expects() statement. The value
* this.actual (like in Jasmine) is available in your matcher to compare
* against. Your function should return a boolean. The future is automatically
* created for you.
*
* @param {string} name The name of the matcher
* @param {function()} fn The matching function(expected).
*/
angular.scenario.matcher = angular.scenario.matcher || function(name, fn) {
angular.scenario.matcher[name] = function(expected) {
var prefix = 'expect ' + this.future.name + ' ';
if (this.inverse) {
prefix += 'not ';
}
var self = this;
this.addFuture(prefix + name + ' ' + angular.toJson(expected),
function(done) {
var error;
self.actual = self.future.value;
if ((self.inverse && fn.call(self, expected)) ||
(!self.inverse && !fn.call(self, expected))) {
error = 'expected ' + angular.toJson(expected) +
' but was ' + angular.toJson(self.actual);
}
done(error);
});
};
};
/**
* Initialize the scenario runner and run !
*
* Access global window and document object
* Access $runner through closure
*
* @param {Object=} config Config options
*/
angular.scenario.setUpAndRun = function(config) {
var href = window.location.href;
var body = _jQuery(document.body);
var output = [];
var objModel = new angular.scenario.ObjectModel($runner);
if (config && config.scenario_output) {
output = config.scenario_output.split(',');
}
angular.forEach(angular.scenario.output, function(fn, name) {
if (!output.length || indexOf(output,name) != -1) {
var context = body.append('<div></div>').find('div:last');
context.attr('id', name);
fn.call({}, context, $runner, objModel);
}
});
if (!/^http/.test(href) && !/^https/.test(href)) {
body.append('<p id="system-error"></p>');
body.find('#system-error').text(
'Scenario runner must be run using http or https. The protocol ' +
href.split(':')[0] + ':// is not supported.'
);
return;
}
var appFrame = body.append('<div id="application"></div>').find('#application');
var application = new angular.scenario.Application(appFrame);
$runner.on('RunnerEnd', function() {
appFrame.css('display', 'none');
appFrame.find('iframe').attr('src', 'about:blank');
});
$runner.on('RunnerError', function(error) {
if (window.console) {
console.log(formatException(error));
} else {
// Do something for IE
alert(error);
}
});
$runner.run(application);
};
/**
* Iterates through list with iterator function that must call the
* continueFunction to continute iterating.
*
* @param {Array} list list to iterate over
* @param {function()} iterator Callback function(value, continueFunction)
* @param {function()} done Callback function(error, result) called when
* iteration finishes or an error occurs.
*/
function asyncForEach(list, iterator, done) {
var i = 0;
function loop(error, index) {
if (index && index > i) {
i = index;
}
if (error || i >= list.length) {
done(error);
} else {
try {
iterator(list[i++], loop);
} catch (e) {
done(e);
}
}
}
loop();
}
/**
* Formats an exception into a string with the stack trace, but limits
* to a specific line length.
*
* @param {Object} error The exception to format, can be anything throwable
* @param {Number=} [maxStackLines=5] max lines of the stack trace to include
* default is 5.
*/
function formatException(error, maxStackLines) {
maxStackLines = maxStackLines || 5;
var message = error.toString();
if (error.stack) {
var stack = error.stack.split('\n');
if (stack[0].indexOf(message) === -1) {
maxStackLines++;
stack.unshift(error.message);
}
message = stack.slice(0, maxStackLines).join('\n');
}
return message;
}
/**
* Returns a function that gets the file name and line number from a
* location in the stack if available based on the call site.
*
* Note: this returns another function because accessing .stack is very
* expensive in Chrome.
*
* @param {Number} offset Number of stack lines to skip
*/
function callerFile(offset) {
var error = new Error();
return function() {
var line = (error.stack || '').split('\n')[offset];
// Clean up the stack trace line
if (line) {
if (line.indexOf('@') !== -1) {
// Firefox
line = line.substring(line.indexOf('@')+1);
} else {
// Chrome
line = line.substring(line.indexOf('(')+1).replace(')', '');
}
}
return line || '';
};
}
/**
* Triggers a browser event. Attempts to choose the right event if one is
* not specified.
*
* @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement
* @param {string} type Optional event type.
* @param {Array.<string>=} keys Optional list of pressed keys
* (valid values: 'alt', 'meta', 'shift', 'ctrl')
*/
function browserTrigger(element, type, keys) {
if (element && !element.nodeName) element = element[0];
if (!element) return;
if (!type) {
type = {
'text': 'change',
'textarea': 'change',
'hidden': 'change',
'password': 'change',
'button': 'click',
'submit': 'click',
'reset': 'click',
'image': 'click',
'checkbox': 'click',
'radio': 'click',
'select-one': 'change',
'select-multiple': 'change'
}[lowercase(element.type)] || 'click';
}
if (lowercase(nodeName_(element)) == 'option') {
element.parentNode.value = element.value;
element = element.parentNode;
type = 'change';
}
keys = keys || [];
function pressed(key) {
return indexOf(keys, key) !== -1;
}
if (msie < 9) {
switch(element.type) {
case 'radio':
case 'checkbox':
element.checked = !element.checked;
break;
}
// WTF!!! Error: Unspecified error.
// Don't know why, but some elements when detached seem to be in inconsistent state and
// calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error)
// forcing the browser to compute the element position (by reading its CSS)
// puts the element in consistent state.
element.style.posLeft;
// TODO(vojta): create event objects with pressed keys to get it working on IE<9
var ret = element.fireEvent('on' + type);
if (lowercase(element.type) == 'submit') {
while(element) {
if (lowercase(element.nodeName) == 'form') {
element.fireEvent('onsubmit');
break;
}
element = element.parentNode;
}
}
return ret;
} else {
var evnt = document.createEvent('MouseEvents'),
originalPreventDefault = evnt.preventDefault,
iframe = _jQuery('#application iframe')[0],
appWindow = iframe ? iframe.contentWindow : window,
fakeProcessDefault = true,
finalProcessDefault;
// igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208
appWindow.angular['ff-684208-preventDefault'] = false;
evnt.preventDefault = function() {
fakeProcessDefault = false;
return originalPreventDefault.apply(evnt, arguments);
};
evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'),
pressed('shift'), pressed('meta'), 0, element);
element.dispatchEvent(evnt);
finalProcessDefault = !(appWindow.angular['ff-684208-preventDefault'] || !fakeProcessDefault);
delete appWindow.angular['ff-684208-preventDefault'];
return finalProcessDefault;
}
}
/**
* Don't use the jQuery trigger method since it works incorrectly.
*
* jQuery notifies listeners and then changes the state of a checkbox and
* does not create a real browser event. A real click changes the state of
* the checkbox and then notifies listeners.
*
* To work around this we instead use our own handler that fires a real event.
*/
(function(fn){
var parentTrigger = fn.trigger;
fn.trigger = function(type) {
if (/(click|change|keydown|blur|input)/.test(type)) {
var processDefaults = [];
this.each(function(index, node) {
processDefaults.push(browserTrigger(node, type));
});
// this is not compatible with jQuery - we return an array of returned values,
// so that scenario runner know whether JS code has preventDefault() of the event or not...
return processDefaults;
}
return parentTrigger.apply(this, arguments);
};
})(_jQuery.fn);
/**
* Finds all bindings with the substring match of name and returns an
* array of their values.
*
* @param {string} bindExp The name to match
* @return {Array.<string>} String of binding values
*/
_jQuery.fn.bindings = function(windowJquery, bindExp) {
var result = [], match,
bindSelector = '.ng-binding:visible';
if (angular.isString(bindExp)) {
bindExp = bindExp.replace(/\s/g, '');
match = function (actualExp) {
if (actualExp) {
actualExp = actualExp.replace(/\s/g, '');
if (actualExp == bindExp) return true;
if (actualExp.indexOf(bindExp) == 0) {
return actualExp.charAt(bindExp.length) == '|';
}
}
}
} else if (bindExp) {
match = function(actualExp) {
return actualExp && bindExp.exec(actualExp);
}
} else {
match = function(actualExp) {
return !!actualExp;
};
}
var selection = this.find(bindSelector);
if (this.is(bindSelector)) {
selection = selection.add(this);
}
function push(value) {
if (value == undefined) {
value = '';
} else if (typeof value != 'string') {
value = angular.toJson(value);
}
result.push('' + value);
}
selection.each(function() {
var element = windowJquery(this),
binding;
if (binding = element.data('$binding')) {
if (typeof binding == 'string') {
if (match(binding)) {
push(element.scope().$eval(binding));
}
} else {
if (!angular.isArray(binding)) {
binding = [binding];
}
for(var fns, j=0, jj=binding.length; j<jj; j++) {
fns = binding[j];
if (fns.parts) {
fns = fns.parts;
} else {
fns = [fns];
}
for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) {
if(match((fn = fns[i]).exp)) {
push(fn(scope = scope || element.scope()));
}
}
}
}
}
});
return result;
};
/**
* Represents the application currently being tested and abstracts usage
* of iframes or separate windows.
*
* @param {Object} context jQuery wrapper around HTML context.
*/
angular.scenario.Application = function(context) {
this.context = context;
context.append(
'<h2>Current URL: <a href="about:blank">None</a></h2>' +
'<div id="test-frames"></div>'
);
};
/**
* Gets the jQuery collection of frames. Don't use this directly because
* frames may go stale.
*
* @private
* @return {Object} jQuery collection
*/
angular.scenario.Application.prototype.getFrame_ = function() {
return this.context.find('#test-frames iframe:last');
};
/**
* Gets the window of the test runner frame. Always favor executeAction()
* instead of this method since it prevents you from getting a stale window.
*
* @private
* @return {Object} the window of the frame
*/
angular.scenario.Application.prototype.getWindow_ = function() {
var contentWindow = this.getFrame_().prop('contentWindow');
if (!contentWindow)
throw 'Frame window is not accessible.';
return contentWindow;
};
/**
* Changes the location of the frame.
*
* @param {string} url The URL. If it begins with a # then only the
* hash of the page is changed.
* @param {function()} loadFn function($window, $document) Called when frame loads.
* @param {function()} errorFn function(error) Called if any error when loading.
*/
angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) {
var self = this;
var frame = this.getFrame_();
//TODO(esprehn): Refactor to use rethrow()
errorFn = errorFn || function(e) { throw e; };
if (url === 'about:blank') {
errorFn('Sandbox Error: Navigating to about:blank is not allowed.');
} else if (url.charAt(0) === '#') {
url = frame.attr('src').split('#')[0] + url;
frame.attr('src', url);
this.executeAction(loadFn);
} else {
frame.remove();
this.context.find('#test-frames').append('<iframe>');
frame = this.getFrame_();
frame.load(function() {
frame.unbind();
try {
self.executeAction(loadFn);
} catch (e) {
errorFn(e);
}
}).attr('src', url);
}
this.context.find('> h2 a').attr('href', url).text(url);
};
/**
* Executes a function in the context of the tested application. Will wait
* for all pending angular xhr requests before executing.
*
* @param {function()} action The callback to execute. function($window, $document)
* $document is a jQuery wrapped document.
*/
angular.scenario.Application.prototype.executeAction = function(action) {
var self = this;
var $window = this.getWindow_();
if (!$window.document) {
throw 'Sandbox Error: Application document not accessible.';
}
if (!$window.angular) {
return action.call(this, $window, _jQuery($window.document));
}
angularInit($window.document, function(element) {
var $injector = $window.angular.element(element).injector();
var $element = _jQuery(element);
$element.injector = function() {
return $injector;
};
$injector.invoke(function($browser){
$browser.notifyWhenNoOutstandingRequests(function() {
action.call(self, $window, $element);
});
});
});
};
/**
* The representation of define blocks. Don't used directly, instead use
* define() in your tests.
*
* @param {string} descName Name of the block
* @param {Object} parent describe or undefined if the root.
*/
angular.scenario.Describe = function(descName, parent) {
this.only = parent && parent.only;
this.beforeEachFns = [];
this.afterEachFns = [];
this.its = [];
this.children = [];
this.name = descName;
this.parent = parent;
this.id = angular.scenario.Describe.id++;
/**
* Calls all before functions.
*/
var beforeEachFns = this.beforeEachFns;
this.setupBefore = function() {
if (parent) parent.setupBefore.call(this);
angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this);
};
/**
* Calls all after functions.
*/
var afterEachFns = this.afterEachFns;
this.setupAfter = function() {
angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this);
if (parent) parent.setupAfter.call(this);
};
};
// Shared Unique ID generator for every describe block
angular.scenario.Describe.id = 0;
// Shared Unique ID generator for every it (spec)
angular.scenario.Describe.specId = 0;
/**
* Defines a block to execute before each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.beforeEach = function(body) {
this.beforeEachFns.push(body);
};
/**
* Defines a block to execute after each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.afterEach = function(body) {
this.afterEachFns.push(body);
};
/**
* Creates a new describe block that's a child of this one.
*
* @param {string} name Name of the block. Appended to the parent block's name.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.describe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
this.children.push(child);
body.call(child);
};
/**
* Same as describe() but makes ddescribe blocks the only to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.ddescribe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
child.only = true;
this.children.push(child);
body.call(child);
};
/**
* Use to disable a describe block.
*/
angular.scenario.Describe.prototype.xdescribe = angular.noop;
/**
* Defines a test.
*
* @param {string} name Name of the test.
* @param {function()} vody Body of the block.
*/
angular.scenario.Describe.prototype.it = function(name, body) {
this.its.push({
id: angular.scenario.Describe.specId++,
definition: this,
only: this.only,
name: name,
before: this.setupBefore,
body: body,
after: this.setupAfter
});
};
/**
* Same as it() but makes iit tests the only test to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.iit = function(name, body) {
this.it.apply(this, arguments);
this.its[this.its.length-1].only = true;
};
/**
* Use to disable a test block.
*/
angular.scenario.Describe.prototype.xit = angular.noop;
/**
* Gets an array of functions representing all the tests (recursively).
* that can be executed with SpecRunner's.
*
* @return {Array<Object>} Array of it blocks {
* definition : Object // parent Describe
* only: boolean
* name: string
* before: Function
* body: Function
* after: Function
* }
*/
angular.scenario.Describe.prototype.getSpecs = function() {
var specs = arguments[0] || [];
angular.forEach(this.children, function(child) {
child.getSpecs(specs);
});
angular.forEach(this.its, function(it) {
specs.push(it);
});
var only = [];
angular.forEach(specs, function(it) {
if (it.only) {
only.push(it);
}
});
return (only.length && only) || specs;
};
/**
* A future action in a spec.
*
* @param {string} name of the future action
* @param {function()} future callback(error, result)
* @param {function()} Optional. function that returns the file/line number.
*/
angular.scenario.Future = function(name, behavior, line) {
this.name = name;
this.behavior = behavior;
this.fulfilled = false;
this.value = undefined;
this.parser = angular.identity;
this.line = line || function() { return ''; };
};
/**
* Executes the behavior of the closure.
*
* @param {function()} doneFn Callback function(error, result)
*/
angular.scenario.Future.prototype.execute = function(doneFn) {
var self = this;
this.behavior(function(error, result) {
self.fulfilled = true;
if (result) {
try {
result = self.parser(result);
} catch(e) {
error = e;
}
}
self.value = error || result;
doneFn(error, result);
});
};
/**
* Configures the future to convert it's final with a function fn(value)
*
* @param {function()} fn function(value) that returns the parsed value
*/
angular.scenario.Future.prototype.parsedWith = function(fn) {
this.parser = fn;
return this;
};
/**
* Configures the future to parse it's final value from JSON
* into objects.
*/
angular.scenario.Future.prototype.fromJson = function() {
return this.parsedWith(angular.fromJson);
};
/**
* Configures the future to convert it's final value from objects
* into JSON.
*/
angular.scenario.Future.prototype.toJson = function() {
return this.parsedWith(angular.toJson);
};
/**
* Maintains an object tree from the runner events.
*
* @param {Object} runner The scenario Runner instance to connect to.
*
* TODO(esprehn): Every output type creates one of these, but we probably
* want one global shared instance. Need to handle events better too
* so the HTML output doesn't need to do spec model.getSpec(spec.id)
* silliness.
*
* TODO(vojta) refactor on, emit methods (from all objects) - use inheritance
*/
angular.scenario.ObjectModel = function(runner) {
var self = this;
this.specMap = {};
this.listeners = [];
this.value = {
name: '',
children: {}
};
runner.on('SpecBegin', function(spec) {
var block = self.value,
definitions = [];
angular.forEach(self.getDefinitionPath(spec), function(def) {
if (!block.children[def.name]) {
block.children[def.name] = {
id: def.id,
name: def.name,
children: {},
specs: {}
};
}
block = block.children[def.name];
definitions.push(def.name);
});
var it = self.specMap[spec.id] =
block.specs[spec.name] =
new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions);
// forward the event
self.emit('SpecBegin', it);
});
runner.on('SpecError', function(spec, error) {
var it = self.getSpec(spec.id);
it.status = 'error';
it.error = error;
// forward the event
self.emit('SpecError', it, error);
});
runner.on('SpecEnd', function(spec) {
var it = self.getSpec(spec.id);
complete(it);
// forward the event
self.emit('SpecEnd', it);
});
runner.on('StepBegin', function(spec, step) {
var it = self.getSpec(spec.id);
var step = new angular.scenario.ObjectModel.Step(step.name);
it.steps.push(step);
// forward the event
self.emit('StepBegin', it, step);
});
runner.on('StepEnd', function(spec) {
var it = self.getSpec(spec.id);
var step = it.getLastStep();
if (step.name !== step.name)
throw 'Events fired in the wrong order. Step names don\'t match.';
complete(step);
// forward the event
self.emit('StepEnd', it, step);
});
runner.on('StepFailure', function(spec, step, error) {
var it = self.getSpec(spec.id),
modelStep = it.getLastStep();
modelStep.setErrorStatus('failure', error, step.line());
it.setStatusFromStep(modelStep);
// forward the event
self.emit('StepFailure', it, modelStep, error);
});
runner.on('StepError', function(spec, step, error) {
var it = self.getSpec(spec.id),
modelStep = it.getLastStep();
modelStep.setErrorStatus('error', error, step.line());
it.setStatusFromStep(modelStep);
// forward the event
self.emit('StepError', it, modelStep, error);
});
runner.on('RunnerEnd', function() {
self.emit('RunnerEnd');
});
function complete(item) {
item.endTime = new Date().getTime();
item.duration = item.endTime - item.startTime;
item.status = item.status || 'success';
}
};
/**
* Adds a listener for an event.
*
* @param {string} eventName Name of the event to add a handler for
* @param {function()} listener Function that will be called when event is fired
*/
angular.scenario.ObjectModel.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.ObjectModel.prototype.emit = function(eventName) {
var self = this,
args = Array.prototype.slice.call(arguments, 1),
eventName = eventName.toLowerCase();
if (this.listeners[eventName]) {
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
}
};
/**
* Computes the path of definition describe blocks that wrap around
* this spec.
*
* @param spec Spec to compute the path for.
* @return {Array<Describe>} The describe block path
*/
angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) {
var path = [];
var currentDefinition = spec.definition;
while (currentDefinition && currentDefinition.name) {
path.unshift(currentDefinition);
currentDefinition = currentDefinition.parent;
}
return path;
};
/**
* Gets a spec by id.
*
* @param {string} The id of the spec to get the object for.
* @return {Object} the Spec instance
*/
angular.scenario.ObjectModel.prototype.getSpec = function(id) {
return this.specMap[id];
};
/**
* A single it block.
*
* @param {string} id Id of the spec
* @param {string} name Name of the spec
* @param {Array<string>=} definitionNames List of all describe block names that wrap this spec
*/
angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) {
this.id = id;
this.name = name;
this.startTime = new Date().getTime();
this.steps = [];
this.fullDefinitionName = (definitionNames || []).join(' ');
};
/**
* Adds a new step to the Spec.
*
* @param {string} step Name of the step (really name of the future)
* @return {Object} the added step
*/
angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) {
var step = new angular.scenario.ObjectModel.Step(name);
this.steps.push(step);
return step;
};
/**
* Gets the most recent step.
*
* @return {Object} the step
*/
angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() {
return this.steps[this.steps.length-1];
};
/**
* Set status of the Spec from given Step
*
* @param {angular.scenario.ObjectModel.Step} step
*/
angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) {
if (!this.status || step.status == 'error') {
this.status = step.status;
this.error = step.error;
this.line = step.line;
}
};
/**
* A single step inside a Spec.
*
* @param {string} step Name of the step
*/
angular.scenario.ObjectModel.Step = function(name) {
this.name = name;
this.startTime = new Date().getTime();
};
/**
* Helper method for setting all error status related properties
*
* @param {string} status
* @param {string} error
* @param {string} line
*/
angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) {
this.status = status;
this.error = error;
this.line = line;
};
/**
* The representation of define blocks. Don't used directly, instead use
* define() in your tests.
*
* @param {string} descName Name of the block
* @param {Object} parent describe or undefined if the root.
*/
angular.scenario.Describe = function(descName, parent) {
this.only = parent && parent.only;
this.beforeEachFns = [];
this.afterEachFns = [];
this.its = [];
this.children = [];
this.name = descName;
this.parent = parent;
this.id = angular.scenario.Describe.id++;
/**
* Calls all before functions.
*/
var beforeEachFns = this.beforeEachFns;
this.setupBefore = function() {
if (parent) parent.setupBefore.call(this);
angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this);
};
/**
* Calls all after functions.
*/
var afterEachFns = this.afterEachFns;
this.setupAfter = function() {
angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this);
if (parent) parent.setupAfter.call(this);
};
};
// Shared Unique ID generator for every describe block
angular.scenario.Describe.id = 0;
// Shared Unique ID generator for every it (spec)
angular.scenario.Describe.specId = 0;
/**
* Defines a block to execute before each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.beforeEach = function(body) {
this.beforeEachFns.push(body);
};
/**
* Defines a block to execute after each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.afterEach = function(body) {
this.afterEachFns.push(body);
};
/**
* Creates a new describe block that's a child of this one.
*
* @param {string} name Name of the block. Appended to the parent block's name.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.describe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
this.children.push(child);
body.call(child);
};
/**
* Same as describe() but makes ddescribe blocks the only to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.ddescribe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
child.only = true;
this.children.push(child);
body.call(child);
};
/**
* Use to disable a describe block.
*/
angular.scenario.Describe.prototype.xdescribe = angular.noop;
/**
* Defines a test.
*
* @param {string} name Name of the test.
* @param {function()} vody Body of the block.
*/
angular.scenario.Describe.prototype.it = function(name, body) {
this.its.push({
id: angular.scenario.Describe.specId++,
definition: this,
only: this.only,
name: name,
before: this.setupBefore,
body: body,
after: this.setupAfter
});
};
/**
* Same as it() but makes iit tests the only test to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.iit = function(name, body) {
this.it.apply(this, arguments);
this.its[this.its.length-1].only = true;
};
/**
* Use to disable a test block.
*/
angular.scenario.Describe.prototype.xit = angular.noop;
/**
* Gets an array of functions representing all the tests (recursively).
* that can be executed with SpecRunner's.
*
* @return {Array<Object>} Array of it blocks {
* definition : Object // parent Describe
* only: boolean
* name: string
* before: Function
* body: Function
* after: Function
* }
*/
angular.scenario.Describe.prototype.getSpecs = function() {
var specs = arguments[0] || [];
angular.forEach(this.children, function(child) {
child.getSpecs(specs);
});
angular.forEach(this.its, function(it) {
specs.push(it);
});
var only = [];
angular.forEach(specs, function(it) {
if (it.only) {
only.push(it);
}
});
return (only.length && only) || specs;
};
/**
* Runner for scenarios
*
* Has to be initialized before any test is loaded,
* because it publishes the API into window (global space).
*/
angular.scenario.Runner = function($window) {
this.listeners = [];
this.$window = $window;
this.rootDescribe = new angular.scenario.Describe();
this.currentDescribe = this.rootDescribe;
this.api = {
it: this.it,
iit: this.iit,
xit: angular.noop,
describe: this.describe,
ddescribe: this.ddescribe,
xdescribe: angular.noop,
beforeEach: this.beforeEach,
afterEach: this.afterEach
};
angular.forEach(this.api, angular.bind(this, function(fn, key) {
this.$window[key] = angular.bind(this, fn);
}));
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.Runner.prototype.emit = function(eventName) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
eventName = eventName.toLowerCase();
if (!this.listeners[eventName])
return;
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
};
/**
* Adds a listener for an event.
*
* @param {string} eventName The name of the event to add a handler for
* @param {string} listener The fn(...) that takes the extra arguments from emit()
*/
angular.scenario.Runner.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Defines a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.describe = function(name, body) {
var self = this;
this.currentDescribe.describe(name, function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Same as describe, but makes ddescribe the only blocks to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.ddescribe = function(name, body) {
var self = this;
this.currentDescribe.ddescribe(name, function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Defines a test in a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.it = function(name, body) {
this.currentDescribe.it(name, body);
};
/**
* Same as it, but makes iit tests the only tests to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.iit = function(name, body) {
this.currentDescribe.iit(name, body);
};
/**
* Defines a function to be called before each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.beforeEach = function(body) {
this.currentDescribe.beforeEach(body);
};
/**
* Defines a function to be called after each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.afterEach = function(body) {
this.currentDescribe.afterEach(body);
};
/**
* Creates a new spec runner.
*
* @private
* @param {Object} scope parent scope
*/
angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
var child = scope.$new();
var Cls = angular.scenario.SpecRunner;
// Export all the methods to child scope manually as now we don't mess controllers with scopes
// TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current
for (var name in Cls.prototype)
child[name] = angular.bind(child, Cls.prototype[name]);
Cls.call(child);
return child;
};
/**
* Runs all the loaded tests with the specified runner class on the
* provided application.
*
* @param {angular.scenario.Application} application App to remote control.
*/
angular.scenario.Runner.prototype.run = function(application) {
var self = this;
var $root = angular.injector(['ng']).get('$rootScope');
angular.extend($root, this);
angular.forEach(angular.scenario.Runner.prototype, function(fn, name) {
$root[name] = angular.bind(self, fn);
});
$root.application = application;
$root.emit('RunnerBegin');
asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) {
var dslCache = {};
var runner = self.createSpecRunner_($root);
angular.forEach(angular.scenario.dsl, function(fn, key) {
dslCache[key] = fn.call($root);
});
angular.forEach(angular.scenario.dsl, function(fn, key) {
self.$window[key] = function() {
var line = callerFile(3);
var scope = runner.$new();
// Make the dsl accessible on the current chain
scope.dsl = {};
angular.forEach(dslCache, function(fn, key) {
scope.dsl[key] = function() {
return dslCache[key].apply(scope, arguments);
};
});
// Make these methods work on the current chain
scope.addFuture = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFuture.apply(scope, arguments);
};
scope.addFutureAction = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFutureAction.apply(scope, arguments);
};
return scope.dsl[key].apply(scope, arguments);
};
});
runner.run(spec, function() {
runner.$destroy();
specDone.apply(this, arguments);
});
},
function(error) {
if (error) {
self.emit('RunnerError', error);
}
self.emit('RunnerEnd');
});
};
/**
* This class is the "this" of the it/beforeEach/afterEach method.
* Responsibilities:
* - "this" for it/beforeEach/afterEach
* - keep state for single it/beforeEach/afterEach execution
* - keep track of all of the futures to execute
* - run single spec (execute each future)
*/
angular.scenario.SpecRunner = function() {
this.futures = [];
this.afterIndex = 0;
};
/**
* Executes a spec which is an it block with associated before/after functions
* based on the describe nesting.
*
* @param {Object} spec A spec object
* @param {function()} specDone function that is called when the spec finshes. Function(error, index)
*/
angular.scenario.SpecRunner.prototype.run = function(spec, specDone) {
var self = this;
this.spec = spec;
this.emit('SpecBegin', spec);
try {
spec.before.call(this);
spec.body.call(this);
this.afterIndex = this.futures.length;
spec.after.call(this);
} catch (e) {
this.emit('SpecError', spec, e);
this.emit('SpecEnd', spec);
specDone();
return;
}
var handleError = function(error, done) {
if (self.error) {
return done();
}
self.error = true;
done(null, self.afterIndex);
};
asyncForEach(
this.futures,
function(future, futureDone) {
self.step = future;
self.emit('StepBegin', spec, future);
try {
future.execute(function(error) {
if (error) {
self.emit('StepFailure', spec, future, error);
self.emit('StepEnd', spec, future);
return handleError(error, futureDone);
}
self.emit('StepEnd', spec, future);
self.$window.setTimeout(function() { futureDone(); }, 0);
});
} catch (e) {
self.emit('StepError', spec, future, e);
self.emit('StepEnd', spec, future);
handleError(e, futureDone);
}
},
function(e) {
if (e) {
self.emit('SpecError', spec, e);
}
self.emit('SpecEnd', spec);
// Call done in a timeout so exceptions don't recursively
// call this function
self.$window.setTimeout(function() { specDone(); }, 0);
}
);
};
/**
* Adds a new future action.
*
* Note: Do not pass line manually. It happens automatically.
*
* @param {string} name Name of the future
* @param {function()} behavior Behavior of the future
* @param {function()} line fn() that returns file/line number
*/
angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) {
var future = new angular.scenario.Future(name, angular.bind(this, behavior), line);
this.futures.push(future);
return future;
};
/**
* Adds a new future action to be executed on the application window.
*
* Note: Do not pass line manually. It happens automatically.
*
* @param {string} name Name of the future
* @param {function()} behavior Behavior of the future
* @param {function()} line fn() that returns file/line number
*/
angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) {
var self = this;
var NG = /\[ng\\\:/;
return this.addFuture(name, function(done) {
this.application.executeAction(function($window, $document) {
//TODO(esprehn): Refactor this so it doesn't need to be in here.
$document.elements = function(selector) {
var args = Array.prototype.slice.call(arguments, 1);
selector = (self.selector || '') + ' ' + (selector || '');
selector = _jQuery.trim(selector) || '*';
angular.forEach(args, function(value, index) {
selector = selector.replace('$' + (index + 1), value);
});
var result = $document.find(selector);
if (selector.match(NG)) {
result = result.add(selector.replace(NG, '[ng-'), $document);
}
if (!result.length) {
throw {
type: 'selector',
message: 'Selector ' + selector + ' did not match any elements.'
};
}
return result;
};
try {
behavior.call(self, $window, $document, done);
} catch(e) {
if (e.type && e.type === 'selector') {
done(e.message);
} else {
throw e;
}
}
});
}, line);
};
/**
* Shared DSL statements that are useful to all scenarios.
*/
/**
* Usage:
* pause() pauses until you call resume() in the console
*/
angular.scenario.dsl('pause', function() {
return function() {
return this.addFuture('pausing for you to resume', function(done) {
this.emit('InteractivePause', this.spec, this.step);
this.$window.resume = function() { done(); };
});
};
});
/**
* Usage:
* sleep(seconds) pauses the test for specified number of seconds
*/
angular.scenario.dsl('sleep', function() {
return function(time) {
return this.addFuture('sleep for ' + time + ' seconds', function(done) {
this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000);
});
};
});
/**
* Usage:
* browser().navigateTo(url) Loads the url into the frame
* browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to
* browser().reload() refresh the page (reload the same URL)
* browser().window.href() window.location.href
* browser().window.path() window.location.pathname
* browser().window.search() window.location.search
* browser().window.hash() window.location.hash without # prefix
* browser().location().url() see ng.$location#url
* browser().location().path() see ng.$location#path
* browser().location().search() see ng.$location#search
* browser().location().hash() see ng.$location#hash
*/
angular.scenario.dsl('browser', function() {
var chain = {};
chain.navigateTo = function(url, delegate) {
var application = this.application;
return this.addFuture("browser navigate to '" + url + "'", function(done) {
if (delegate) {
url = delegate.call(this, url);
}
application.navigateTo(url, function() {
done(null, url);
}, done);
});
};
chain.reload = function() {
var application = this.application;
return this.addFutureAction('browser reload', function($window, $document, done) {
var href = $window.location.href;
application.navigateTo(href, function() {
done(null, href);
}, done);
});
};
chain.window = function() {
var api = {};
api.href = function() {
return this.addFutureAction('window.location.href', function($window, $document, done) {
done(null, $window.location.href);
});
};
api.path = function() {
return this.addFutureAction('window.location.path', function($window, $document, done) {
done(null, $window.location.pathname);
});
};
api.search = function() {
return this.addFutureAction('window.location.search', function($window, $document, done) {
done(null, $window.location.search);
});
};
api.hash = function() {
return this.addFutureAction('window.location.hash', function($window, $document, done) {
done(null, $window.location.hash.replace('#', ''));
});
};
return api;
};
chain.location = function() {
var api = {};
api.url = function() {
return this.addFutureAction('$location.url()', function($window, $document, done) {
done(null, $document.injector().get('$location').url());
});
};
api.path = function() {
return this.addFutureAction('$location.path()', function($window, $document, done) {
done(null, $document.injector().get('$location').path());
});
};
api.search = function() {
return this.addFutureAction('$location.search()', function($window, $document, done) {
done(null, $document.injector().get('$location').search());
});
};
api.hash = function() {
return this.addFutureAction('$location.hash()', function($window, $document, done) {
done(null, $document.injector().get('$location').hash());
});
};
return api;
};
return function() {
return chain;
};
});
/**
* Usage:
* expect(future).{matcher} where matcher is one of the matchers defined
* with angular.scenario.matcher
*
* ex. expect(binding("name")).toEqual("Elliott")
*/
angular.scenario.dsl('expect', function() {
var chain = angular.extend({}, angular.scenario.matcher);
chain.not = function() {
this.inverse = true;
return chain;
};
return function(future) {
this.future = future;
return chain;
};
});
/**
* Usage:
* using(selector, label) scopes the next DSL element selection
*
* ex.
* using('#foo', "'Foo' text field").input('bar')
*/
angular.scenario.dsl('using', function() {
return function(selector, label) {
this.selector = _jQuery.trim((this.selector||'') + ' ' + selector);
if (angular.isString(label) && label.length) {
this.label = label + ' ( ' + this.selector + ' )';
} else {
this.label = this.selector;
}
return this.dsl;
};
});
/**
* Usage:
* binding(name) returns the value of the first matching binding
*/
angular.scenario.dsl('binding', function() {
return function(name) {
return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) {
var values = $document.elements().bindings($window.angular.element, name);
if (!values.length) {
return done("Binding selector '" + name + "' did not match.");
}
done(null, values[0]);
});
};
});
/**
* Usage:
* input(name).enter(value) enters value in input with specified name
* input(name).check() checks checkbox
* input(name).select(value) selects the radio button with specified name/value
* input(name).val() returns the value of the input.
*/
angular.scenario.dsl('input', function() {
var chain = {};
var supportInputEvent = 'oninput' in document.createElement('div');
chain.enter = function(value, event) {
return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
input.val(value);
input.trigger(event || supportInputEvent && 'input' || 'change');
done();
});
};
chain.check = function() {
return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox');
input.trigger('click');
done();
});
};
chain.select = function(value) {
return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) {
var input = $document.
elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio');
input.trigger('click');
done();
});
};
chain.val = function() {
return this.addFutureAction("return input val", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
done(null,input.val());
});
};
return function(name) {
this.name = name;
return chain;
};
});
/**
* Usage:
* repeater('#products table', 'Product List').count() number of rows
* repeater('#products table', 'Product List').row(1) all bindings in row as an array
* repeater('#products table', 'Product List').column('product.name') all values across all rows in an array
*/
angular.scenario.dsl('repeater', function() {
var chain = {};
chain.count = function() {
return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.column = function(binding) {
return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) {
done(null, $document.elements().bindings($window.angular.element, binding));
});
};
chain.row = function(index) {
return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) {
var matches = $document.elements().slice(index, index + 1);
if (!matches.length)
return done('row ' + index + ' out of bounds');
done(null, matches.bindings($window.angular.element));
});
};
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
/**
* Usage:
* select(name).option('value') select one option
* select(name).options('value1', 'value2', ...) select options from a multi select
*/
angular.scenario.dsl('select', function() {
var chain = {};
chain.option = function(value) {
return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) {
var select = $document.elements('select[ng\\:model="$1"]', this.name);
var option = select.find('option[value="' + value + '"]');
if (option.length) {
select.val(value);
} else {
option = select.find('option:contains("' + value + '")');
if (option.length) {
select.val(option.val());
}
}
select.trigger('change');
done();
});
};
chain.options = function() {
var values = arguments;
return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) {
var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name);
select.val(values);
select.trigger('change');
done();
});
};
return function(name) {
this.name = name;
return chain;
};
});
/**
* Usage:
* element(selector, label).count() get the number of elements that match selector
* element(selector, label).click() clicks an element
* element(selector, label).query(fn) executes fn(selectedElements, done)
* element(selector, label).{method}() gets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr)
* element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr)
*/
angular.scenario.dsl('element', function() {
var KEY_VALUE_METHODS = ['attr', 'css', 'prop'];
var VALUE_METHODS = [
'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width',
'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset'
];
var chain = {};
chain.count = function() {
return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.click = function() {
return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) {
var elements = $document.elements();
var href = elements.attr('href');
var eventProcessDefault = elements.trigger('click')[0];
if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) {
this.application.navigateTo(href, function() {
done();
}, done);
} else {
done();
}
});
};
chain.query = function(fn) {
return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) {
fn.call(this, $document.elements(), done);
});
};
angular.forEach(KEY_VALUE_METHODS, function(methodName) {
chain[methodName] = function(name, value) {
var args = arguments,
futureName = (args.length == 1)
? "element '" + this.label + "' get " + methodName + " '" + name + "'"
: "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
angular.forEach(VALUE_METHODS, function(methodName) {
chain[methodName] = function(value) {
var args = arguments,
futureName = (args.length == 0)
? "element '" + this.label + "' " + methodName
: futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
/**
* Matchers for implementing specs. Follows the Jasmine spec conventions.
*/
angular.scenario.matcher('toEqual', function(expected) {
return angular.equals(this.actual, expected);
});
angular.scenario.matcher('toBe', function(expected) {
return this.actual === expected;
});
angular.scenario.matcher('toBeDefined', function() {
return angular.isDefined(this.actual);
});
angular.scenario.matcher('toBeTruthy', function() {
return this.actual;
});
angular.scenario.matcher('toBeFalsy', function() {
return !this.actual;
});
angular.scenario.matcher('toMatch', function(expected) {
return new RegExp(expected).test(this.actual);
});
angular.scenario.matcher('toBeNull', function() {
return this.actual === null;
});
angular.scenario.matcher('toContain', function(expected) {
return includes(this.actual, expected);
});
angular.scenario.matcher('toBeLessThan', function(expected) {
return this.actual < expected;
});
angular.scenario.matcher('toBeGreaterThan', function(expected) {
return this.actual > expected;
});
/**
* User Interface for the Scenario Runner.
*
* TODO(esprehn): This should be refactored now that ObjectModel exists
* to use angular bindings for the UI.
*/
angular.scenario.output('html', function(context, runner, model) {
var specUiMap = {},
lastStepUiMap = {};
context.append(
'<div id="header">' +
' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' +
' <ul id="status-legend" class="status-display">' +
' <li class="status-error">0 Errors</li>' +
' <li class="status-failure">0 Failures</li>' +
' <li class="status-success">0 Passed</li>' +
' </ul>' +
'</div>' +
'<div id="specs">' +
' <div class="test-children"></div>' +
'</div>'
);
runner.on('InteractivePause', function(spec) {
var ui = lastStepUiMap[spec.id];
ui.find('.test-title').
html('paused... <a href="javascript:resume()">resume</a> when ready.');
});
runner.on('SpecBegin', function(spec) {
var ui = findContext(spec);
ui.find('> .tests').append(
'<li class="status-pending test-it"></li>'
);
ui = ui.find('> .tests li:last');
ui.append(
'<div class="test-info">' +
' <p class="test-title">' +
' <span class="timer-result"></span>' +
' <span class="test-name"></span>' +
' </p>' +
'</div>' +
'<div class="scrollpane">' +
' <ol class="test-actions"></ol>' +
'</div>'
);
ui.find('> .test-info .test-name').text(spec.name);
ui.find('> .test-info').click(function() {
var scrollpane = ui.find('> .scrollpane');
var actions = scrollpane.find('> .test-actions');
var name = context.find('> .test-info .test-name');
if (actions.find(':visible').length) {
actions.hide();
name.removeClass('open').addClass('closed');
} else {
actions.show();
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
name.removeClass('closed').addClass('open');
}
});
specUiMap[spec.id] = ui;
});
runner.on('SpecError', function(spec, error) {
var ui = specUiMap[spec.id];
ui.append('<pre></pre>');
ui.find('> pre').text(formatException(error));
});
runner.on('SpecEnd', function(spec) {
var ui = specUiMap[spec.id];
spec = model.getSpec(spec.id);
ui.removeClass('status-pending');
ui.addClass('status-' + spec.status);
ui.find("> .test-info .timer-result").text(spec.duration + "ms");
if (spec.status === 'success') {
ui.find('> .test-info .test-name').addClass('closed');
ui.find('> .scrollpane .test-actions').hide();
}
updateTotals(spec.status);
});
runner.on('StepBegin', function(spec, step) {
var ui = specUiMap[spec.id];
spec = model.getSpec(spec.id);
step = spec.getLastStep();
ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>');
var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last');
stepUi.append(
'<div class="timer-result"></div>' +
'<div class="test-title"></div>'
);
stepUi.find('> .test-title').text(step.name);
var scrollpane = stepUi.parents('.scrollpane');
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
});
runner.on('StepFailure', function(spec, step, error) {
var ui = lastStepUiMap[spec.id];
addError(ui, step.line, error);
});
runner.on('StepError', function(spec, step, error) {
var ui = lastStepUiMap[spec.id];
addError(ui, step.line, error);
});
runner.on('StepEnd', function(spec, step) {
var stepUi = lastStepUiMap[spec.id];
spec = model.getSpec(spec.id);
step = spec.getLastStep();
stepUi.find('.timer-result').text(step.duration + 'ms');
stepUi.removeClass('status-pending');
stepUi.addClass('status-' + step.status);
var scrollpane = specUiMap[spec.id].find('> .scrollpane');
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
});
/**
* Finds the context of a spec block defined by the passed definition.
*
* @param {Object} The definition created by the Describe object.
*/
function findContext(spec) {
var currentContext = context.find('#specs');
angular.forEach(model.getDefinitionPath(spec), function(defn) {
var id = 'describe-' + defn.id;
if (!context.find('#' + id).length) {
currentContext.find('> .test-children').append(
'<div class="test-describe" id="' + id + '">' +
' <h2></h2>' +
' <div class="test-children"></div>' +
' <ul class="tests"></ul>' +
'</div>'
);
context.find('#' + id).find('> h2').text('describe: ' + defn.name);
}
currentContext = context.find('#' + id);
});
return context.find('#describe-' + spec.definition.id);
}
/**
* Updates the test counter for the status.
*
* @param {string} the status.
*/
function updateTotals(status) {
var legend = context.find('#status-legend .status-' + status);
var parts = legend.text().split(' ');
var value = (parts[0] * 1) + 1;
legend.text(value + ' ' + parts[1]);
}
/**
* Add an error to a step.
*
* @param {Object} The JQuery wrapped context
* @param {function()} fn() that should return the file/line number of the error
* @param {Object} the error.
*/
function addError(context, line, error) {
context.find('.test-title').append('<pre></pre>');
var message = _jQuery.trim(line() + '\n\n' + formatException(error));
context.find('.test-title pre:last').text(message);
}
});
/**
* Generates JSON output into a context.
*/
angular.scenario.output('json', function(context, runner, model) {
model.on('RunnerEnd', function() {
context.text(angular.toJson(model.value));
});
});
/**
* Generates XML output into a context.
*/
angular.scenario.output('xml', function(context, runner, model) {
var $ = function(args) {return new context.init(args);};
model.on('RunnerEnd', function() {
var scenario = $('<scenario></scenario>');
context.append(scenario);
serializeXml(scenario, model.value);
});
/**
* Convert the tree into XML.
*
* @param {Object} context jQuery context to add the XML to.
* @param {Object} tree node to serialize
*/
function serializeXml(context, tree) {
angular.forEach(tree.children, function(child) {
var describeContext = $('<describe></describe>');
describeContext.attr('id', child.id);
describeContext.attr('name', child.name);
context.append(describeContext);
serializeXml(describeContext, child);
});
var its = $('<its></its>');
context.append(its);
angular.forEach(tree.specs, function(spec) {
var it = $('<it></it>');
it.attr('id', spec.id);
it.attr('name', spec.name);
it.attr('duration', spec.duration);
it.attr('status', spec.status);
its.append(it);
angular.forEach(spec.steps, function(step) {
var stepContext = $('<step></step>');
stepContext.attr('name', step.name);
stepContext.attr('duration', step.duration);
stepContext.attr('status', step.status);
it.append(stepContext);
if (step.error) {
var error = $('<error></error>');
stepContext.append(error);
error.text(formatException(stepContext.error));
}
});
});
}
});
/**
* Creates a global value $result with the result of the runner.
*/
angular.scenario.output('object', function(context, runner, model) {
runner.$window.$result = model.value;
});
bindJQuery();
publishExternalAPI(angular);
var $runner = new angular.scenario.Runner(window),
scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1],
config = {};
angular.forEach(script.attributes, function(attr) {
var match = attr.name.match(/ng[:\-](.*)/);
if (match) {
config[match[1]] = attr.value || true;
}
});
if (config.autotest) {
JQLite(document).ready(function() {
angular.scenario.setUpAndRun(config);
});
}
})(window, document);
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>');
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>'); | zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-scenario-1.0.0.js | JavaScript | asf20 | 793,870 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*
* TODO(vojta): wrap whole file into closure during build
*/
/**
* @ngdoc overview
* @name angular.mock
* @description
*
* Namespace from 'angular-mocks.js' which contains testing related code.
*/
angular.mock = {};
/**
* ! This is a private undocumented service !
*
* @name ngMock.$browser
*
* @description
* This service is a mock implementation of {@link ng.$browser}. It provides fake
* implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
* cookies, etc...
*
* The api of this service is the same as that of the real {@link ng.$browser $browser}, except
* that there are several helper methods available which can be used in tests.
*/
angular.mock.$BrowserProvider = function() {
this.$get = function(){
return new angular.mock.$Browser();
};
};
angular.mock.$Browser = function() {
var self = this;
this.isMock = true;
self.$$url = "http://server/";
self.$$lastUrl = self.$$url; // used by url polling fn
self.pollFns = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = angular.noop;
self.$$incOutstandingRequestCount = angular.noop;
// register url polling fn
self.onUrlChange = function(listener) {
self.pollFns.push(
function() {
if (self.$$lastUrl != self.$$url) {
self.$$lastUrl = self.$$url;
listener(self.$$url);
}
}
);
return listener;
};
self.cookieHash = {};
self.lastCookieHash = {};
self.deferredFns = [];
self.deferredNextId = 0;
self.defer = function(fn, delay) {
delay = delay || 0;
self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
self.deferredFns.sort(function(a,b){ return a.time - b.time;});
return self.deferredNextId++;
};
self.defer.now = 0;
self.defer.cancel = function(deferId) {
var fnIndex;
angular.forEach(self.deferredFns, function(fn, index) {
if (fn.id === deferId) fnIndex = index;
});
if (fnIndex !== undefined) {
self.deferredFns.splice(fnIndex, 1);
return true;
}
return false;
};
/**
* @name ngMock.$browser#defer.flush
* @methodOf ngMock.$browser
*
* @description
* Flushes all pending requests and executes the defer callbacks.
*
* @param {number=} number of milliseconds to flush. See {@link #defer.now}
*/
self.defer.flush = function(delay) {
if (angular.isDefined(delay)) {
self.defer.now += delay;
} else {
if (self.deferredFns.length) {
self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
} else {
throw Error('No deferred tasks to be flushed');
}
}
while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
self.deferredFns.shift().fn();
}
};
/**
* @name ngMock.$browser#defer.now
* @propertyOf ngMock.$browser
*
* @description
* Current milliseconds mock time.
*/
self.$$baseHref = '';
self.baseHref = function() {
return this.$$baseHref;
};
};
angular.mock.$Browser.prototype = {
/**
* @name ngMock.$browser#poll
* @methodOf ngMock.$browser
*
* @description
* run all fns in pollFns
*/
poll: function poll() {
angular.forEach(this.pollFns, function(pollFn){
pollFn();
});
},
addPollFn: function(pollFn) {
this.pollFns.push(pollFn);
return pollFn;
},
url: function(url, replace) {
if (url) {
this.$$url = url;
return this;
}
return this.$$url;
},
cookies: function(name, value) {
if (name) {
if (value == undefined) {
delete this.cookieHash[name];
} else {
if (angular.isString(value) && //strings only
value.length <= 4096) { //strict cookie storage limits
this.cookieHash[name] = value;
}
}
} else {
if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
this.lastCookieHash = angular.copy(this.cookieHash);
this.cookieHash = angular.copy(this.cookieHash);
}
return this.cookieHash;
}
},
notifyWhenNoOutstandingRequests: function(fn) {
fn();
}
};
/**
* @ngdoc object
* @name ngMock.$exceptionHandlerProvider
*
* @description
* Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors passed
* into the `$exceptionHandler`.
*/
/**
* @ngdoc object
* @name ngMock.$exceptionHandler
*
* @description
* Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
* into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
* information.
*/
angular.mock.$ExceptionHandlerProvider = function() {
var handler;
/**
* @ngdoc method
* @name ngMock.$exceptionHandlerProvider#mode
* @methodOf ngMock.$exceptionHandlerProvider
*
* @description
* Sets the logging mode.
*
* @param {string} mode Mode of operation, defaults to `rethrow`.
*
* - `rethrow`: If any errors are are passed into the handler in tests, it typically
* means that there is a bug in the application or test, so this mock will
* make these tests fail.
* - `log`: Sometimes it is desirable to test that an error is throw, for this case the `log` mode stores the
* error and allows later assertion of it.
* See {@link ngMock.$log#assertEmpty assertEmpty()} and
* {@link ngMock.$log#reset reset()}
*/
this.mode = function(mode) {
switch(mode) {
case 'rethrow':
handler = function(e) {
throw e;
};
break;
case 'log':
var errors = [];
handler = function(e) {
if (arguments.length == 1) {
errors.push(e);
} else {
errors.push([].slice.call(arguments, 0));
}
};
handler.errors = errors;
break;
default:
throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
}
};
this.$get = function() {
return handler;
};
this.mode('rethrow');
};
/**
* @ngdoc service
* @name ngMock.$log
*
* @description
* Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
* (one array per logging level). These arrays are exposed as `logs` property of each of the
* level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
*
*/
angular.mock.$LogProvider = function() {
function concat(array1, array2, index) {
return array1.concat(Array.prototype.slice.call(array2, index));
}
this.$get = function () {
var $log = {
log: function() { $log.log.logs.push(concat([], arguments, 0)); },
warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
info: function() { $log.info.logs.push(concat([], arguments, 0)); },
error: function() { $log.error.logs.push(concat([], arguments, 0)); }
};
/**
* @ngdoc method
* @name ngMock.$log#reset
* @methodOf ngMock.$log
*
* @description
* Reset all of the logging arrays to empty.
*/
$log.reset = function () {
/**
* @ngdoc property
* @name ngMock.$log#log.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.log.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#warn.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.warn.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#info.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.info.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#error.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.error.logs = [];
};
/**
* @ngdoc method
* @name ngMock.$log#assertEmpty
* @methodOf ngMock.$log
*
* @description
* Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
*/
$log.assertEmpty = function() {
var errors = [];
angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
angular.forEach($log[logLevel].logs, function(log) {
angular.forEach(log, function (logItem) {
errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
});
});
});
if (errors.length) {
errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
"log message was not checked and removed:");
errors.push('');
throw new Error(errors.join('\n---------\n'));
}
};
$log.reset();
return $log;
};
};
(function() {
var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8061_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
function int(str) {
return parseInt(str, 10);
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
/**
* @ngdoc object
* @name angular.mock.TzDate
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
*
* Mock of the Date type which has its timezone specified via constroctor arg.
*
* The main purpose is to create Date-like instances with timezone fixed to the specified timezone
* offset, so that we can test code that depends on local timezone settings without dependency on
* the time zone settings of the machine where the code is running.
*
* @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
* @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
*
* @example
* !!!! WARNING !!!!!
* This is not a complete Date object so only methods that were implemented can be called safely.
* To make matters worse, TzDate instances inherit stuff from Date via a prototype.
*
* We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
* incomplete we might be missing some non-standard methods. This can result in errors like:
* "Date.prototype.foo called on incompatible Object".
*
* <pre>
* var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
* newYearInBratislava.getTimezoneOffset() => -60;
* newYearInBratislava.getFullYear() => 2010;
* newYearInBratislava.getMonth() => 0;
* newYearInBratislava.getDate() => 1;
* newYearInBratislava.getHours() => 0;
* newYearInBratislava.getMinutes() => 0;
* </pre>
*
*/
angular.mock.TzDate = function (offset, timestamp) {
var self = new Date(0);
if (angular.isString(timestamp)) {
var tsStr = timestamp;
self.origDate = jsonStringToDate(timestamp);
timestamp = self.origDate.getTime();
if (isNaN(timestamp))
throw {
name: "Illegal Argument",
message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
};
} else {
self.origDate = new Date(timestamp);
}
var localOffset = new Date(timestamp).getTimezoneOffset();
self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
self.date = new Date(timestamp + self.offsetDiff);
self.getTime = function() {
return self.date.getTime() - self.offsetDiff;
};
self.toLocaleDateString = function() {
return self.date.toLocaleDateString();
};
self.getFullYear = function() {
return self.date.getFullYear();
};
self.getMonth = function() {
return self.date.getMonth();
};
self.getDate = function() {
return self.date.getDate();
};
self.getHours = function() {
return self.date.getHours();
};
self.getMinutes = function() {
return self.date.getMinutes();
};
self.getSeconds = function() {
return self.date.getSeconds();
};
self.getTimezoneOffset = function() {
return offset * 60;
};
self.getUTCFullYear = function() {
return self.origDate.getUTCFullYear();
};
self.getUTCMonth = function() {
return self.origDate.getUTCMonth();
};
self.getUTCDate = function() {
return self.origDate.getUTCDate();
};
self.getUTCHours = function() {
return self.origDate.getUTCHours();
};
self.getUTCMinutes = function() {
return self.origDate.getUTCMinutes();
};
self.getUTCSeconds = function() {
return self.origDate.getUTCSeconds();
};
self.getUTCMilliseconds = function() {
return self.origDate.getUTCMilliseconds();
};
self.getDay = function() {
return self.date.getDay();
};
// provide this method only on browsers that already have it
if (self.toISOString) {
self.toISOString = function() {
return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
padNumber(self.origDate.getUTCDate(), 2) + 'T' +
padNumber(self.origDate.getUTCHours(), 2) + ':' +
padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'
}
}
//hide all methods not implemented in this mock that the Date prototype exposes
var unimplementedMethods = ['getMilliseconds', 'getUTCDay',
'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
angular.forEach(unimplementedMethods, function(methodName) {
self[methodName] = function() {
throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
};
});
return self;
};
//make "tzDateInstance instanceof Date" return true
angular.mock.TzDate.prototype = Date.prototype;
})();
/**
* @ngdoc function
* @name angular.mock.debug
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available function.
*
* Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
*
* This method is also available on window, where it can be used to display objects on debug console.
*
* @param {*} object - any object to turn into string.
* @return {string} a serialized string of the argument
*/
angular.mock.dump = function(object) {
return serialize(object);
function serialize(object) {
var out;
if (angular.isElement(object)) {
object = angular.element(object);
out = angular.element('<div></div>');
angular.forEach(object, function(element) {
out.append(angular.element(element).clone());
});
out = out.html();
} else if (angular.isArray(object)) {
out = [];
angular.forEach(object, function(o) {
out.push(serialize(o));
});
out = '[ ' + out.join(', ') + ' ]';
} else if (angular.isObject(object)) {
if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
out = serializeScope(object);
} else if (object instanceof Error) {
out = object.stack || ('' + object.name + ': ' + object.message);
} else {
out = angular.toJson(object, true);
}
} else {
out = String(object);
}
return out;
}
function serializeScope(scope, offset) {
offset = offset || ' ';
var log = [offset + 'Scope(' + scope.$id + '): {'];
for ( var key in scope ) {
if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) {
log.push(' ' + key + ': ' + angular.toJson(scope[key]));
}
}
var child = scope.$$childHead;
while(child) {
log.push(serializeScope(child, offset + ' '));
child = child.$$nextSibling;
}
log.push('}');
return log.join('\n' + offset);
}
};
/**
* @ngdoc object
* @name ngMock.$httpBackend
* @description
* Fake HTTP backend implementation suitable for unit testing application that use the
* {@link ng.$http $http service}.
*
* *Note*: For fake http backend implementation suitable for end-to-end testing or backend-less
* development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
*
* During unit testing, we want our unit tests to run quickly and have no external dependencies so
* we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or
* {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is
* to verify whether a certain request has been sent or not, or alternatively just let the
* application make requests, respond with pre-trained responses and assert that the end result is
* what we expect it to be.
*
* This mock implementation can be used to respond with static or dynamic responses via the
* `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
*
* When an Angular application needs some data from a server, it calls the $http service, which
* sends the request to a real server using $httpBackend service. With dependency injection, it is
* easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
* the requests and respond with some testing data without sending a request to real server.
*
* There are two ways to specify what test data should be returned as http responses by the mock
* backend when the code under test makes http requests:
*
* - `$httpBackend.expect` - specifies a request expectation
* - `$httpBackend.when` - specifies a backend definition
*
*
* # Request Expectations vs Backend Definitions
*
* Request expectations provide a way to make assertions about requests made by the application and
* to define responses for those requests. The test will fail if the expected requests are not made
* or they are made in the wrong order.
*
* Backend definitions allow you to define a fake backend for your application which doesn't assert
* if a particular request was made or not, it just returns a trained response if a request is made.
* The test will pass whether or not the request gets made during testing.
*
*
* <table class="table">
* <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
* <tr>
* <th>Syntax</th>
* <td>.expect(...).respond(...)</td>
* <td>.when(...).respond(...)</td>
* </tr>
* <tr>
* <th>Typical usage</th>
* <td>strict unit tests</td>
* <td>loose (black-box) unit testing</td>
* </tr>
* <tr>
* <th>Fulfills multiple requests</th>
* <td>NO</td>
* <td>YES</td>
* </tr>
* <tr>
* <th>Order of requests matters</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Request required</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Response required</th>
* <td>optional (see below)</td>
* <td>YES</td>
* </tr>
* </table>
*
* In cases where both backend definitions and request expectations are specified during unit
* testing, the request expectations are evaluated first.
*
* If a request expectation has no response specified, the algorithm will search your backend
* definitions for an appropriate response.
*
* If a request didn't match any expectation or if the expectation doesn't have the response
* defined, the backend definitions are evaluated in sequential order to see if any of them match
* the request. The response from the first matched definition is returned.
*
*
* # Flushing HTTP requests
*
* The $httpBackend used in production, always responds to requests with responses asynchronously.
* If we preserved this behavior in unit testing, we'd have to create async unit tests, which are
* hard to write, follow and maintain. At the same time the testing mock, can't respond
* synchronously because that would change the execution of the code under test. For this reason the
* mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending
* requests and thus preserving the async api of the backend, while allowing the test to execute
* synchronously.
*
*
* # Unit testing with mock $httpBackend
*
* <pre>
// controller
function MyController($scope, $http) {
$http.get('/auth.py').success(function(data) {
$scope.user = data;
});
this.saveMessage = function(message) {
$scope.status = 'Saving...';
$http.post('/add-msg.py', message).success(function(response) {
$scope.status = '';
}).error(function() {
$scope.status = 'ERROR!';
});
};
}
// testing controller
var $http;
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
$httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch authentication token', function() {
$httpBackend.expectGET('/auth.py');
var controller = scope.$new(MyController);
$httpBackend.flush();
});
it('should send msg to server', function() {
// now you don’t care about the authentication, but
// the controller will still send the request and
// $httpBackend will respond without you having to
// specify the expectation and response for this request
$httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
var controller = scope.$new(MyController);
$httpBackend.flush();
controller.saveMessage('message content');
expect(controller.status).toBe('Saving...');
$httpBackend.flush();
expect(controller.status).toBe('');
});
it('should send auth header', function() {
$httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
// check if the header was send, if it wasn't the expectation won't
// match the request and the test will fail
return headers['Authorization'] == 'xxx';
}).respond(201, '');
var controller = scope.$new(MyController);
controller.saveMessage('whatever');
$httpBackend.flush();
});
</pre>
*/
angular.mock.$HttpBackendProvider = function() {
this.$get = [createHttpBackendMock];
};
/**
* General factory function for $httpBackend mock.
* Returns instance for unit testing (when no arguments specified):
* - passing through is disabled
* - auto flushing is disabled
*
* Returns instance for e2e testing (when `$delegate` and `$browser` specified):
* - passing through (delegating request to real backend) is enabled
* - auto flushing is enabled
*
* @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
* @param {Object=} $browser Auto-flushing enabled if specified
* @return {Object} Instance of $httpBackend mock
*/
function createHttpBackendMock($delegate, $browser) {
var definitions = [],
expectations = [],
responses = [],
responsesPush = angular.bind(responses, responses.push);
function createResponse(status, data, headers) {
if (angular.isFunction(status)) return status;
return function() {
return angular.isNumber(status)
? [status, data, headers]
: [200, status, data];
};
}
// TODO(vojta): change params to: method, url, data, headers, callback
function $httpBackend(method, url, data, callback, headers) {
var xhr = new MockXhr(),
expectation = expectations[0],
wasExpected = false;
function prettyPrint(data) {
return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
? data
: angular.toJson(data);
}
if (expectation && expectation.match(method, url)) {
if (!expectation.matchData(data))
throw Error('Expected ' + expectation + ' with different data\n' +
'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
if (!expectation.matchHeaders(headers))
throw Error('Expected ' + expectation + ' with different headers\n' +
'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
prettyPrint(headers));
expectations.shift();
if (expectation.response) {
responses.push(function() {
var response = expectation.response(method, url, data, headers);
xhr.$$respHeaders = response[2];
callback(response[0], response[1], xhr.getAllResponseHeaders());
});
return;
}
wasExpected = true;
}
var i = -1, definition;
while ((definition = definitions[++i])) {
if (definition.match(method, url, data, headers || {})) {
if (definition.response) {
// if $browser specified, we do auto flush all requests
($browser ? $browser.defer : responsesPush)(function() {
var response = definition.response(method, url, data, headers);
xhr.$$respHeaders = response[2];
callback(response[0], response[1], xhr.getAllResponseHeaders());
});
} else if (definition.passThrough) {
$delegate(method, url, data, callback, headers);
} else throw Error('No response defined !');
return;
}
}
throw wasExpected ?
Error('No response defined !') :
Error('Unexpected request: ' + method + ' ' + url + '\n' +
(expectation ? 'Expected ' + expectation : 'No more request expected'));
}
/**
* @ngdoc method
* @name ngMock.$httpBackend#when
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
*/
$httpBackend.when = function(method, url, data, headers) {
var definition = new MockHttpExpectation(method, url, data, headers),
chain = {
respond: function(status, data, headers) {
definition.response = createResponse(status, data, headers);
}
};
if ($browser) {
chain.passThrough = function() {
definition.passThrough = true;
};
}
definitions.push(definition);
return chain;
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenGET
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenHEAD
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenDELETE
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenPOST
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenPUT
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenJSONP
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
createShortMethods('when');
/**
* @ngdoc method
* @name ngMock.$httpBackend#expect
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current expectation.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
*/
$httpBackend.expect = function(method, url, data, headers) {
var expectation = new MockHttpExpectation(method, url, data, headers);
expectations.push(expectation);
return {
respond: function(status, data, headers) {
expectation.response = createResponse(status, data, headers);
}
};
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectGET
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for GET requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. See #expect for more info.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectHEAD
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for HEAD requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectDELETE
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for DELETE requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPOST
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for POST requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPUT
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for PUT requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPATCH
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for PATCH requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectJSONP
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for JSONP requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
createShortMethods('expect');
/**
* @ngdoc method
* @name ngMock.$httpBackend#flush
* @methodOf ngMock.$httpBackend
* @description
* Flushes all pending requests using the trained responses.
*
* @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
* all pending requests will be flushed. If there are no pending requests when the flush method
* is called an exception is thrown (as this typically a sign of programming error).
*/
$httpBackend.flush = function(count) {
if (!responses.length) throw Error('No pending request to flush !');
if (angular.isDefined(count)) {
while (count--) {
if (!responses.length) throw Error('No more pending request to flush !');
responses.shift()();
}
} else {
while (responses.length) {
responses.shift()();
}
}
$httpBackend.verifyNoOutstandingExpectation();
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#verifyNoOutstandingExpectation
* @methodOf ngMock.$httpBackend
* @description
* Verifies that all of the requests defined via the `expect` api were made. If any of the
* requests were not made, verifyNoOutstandingExpectation throws an exception.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* <pre>
* afterEach($httpBackend.verifyExpectations);
* </pre>
*/
$httpBackend.verifyNoOutstandingExpectation = function() {
if (expectations.length) {
throw Error('Unsatisfied requests: ' + expectations.join(', '));
}
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#verifyNoOutstandingRequest
* @methodOf ngMock.$httpBackend
* @description
* Verifies that there are no outstanding requests that need to be flushed.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* <pre>
* afterEach($httpBackend.verifyNoOutstandingRequest);
* </pre>
*/
$httpBackend.verifyNoOutstandingRequest = function() {
if (responses.length) {
throw Error('Unflushed requests: ' + responses.length);
}
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#resetExpectations
* @methodOf ngMock.$httpBackend
* @description
* Resets all request expectations, but preserves all backend definitions. Typically, you would
* call resetExpectations during a multiple-phase test when you want to reuse the same instance of
* $httpBackend mock.
*/
$httpBackend.resetExpectations = function() {
expectations.length = 0;
responses.length = 0;
};
return $httpBackend;
function createShortMethods(prefix) {
angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
$httpBackend[prefix + method] = function(url, headers) {
return $httpBackend[prefix](method, url, undefined, headers)
}
});
angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
$httpBackend[prefix + method] = function(url, data, headers) {
return $httpBackend[prefix](method, url, data, headers)
}
});
}
}
function MockHttpExpectation(method, url, data, headers) {
this.data = data;
this.headers = headers;
this.match = function(m, u, d, h) {
if (method != m) return false;
if (!this.matchUrl(u)) return false;
if (angular.isDefined(d) && !this.matchData(d)) return false;
if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
return true;
};
this.matchUrl = function(u) {
if (!url) return true;
if (angular.isFunction(url.test)) return url.test(u);
return url == u;
};
this.matchHeaders = function(h) {
if (angular.isUndefined(headers)) return true;
if (angular.isFunction(headers)) return headers(h);
return angular.equals(headers, h);
};
this.matchData = function(d) {
if (angular.isUndefined(data)) return true;
if (data && angular.isFunction(data.test)) return data.test(d);
if (data && !angular.isString(data)) return angular.toJson(data) == d;
return data == d;
};
this.toString = function() {
return method + ' ' + url;
};
}
function MockXhr() {
// hack for testing $http, $httpBackend
MockXhr.$$lastInstance = this;
this.open = function(method, url, async) {
this.$$method = method;
this.$$url = url;
this.$$async = async;
this.$$reqHeaders = {};
this.$$respHeaders = {};
};
this.send = function(data) {
this.$$data = data;
};
this.setRequestHeader = function(key, value) {
this.$$reqHeaders[key] = value;
};
this.getResponseHeader = function(name) {
// the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
var header = this.$$respHeaders[name];
if (header) return header;
name = angular.lowercase(name);
header = this.$$respHeaders[name];
if (header) return header;
header = undefined;
angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
if (!header && angular.lowercase(headerName) == name) header = headerVal;
});
return header;
};
this.getAllResponseHeaders = function() {
var lines = [];
angular.forEach(this.$$respHeaders, function(value, key) {
lines.push(key + ': ' + value);
});
return lines.join('\n');
};
this.abort = angular.noop;
}
/**
* @ngdoc function
* @name ngMock.$timeout
* @description
*
* This service is just a simple decorator for {@link ng.$timeout $timeout} service
* that adds a "flush" method.
*/
/**
* @ngdoc method
* @name ngMock.$timeout#flush
* @methodOf ngMock.$timeout
* @description
*
* Flushes the queue of pending tasks.
*/
/**
*
*/
angular.mock.$RootElementProvider = function() {
this.$get = function() {
return angular.element('<div ng-app></div>');
}
};
/**
* @ngdoc overview
* @name ngMock
* @description
*
* The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful
* mocks to the {@link AUTO.$injector $injector}.
*/
angular.module('ngMock', ['ng']).provider({
$browser: angular.mock.$BrowserProvider,
$exceptionHandler: angular.mock.$ExceptionHandlerProvider,
$log: angular.mock.$LogProvider,
$httpBackend: angular.mock.$HttpBackendProvider,
$rootElement: angular.mock.$RootElementProvider
}).config(function($provide) {
$provide.decorator('$timeout', function($delegate, $browser) {
$delegate.flush = function() {
$browser.defer.flush();
};
return $delegate;
});
});
/**
* @ngdoc overview
* @name ngMockE2E
* @description
*
* The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
* Currently there is only one mock present in this module -
* the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
*/
angular.module('ngMockE2E', ['ng']).config(function($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
});
/**
* @ngdoc object
* @name ngMockE2E.$httpBackend
* @description
* Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
* applications that use the {@link ng.$http $http service}.
*
* *Note*: For fake http backend implementation suitable for unit testing please see
* {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
*
* This implementation can be used to respond with static or dynamic responses via the `when` api
* and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
* real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
* templates from a webserver).
*
* As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
* is being developed with the real backend api replaced with a mock, it is often desirable for
* certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
* templates or static files from the webserver). To configure the backend with this behavior
* use the `passThrough` request handler of `when` instead of `respond`.
*
* Additionally, we don't want to manually have to flush mocked out requests like we do during unit
* testing. For this reason the e2e $httpBackend automatically flushes mocked out requests
* automatically, closely simulating the behavior of the XMLHttpRequest object.
*
* To setup the application to run with this http backend, you have to create a module that depends
* on the `ngMockE2E` and your application modules and defines the fake backend:
*
* <pre>
* myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
* myAppDev.run(function($httpBackend) {
* phones = [{name: 'phone1'}, {name: 'phone2'}];
*
* // returns the current list of phones
* $httpBackend.whenGET('/phones').respond(phones);
*
* // adds a new phone to the phones array
* $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
* phones.push(angular.fromJSON(data));
* });
* $httpBackend.whenGET(/^\/templates\//).passThrough();
* //...
* });
* </pre>
*
* Afterwards, bootstrap your app with this new module.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#when
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
* - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
* handler, will be pass through to the real backend (an XHR request will be made to the
* server.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenGET
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenHEAD
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenDELETE
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPOST
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPUT
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPATCH
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for PATCH requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenJSONP
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
angular.mock.e2e = {};
angular.mock.e2e.$httpBackendDecorator = ['$delegate', '$browser', createHttpBackendMock];
angular.mock.clearDataCache = function() {
var key,
cache = angular.element.cache;
for(key in cache) {
if (cache.hasOwnProperty(key)) {
var handle = cache[key].handle;
handle && angular.element(handle.elem).unbind();
delete cache[key];
}
}
};
window.jstestdriver && (function(window) {
/**
* Global method to output any number of objects into JSTD console. Useful for debugging.
*/
window.dump = function() {
var args = [];
angular.forEach(arguments, function(arg) {
args.push(angular.mock.dump(arg));
});
jstestdriver.console.log.apply(jstestdriver.console, args);
if (window.console) {
window.console.log.apply(window.console, args);
}
};
})(window);
window.jasmine && (function(window) {
afterEach(function() {
var spec = getCurrentSpec();
spec.$injector = null;
spec.$modules = null;
angular.mock.clearDataCache();
});
function getCurrentSpec() {
return jasmine.getEnv().currentSpec;
}
function isSpecRunning() {
var spec = getCurrentSpec();
return spec && spec.queue.running;
}
/**
* @ngdoc function
* @name angular.mock.module
* @description
*
* *NOTE*: This is function is also published on window for easy access.<br>
* *NOTE*: Only available with {@link http://pivotal.github.com/jasmine/ jasmine}.
*
* This function registers a module configuration code. It collects the configuration information
* which will be used when the injector is created by {@link angular.mock.inject inject}.
*
* See {@link angular.mock.inject inject} for usage example
*
* @param {...(string|Function)} fns any number of modules which are represented as string
* aliases or as anonymous module initialization functions. The modules are used to
* configure the injector. The 'ng' and 'ngMock' modules are automatically loaded.
*/
window.module = angular.mock.module = function() {
var moduleFns = Array.prototype.slice.call(arguments, 0);
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
var spec = getCurrentSpec();
if (spec.$injector) {
throw Error('Injector already created, can not register a module!');
} else {
var modules = spec.$modules || (spec.$modules = []);
angular.forEach(moduleFns, function(module) {
modules.push(module);
});
}
}
};
/**
* @ngdoc function
* @name angular.mock.inject
* @description
*
* *NOTE*: This is function is also published on window for easy access.<br>
* *NOTE*: Only available with {@link http://pivotal.github.com/jasmine/ jasmine}.
*
* The inject function wraps a function into an injectable function. The inject() creates new
* instance of {@link AUTO.$injector $injector} per test, which is then used for
* resolving references.
*
* See also {@link angular.mock.module module}
*
* Example of what a typical jasmine tests looks like with the inject method.
* <pre>
*
* angular.module('myApplicationModule', [])
* .value('mode', 'app')
* .value('version', 'v1.0.1');
*
*
* describe('MyApp', function() {
*
* // You need to load modules that you want to test,
* // it loads only the "ng" module by default.
* beforeEach(module('myApplicationModule'));
*
*
* // inject() is used to inject arguments of all given functions
* it('should provide a version', inject(function(mode, version) {
* expect(version).toEqual('v1.0.1');
* expect(mode).toEqual('app');
* }));
*
*
* // The inject and module method can also be used inside of the it or beforeEach
* it('should override a version and test the new version is injected', function() {
* // module() takes functions or strings (module aliases)
* module(function($provide) {
* $provide.value('version', 'overridden'); // override version here
* });
*
* inject(function(version) {
* expect(version).toEqual('overridden');
* });
* ));
* });
*
* </pre>
*
* @param {...Function} fns any number of functions which will be injected using the injector.
*/
window.inject = angular.mock.inject = function() {
var blockFns = Array.prototype.slice.call(arguments, 0);
var stack = new Error('Declaration Location').stack;
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
var spec = getCurrentSpec();
var modules = spec.$modules || [];
modules.unshift('ngMock');
modules.unshift('ng');
var injector = spec.$injector;
if (!injector) {
injector = spec.$injector = angular.injector(modules);
}
for(var i = 0, ii = blockFns.length; i < ii; i++) {
try {
injector.invoke(blockFns[i] || angular.noop, this);
} catch (e) {
if(e.stack) e.stack += '\n' + stack;
throw e;
}
}
}
}
})(window);
| zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-mocks-1.0.0.js | JavaScript | asf20 | 54,707 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngSanitize
* @description
*/
/*
* HTML Parser By Misko Hevery (misko@hevery.com)
* based on: HTML Parser By John Resig (ejohn.org)
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* // Use like so:
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
*/
/**
* @ngdoc service
* @name ngSanitize.$sanitize
* @function
*
* @description
* The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are
* then serialized back to properly escaped html string. This means that no unsafe input can make
* it into the returned string, however, since our parser is more strict than a typical browser
* parser, it's possible that some obscure input, which would be recognized as valid HTML by a
* browser, won't make it through the sanitizer.
*
* @param {string} html Html input.
* @returns {string} Sanitized html.
*
* @example
<doc:example module="ngSanitize">
<doc:source>
<script>
function Ctrl($scope) {
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
}
</script>
<div ng-controller="Ctrl">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Filter</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="html-filter">
<td>html filter</td>
<td>
<pre><div ng-bind-html="snippet"><br/></div></pre>
</td>
<td>
<div ng-bind-html="snippet"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br/></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
<tr id="html-unsafe-filter">
<td>unsafe html filter</td>
<td><pre><div ng-bind-html-unsafe="snippet"><br/></div></pre></td>
<td><div ng-bind-html-unsafe="snippet"></div></td>
</tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should sanitize the html snippet ', function() {
expect(using('#html-filter').element('div').html()).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
});
it('should escape snippet without any filter', function() {
expect(using('#escaped-html').element('div').html()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should inline raw snippet if filtered as unsafe', function() {
expect(using('#html-unsafe-filter').element("div").html()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
input('snippet').enter('new <b>text</b>');
expect(using('#html-filter').binding('snippet')).toBe('new <b>text</b>');
expect(using('#escaped-html').element('div').html()).toBe("new <b>text</b>");
expect(using('#html-unsafe-filter').binding("snippet")).toBe('new <b>text</b>');
});
</doc:scenario>
</doc:example>
*/
var $sanitize = function(html) {
var buf = [];
htmlParser(html, htmlSanitizeWriter(buf));
return buf.join('');
};
// Regular Expressions for parsing tags and attributes
var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,
END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/,
ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
BEGIN_TAG_REGEXP = /^</,
BEGING_END_TAGE_REGEXP = /^<\s*\//,
COMMENT_REGEXP = /<!--(.*?)-->/g,
CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/,
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character)
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var voidElements = makeMap("area,br,col,hr,img,wbr");
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
optionalEndTagInlineElements = makeMap("rp,rt"),
optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements);
// Safe Block Elements - HTML5
var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," +
"blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," +
"header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
// Inline Elements - HTML5
var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," +
"big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," +
"span,strike,strong,sub,sup,time,tt,u,var"));
// Special Elements (can contain anything)
var specialElements = makeMap("script,style");
var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements);
//Attributes that have href and hence need to be sanitized
var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap");
var validAttrs = angular.extend({}, uriAttrs, makeMap(
'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
'scope,scrolling,shape,span,start,summary,target,title,type,'+
'valign,value,vspace,width'));
function makeMap(str) {
var obj = {}, items = str.split(','), i;
for (i = 0; i < items.length; i++) obj[items[i]] = true;
return obj;
}
/**
* @example
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* @param {string} html string
* @param {object} handler
*/
function htmlParser( html, handler ) {
var index, chars, match, stack = [], last = html;
stack.last = function() { return stack[ stack.length - 1 ]; };
while ( html ) {
chars = true;
// Make sure we're not in a script or style element
if ( !stack.last() || !specialElements[ stack.last() ] ) {
// Comment
if ( html.indexOf("<!--") === 0 ) {
index = html.indexOf("-->");
if ( index >= 0 ) {
if (handler.comment) handler.comment( html.substring( 4, index ) );
html = html.substring( index + 3 );
chars = false;
}
// end tag
} else if ( BEGING_END_TAGE_REGEXP.test(html) ) {
match = html.match( END_TAG_REGEXP );
if ( match ) {
html = html.substring( match[0].length );
match[0].replace( END_TAG_REGEXP, parseEndTag );
chars = false;
}
// start tag
} else if ( BEGIN_TAG_REGEXP.test(html) ) {
match = html.match( START_TAG_REGEXP );
if ( match ) {
html = html.substring( match[0].length );
match[0].replace( START_TAG_REGEXP, parseStartTag );
chars = false;
}
}
if ( chars ) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring( 0, index );
html = index < 0 ? "" : html.substring( index );
if (handler.chars) handler.chars( decodeEntities(text) );
}
} else {
html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){
text = text.
replace(COMMENT_REGEXP, "$1").
replace(CDATA_REGEXP, "$1");
if (handler.chars) handler.chars( decodeEntities(text) );
return "";
});
parseEndTag( "", stack.last() );
}
if ( html == last ) {
throw "Parse Error: " + html;
}
last = html;
}
// Clean up any remaining tags
parseEndTag();
function parseStartTag( tag, tagName, rest, unary ) {
tagName = angular.lowercase(tagName);
if ( blockElements[ tagName ] ) {
while ( stack.last() && inlineElements[ stack.last() ] ) {
parseEndTag( "", stack.last() );
}
}
if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) {
parseEndTag( "", tagName );
}
unary = voidElements[ tagName ] || !!unary;
if ( !unary )
stack.push( tagName );
var attrs = {};
rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) {
var value = doubleQuotedValue
|| singleQoutedValue
|| unqoutedValue
|| '';
attrs[name] = decodeEntities(value);
});
if (handler.start) handler.start( tagName, attrs, unary );
}
function parseEndTag( tag, tagName ) {
var pos = 0, i;
tagName = angular.lowercase(tagName);
if ( tagName )
// Find the closest opened tag of the same type
for ( pos = stack.length - 1; pos >= 0; pos-- )
if ( stack[ pos ] == tagName )
break;
if ( pos >= 0 ) {
// Close all the open elements, up the stack
for ( i = stack.length - 1; i >= pos; i-- )
if (handler.end) handler.end( stack[ i ] );
// Remove the open elements from the stack
stack.length = pos;
}
}
}
/**
* decodes all entities into regular string
* @param value
* @returns {string} A string with decoded entities.
*/
var hiddenPre=document.createElement("pre");
function decodeEntities(value) {
hiddenPre.innerHTML=value.replace(/</g,"<");
return hiddenPre.innerText || hiddenPre.textContent || '';
}
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns escaped text
*/
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(NON_ALPHANUMERIC_REGEXP, function(value){
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
/**
* create an HTML/XML writer which writes to buffer
* @param {Array} buf use buf.jain('') to get out sanitized html string
* @returns {object} in the form of {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* }
*/
function htmlSanitizeWriter(buf){
var ignore = false;
var out = angular.bind(buf, buf.push);
return {
start: function(tag, attrs, unary){
tag = angular.lowercase(tag);
if (!ignore && specialElements[tag]) {
ignore = tag;
}
if (!ignore && validElements[tag] == true) {
out('<');
out(tag);
angular.forEach(attrs, function(value, key){
var lkey=angular.lowercase(key);
if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out(unary ? '/>' : '>');
}
},
end: function(tag){
tag = angular.lowercase(tag);
if (!ignore && validElements[tag] == true) {
out('</');
out(tag);
out('>');
}
if (tag == ignore) {
ignore = false;
}
},
chars: function(chars){
if (!ignore) {
out(encodeEntities(chars));
}
}
};
}
// define ngSanitize module and register $sanitize service
angular.module('ngSanitize', []).value('$sanitize', $sanitize);
/**
* @ngdoc directive
* @name ngSanitize.directive:ngBindHtml
*
* @description
* Creates a binding that will sanitize the result of evaluating the `expression` with the
* {@link ngSanitize.$sanitize $sanitize} service and innerHTML the result into the current element.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*/
angular.module('ngSanitize').directive('ngBindHtml', ['$sanitize', function($sanitize) {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
scope.$watch(attr.ngBindHtml, function(value) {
value = $sanitize(value);
element.html(value || '');
});
};
}]);
/**
* @ngdoc filter
* @name ngSanitize.filter:linky
* @function
*
* @description
* Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
* plain email address links.
*
* @param {string} text Input text.
* @returns {string} Html-linkified text.
*
* @example
<doc:example module="ngSanitize">
<doc:source>
<script>
function Ctrl($scope) {
$scope.snippet =
'Pretty text with some links:\n'+
'http://angularjs.org/,\n'+
'mailto:us@somewhere.org,\n'+
'another@somewhere.org,\n'+
'and one more: ftp://127.0.0.1/.';
}
</script>
<div ng-controller="Ctrl">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Filter</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="linky-filter">
<td>linky filter</td>
<td>
<pre><div ng-bind-html="snippet | linky"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippet | linky"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should linkify the snippet with urls', function() {
expect(using('#linky-filter').binding('snippet | linky')).
toBe('Pretty text with some links: ' +
'<a href="http://angularjs.org/">http://angularjs.org/</a>, ' +
'<a href="mailto:us@somewhere.org">us@somewhere.org</a>, ' +
'<a href="mailto:another@somewhere.org">another@somewhere.org</a>, ' +
'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.');
});
it ('should not linkify snippet without the linky filter', function() {
expect(using('#escaped-html').binding('snippet')).
toBe("Pretty text with some links:\n" +
"http://angularjs.org/,\n" +
"mailto:us@somewhere.org,\n" +
"another@somewhere.org,\n" +
"and one more: ftp://127.0.0.1/.");
});
it('should update', function() {
input('snippet').enter('new http://link.');
expect(using('#linky-filter').binding('snippet | linky')).
toBe('new <a href="http://link">http://link</a>.');
expect(using('#escaped-html').binding('snippet')).toBe('new http://link.');
});
</doc:scenario>
</doc:example>
*/
angular.module('ngSanitize').filter('linky', function() {
var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/,
MAILTO_REGEXP = /^mailto:/;
return function(text) {
if (!text) return text;
var match;
var raw = text;
var html = [];
// TODO(vojta): use $sanitize instead
var writer = htmlSanitizeWriter(html);
var url;
var i;
while ((match = raw.match(LINKY_URL_REGEXP))) {
// We can not end in these as they are sometimes found at the end of the sentence
url = match[0];
// if we did not match ftp/http/mailto then assume mailto
if (match[2] == match[3]) url = 'mailto:' + url;
i = match.index;
writer.chars(raw.substr(0, i));
writer.start('a', {href:url});
writer.chars(match[0].replace(MAILTO_REGEXP, ''));
writer.end('a');
raw = raw.substring(i + match[0].length);
}
writer.chars(raw);
return html.join('');
};
});
})(window, window.angular);
| zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-sanitize-1.0.0.js | JavaScript | asf20 | 17,350 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configure information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
'use strict';
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Option configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider.directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which needs to be performed when the injector with
* with the current module is finished loading.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
}
}
});
};
});
}
)(window);
/**
* Closure compiler type information
*
* @typedef { {
* requires: !Array.<string>,
* invokeQueue: !Array.<Array.<*>>,
*
* service: function(string, Function):angular.Module,
* factory: function(string, Function):angular.Module,
* value: function(string, *):angular.Module,
*
* filter: function(string, Function):angular.Module,
*
* init: function(Function):angular.Module
* } }
*/
angular.Module;
| zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-loader-1.0.0.js | JavaScript | asf20 | 9,113 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window) {
'use strict';
/**
* JSTestDriver adapter for angular scenario tests
*
* Example of jsTestDriver.conf for running scenario tests with JSTD:
<pre>
server: http://localhost:9877
load:
- lib/angular-scenario.js
- lib/jstd-scenario-adapter-config.js
- lib/jstd-scenario-adapter.js
# your test files go here #
proxy:
- {matcher: "/your-prefix/*", server: "http://localhost:8000/"}
</pre>
*
* For more information on how to configure jstd proxy, see {@link http://code.google.com/p/js-test-driver/wiki/Proxy}
* Note the order of files - it's important !
*
* Example of jstd-scenario-adapter-config.js
<pre>
var jstdScenarioAdapter = {
relativeUrlPrefix: '/your-prefix/'
};
</pre>
*
* Whenever you use <code>browser().navigateTo('relativeUrl')</code> in your scenario test, the relativeUrlPrefix will be prepended.
* You have to configure this to work together with JSTD proxy.
*
* Let's assume you are using the above configuration (jsTestDriver.conf and jstd-scenario-adapter-config.js):
* Now, when you call <code>browser().navigateTo('index.html')</code> in your scenario test, the browser will open /your-prefix/index.html.
* That matches the proxy, so JSTD will proxy this request to http://localhost:8000/index.html.
*/
/**
* Custom type of test case
*
* @const
* @see jstestdriver.TestCaseInfo
*/
var SCENARIO_TYPE = 'scenario';
/**
* Plugin for JSTestDriver
* Connection point between scenario's jstd output and jstestdriver.
*
* @see jstestdriver.PluginRegistrar
*/
function JstdPlugin() {
var nop = function() {};
this.reportResult = nop;
this.reportEnd = nop;
this.runScenario = nop;
this.name = 'Angular Scenario Adapter';
/**
* Called for each JSTD TestCase
*
* Handles only SCENARIO_TYPE test cases. There should be only one fake TestCase.
* Runs all scenario tests (under one fake TestCase) and report all results to JSTD.
*
* @param {jstestdriver.TestRunConfiguration} configuration
* @param {Function} onTestDone
* @param {Function} onAllTestsComplete
* @returns {boolean} True if this type of test is handled by this plugin, false otherwise
*/
this.runTestConfiguration = function(configuration, onTestDone, onAllTestsComplete) {
if (configuration.getTestCaseInfo().getType() != SCENARIO_TYPE) return false;
this.reportResult = onTestDone;
this.reportEnd = onAllTestsComplete;
this.runScenario();
return true;
};
this.getTestRunsConfigurationFor = function(testCaseInfos, expressions, testRunsConfiguration) {
testRunsConfiguration.push(
new jstestdriver.TestRunConfiguration(
new jstestdriver.TestCaseInfo(
'Angular Scenario Tests', function() {}, SCENARIO_TYPE), []));
return true;
};
}
/**
* Singleton instance of the plugin
* Accessed using closure by:
* - jstd output (reports to this plugin)
* - initScenarioAdapter (register the plugin to jstd)
*/
var plugin = new JstdPlugin();
/**
* Initialise scenario jstd-adapter
* (only if jstestdriver is defined)
*
* @param {Object} jstestdriver Undefined when run from browser (without jstd)
* @param {Function} initScenarioAndRun Function that inits scenario and runs all the tests
* @param {Object=} config Configuration object, supported properties:
* - relativeUrlPrefix: prefix for all relative links when navigateTo()
*/
function initScenarioAdapter(jstestdriver, initScenarioAndRun, config) {
if (jstestdriver) {
// create and register ScenarioPlugin
jstestdriver.pluginRegistrar.register(plugin);
plugin.runScenario = initScenarioAndRun;
/**
* HACK (angular.scenario.Application.navigateTo)
*
* We need to navigate to relative urls when running from browser (without JSTD),
* because we want to allow running scenario tests without creating its own virtual host.
* For example: http://angular.local/build/docs/docs-scenario.html
*
* On the other hand, when running with JSTD, we need to navigate to absolute urls,
* because of JSTD proxy. (proxy, because of same domain policy)
*
* So this hack is applied only if running with JSTD and change all relative urls to absolute.
*/
var appProto = angular.scenario.Application.prototype,
navigateTo = appProto.navigateTo,
relativeUrlPrefix = config && config.relativeUrlPrefix || '/';
appProto.navigateTo = function(url, loadFn, errorFn) {
if (url.charAt(0) != '/' && url.charAt(0) != '#' &&
url != 'about:blank' && !url.match(/^https?/)) {
url = relativeUrlPrefix + url;
}
return navigateTo.call(this, url, loadFn, errorFn);
};
}
}
/**
* Builds proper TestResult object from given model spec
*
* TODO(vojta) report error details
*
* @param {angular.scenario.ObjectModel.Spec} spec
* @returns {jstestdriver.TestResult}
*/
function createTestResultFromSpec(spec) {
var map = {
success: 'PASSED',
error: 'ERROR',
failure: 'FAILED'
};
return new jstestdriver.TestResult(
spec.fullDefinitionName,
spec.name,
jstestdriver.TestResult.RESULT[map[spec.status]],
spec.error || '',
spec.line || '',
spec.duration);
}
/**
* Generates JSTD output (jstestdriver.TestResult)
*/
angular.scenario.output('jstd', function(context, runner, model) {
model.on('SpecEnd', function(spec) {
plugin.reportResult(createTestResultFromSpec(spec));
});
model.on('RunnerEnd', function() {
plugin.reportEnd();
});
});
initScenarioAdapter(window.jstestdriver, angular.scenario.setUpAndRun, window.jstdScenarioAdapter);
})(window);
| zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/jstd-scenario-adapter-1.0.0.js | JavaScript | asf20 | 5,784 |
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngCookies
*/
angular.module('ngCookies', ['ng']).
/**
* @ngdoc object
* @name ngCookies.$cookies
* @requires $browser
*
* @description
* Provides read/write access to browser's cookies.
*
* Only a simple Object is exposed and by adding or removing properties to/from
* this object, new cookies are created/deleted at the end of current $eval.
*
* @example
*/
factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) {
var cookies = {},
lastCookies = {},
lastBrowserCookies,
runEval = false,
copy = angular.copy,
isUndefined = angular.isUndefined;
//creates a poller fn that copies all cookies from the $browser to service & inits the service
$browser.addPollFn(function() {
var currentCookies = $browser.cookies();
if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl
lastBrowserCookies = currentCookies;
copy(currentCookies, lastCookies);
copy(currentCookies, cookies);
if (runEval) $rootScope.$apply();
}
})();
runEval = true;
//at the end of each eval, push cookies
//TODO: this should happen before the "delayed" watches fire, because if some cookies are not
// strings or browser refuses to store some cookies, we update the model in the push fn.
$rootScope.$watch(push);
return cookies;
/**
* Pushes all the cookies from the service to the browser and verifies if all cookies were stored.
*/
function push() {
var name,
value,
browserCookies,
updated;
//delete any cookies deleted in $cookies
for (name in lastCookies) {
if (isUndefined(cookies[name])) {
$browser.cookies(name, undefined);
}
}
//update all cookies updated in $cookies
for(name in cookies) {
value = cookies[name];
if (!angular.isString(value)) {
if (angular.isDefined(lastCookies[name])) {
cookies[name] = lastCookies[name];
} else {
delete cookies[name];
}
} else if (value !== lastCookies[name]) {
$browser.cookies(name, value);
updated = true;
}
}
//verify what was actually stored
if (updated){
updated = false;
browserCookies = $browser.cookies();
for (name in cookies) {
if (cookies[name] !== browserCookies[name]) {
//delete or reset all cookies that the browser dropped from $cookies
if (isUndefined(browserCookies[name])) {
delete cookies[name];
} else {
cookies[name] = browserCookies[name];
}
updated = true;
}
}
}
}
}]).
/**
* @ngdoc object
* @name ngCookies.$cookieStore
* @requires $cookies
*
* @description
* Provides a key-value (string-object) storage, that is backed by session cookies.
* Objects put or retrieved from this storage are automatically serialized or
* deserialized by angular's toJson/fromJson.
* @example
*/
factory('$cookieStore', ['$cookies', function($cookies) {
return {
/**
* @ngdoc method
* @name ngCookies.$cookieStore#get
* @methodOf ngCookies.$cookieStore
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value.
*/
get: function(key) {
return angular.fromJson($cookies[key]);
},
/**
* @ngdoc method
* @name ngCookies.$cookieStore#put
* @methodOf ngCookies.$cookieStore
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
*/
put: function(key, value) {
$cookies[key] = angular.toJson(value);
},
/**
* @ngdoc method
* @name ngCookies.$cookieStore#remove
* @methodOf ngCookies.$cookieStore
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
*/
remove: function(key) {
delete $cookies[key];
}
};
}]);
})(window, window.angular);
| zzangtest123-google-drive-sdk-samples | java/war/lib/angular-1.0.0/angular-cookies-1.0.0.js | JavaScript | asf20 | 4,842 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/tomorrow_night_blue', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-tomorrow-night-blue";
exports.cssText = "\
.ace-tomorrow-night-blue .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-tomorrow-night-blue .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-tomorrow-night-blue .ace_gutter {\
background: #022346;\
color: #7388b5;\
}\
\
.ace-tomorrow-night-blue .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-tomorrow-night-blue .ace_scroller {\
background-color: #002451;\
}\
\
.ace-tomorrow-night-blue .ace_text-layer {\
cursor: text;\
color: #FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_cursor {\
border-left: 2px solid #FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_selection {\
background: #003F8E;\
}\
\
.ace-tomorrow-night-blue.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #002451;\
border-radius: 2px;\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_step {\
background: rgb(127, 111, 19);\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #404F7D;\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_active_line {\
background: #00346E;\
}\
\
.ace-tomorrow-night-blue .ace_gutter_active_line {\
background-color: #022040;\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_selected_word {\
border: 1px solid #003F8E;\
}\
\
.ace-tomorrow-night-blue .ace_invisible {\
color: #404F7D;\
}\
\
.ace-tomorrow-night-blue .ace_keyword, .ace-tomorrow-night-blue .ace_meta {\
color:#EBBBFF;\
}\
\
.ace-tomorrow-night-blue .ace_keyword.ace_operator {\
color:#99FFFF;\
}\
\
.ace-tomorrow-night-blue .ace_constant.ace_language {\
color:#FFC58F;\
}\
\
.ace-tomorrow-night-blue .ace_constant.ace_numeric {\
color:#FFC58F;\
}\
\
.ace-tomorrow-night-blue .ace_constant.ace_other {\
color:#FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_invalid {\
color:#FFFFFF;\
background-color:#F99DA5;\
}\
\
.ace-tomorrow-night-blue .ace_invalid.ace_deprecated {\
color:#FFFFFF;\
background-color:#EBBBFF;\
}\
\
.ace-tomorrow-night-blue .ace_support.ace_constant {\
color:#FFC58F;\
}\
\
.ace-tomorrow-night-blue .ace_fold {\
background-color: #BBDAFF;\
border-color: #FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_support.ace_function {\
color:#BBDAFF;\
}\
\
.ace-tomorrow-night-blue .ace_storage {\
color:#EBBBFF;\
}\
\
.ace-tomorrow-night-blue .ace_storage.ace_type, .ace-tomorrow-night-blue .ace_support.ace_type{\
color:#EBBBFF;\
}\
\
.ace-tomorrow-night-blue .ace_variable {\
color:#BBDAFF;\
}\
\
.ace-tomorrow-night-blue .ace_variable.ace_parameter {\
color:#FFC58F;\
}\
\
.ace-tomorrow-night-blue .ace_string {\
color:#D1F1A9;\
}\
\
.ace-tomorrow-night-blue .ace_string.ace_regexp {\
color:#FF9DA4;\
}\
\
.ace-tomorrow-night-blue .ace_comment {\
color:#7285B7;\
}\
\
.ace-tomorrow-night-blue .ace_variable {\
color:#FF9DA4;\
}\
\
.ace-tomorrow-night-blue .ace_meta.ace_tag {\
color:#FF9DA4;\
}\
\
.ace-tomorrow-night-blue .ace_entity.ace_other.ace_attribute-name {\
color:#FF9DA4;\
}\
\
.ace-tomorrow-night-blue .ace_entity.ace_name.ace_function {\
color:#BBDAFF;\
}\
\
.ace-tomorrow-night-blue .ace_markup.ace_underline {\
text-decoration:underline;\
}\
\
.ace-tomorrow-night-blue .ace_markup.ace_heading {\
color:#D1F1A9;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| zzangtest123-google-drive-sdk-samples | java/war/lib/ace/theme-tomorrow_night_blue.js | JavaScript | asf20 | 5,404 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/cobalt', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-cobalt";
exports.cssText = "\
.ace-cobalt .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-cobalt .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-cobalt .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-cobalt .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-cobalt .ace_scroller {\
background-color: #002240;\
}\
\
.ace-cobalt .ace_text-layer {\
cursor: text;\
color: #FFFFFF;\
}\
\
.ace-cobalt .ace_cursor {\
border-left: 2px solid #FFFFFF;\
}\
\
.ace-cobalt .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #FFFFFF;\
}\
\
.ace-cobalt .ace_marker-layer .ace_selection {\
background: rgba(179, 101, 57, 0.75);\
}\
\
.ace-cobalt.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #002240;\
border-radius: 2px;\
}\
\
.ace-cobalt .ace_marker-layer .ace_step {\
background: rgb(127, 111, 19);\
}\
\
.ace-cobalt .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgba(255, 255, 255, 0.15);\
}\
\
.ace-cobalt .ace_marker-layer .ace_active_line {\
background: rgba(0, 0, 0, 0.35);\
}\
\
.ace-cobalt .ace_gutter_active_line {\
background-color : #dcdcdc;\
}\
\
.ace-cobalt .ace_marker-layer .ace_selected_word {\
border: 1px solid rgba(179, 101, 57, 0.75);\
}\
\
.ace-cobalt .ace_invisible {\
color: rgba(255, 255, 255, 0.15);\
}\
\
.ace-cobalt .ace_keyword, .ace-cobalt .ace_meta {\
color:#FF9D00;\
}\
\
.ace-cobalt .ace_constant, .ace-cobalt .ace_constant.ace_other {\
color:#FF628C;\
}\
\
.ace-cobalt .ace_constant.ace_character, {\
color:#FF628C;\
}\
\
.ace-cobalt .ace_constant.ace_character.ace_escape, {\
color:#FF628C;\
}\
\
.ace-cobalt .ace_invalid {\
color:#F8F8F8;\
background-color:#800F00;\
}\
\
.ace-cobalt .ace_support {\
color:#80FFBB;\
}\
\
.ace-cobalt .ace_support.ace_constant {\
color:#EB939A;\
}\
\
.ace-cobalt .ace_fold {\
background-color: #FF9D00;\
border-color: #FFFFFF;\
}\
\
.ace-cobalt .ace_support.ace_function {\
color:#FFB054;\
}\
\
.ace-cobalt .ace_storage {\
color:#FFEE80;\
}\
\
.ace-cobalt .ace_string.ace_regexp {\
color:#80FFC2;\
}\
\
.ace-cobalt .ace_comment {\
font-style:italic;\
color:#0088FF;\
}\
\
.ace-cobalt .ace_variable {\
color:#CCCCCC;\
}\
\
.ace-cobalt .ace_variable.ace_language {\
color:#FF80E1;\
}\
\
.ace-cobalt .ace_meta.ace_tag {\
color:#9EFFFF;\
}\
\
.ace-cobalt .ace_markup.ace_underline {\
text-decoration:underline;\
}\
\
.ace-cobalt .ace_markup.ace_heading {\
color:#C8E4FD;\
background-color:#001221;\
}\
\
.ace-cobalt .ace_markup.ace_list {\
background-color:#130D26;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| zzangtest123-google-drive-sdk-samples | java/war/lib/ace/theme-cobalt.js | JavaScript | asf20 | 4,632 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/clouds', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = false;
exports.cssClass = "ace-clouds";
exports.cssText = "\
.ace-clouds .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-clouds .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-clouds .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-clouds .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-clouds .ace_scroller {\
background-color: #FFFFFF;\
}\
\
.ace-clouds .ace_text-layer {\
cursor: text;\
color: #000000;\
}\
\
.ace-clouds .ace_cursor {\
border-left: 2px solid #000000;\
}\
\
.ace-clouds .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #000000;\
}\
\
.ace-clouds .ace_marker-layer .ace_selection {\
background: #BDD5FC;\
}\
\
.ace-clouds.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #FFFFFF;\
border-radius: 2px;\
}\
\
.ace-clouds .ace_marker-layer .ace_step {\
background: rgb(255, 255, 0);\
}\
\
.ace-clouds .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #BFBFBF;\
}\
\
.ace-clouds .ace_marker-layer .ace_active_line {\
background: #FFFBD1;\
}\
\
.ace-clouds .ace_gutter_active_line {\
background-color : #dcdcdc;\
}\
\
.ace-clouds .ace_marker-layer .ace_selected_word {\
border: 1px solid #BDD5FC;\
}\
\
.ace-clouds .ace_invisible {\
color: #BFBFBF;\
}\
\
.ace-clouds .ace_keyword, .ace-clouds .ace_meta {\
color:#AF956F;\
}\
\
.ace-clouds .ace_keyword.ace_operator {\
color:#484848;\
}\
\
.ace-clouds .ace_constant.ace_language {\
color:#39946A;\
}\
\
.ace-clouds .ace_constant.ace_numeric {\
color:#46A609;\
}\
\
.ace-clouds .ace_invalid {\
background-color:#FF002A;\
}\
\
.ace-clouds .ace_fold {\
background-color: #AF956F;\
border-color: #000000;\
}\
\
.ace-clouds .ace_support.ace_function {\
color:#C52727;\
}\
\
.ace-clouds .ace_storage {\
color:#C52727;\
}\
\
.ace-clouds .ace_string {\
color:#5D90CD;\
}\
\
.ace-clouds .ace_comment {\
color:#BCC8BA;\
}\
\
.ace-clouds .ace_entity.ace_other.ace_attribute-name {\
color:#606060;\
}\
\
.ace-clouds .ace_markup.ace_underline {\
text-decoration:underline;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| zzangtest123-google-drive-sdk-samples | java/war/lib/ace/theme-clouds.js | JavaScript | asf20 | 4,092 |