text,length,is_long_context,metric_val,label_metric "= v1.Service {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] Service is a named abstraction of software service (for example, mysql) consisting of local port (for example 3306) that the proxy listens on, and the selector that determines which pods will answer requests sent through the proxy. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
spec:
clusterIP:
externalIPs:
- [string]:
externalName:
externalTrafficPolicy:
healthCheckNodePort:
loadBalancerIP:
loadBalancerSourceRanges:
- [string]:
ports:
- name:
nodePort:
port:
protocol:
targetPort:
selector:
[string]:
sessionAffinity:
type:
status:
loadBalancer:
ingress:
- hostname:
ip:
++++ == Operations [[Post-api-v1-services]] === Create a Service Create a Service ==== HTTP request ---- POST /api/v1/services HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""Service"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/api/v1/services <<'EOF' { ""kind"": ""Service"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Service |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Service |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Post-api-v1-namespaces-namespace-services]] === Create a Service in a namespace Create a Service ==== HTTP request ---- POST /api/v1/namespaces/$NAMESPACE/services HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""Service"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services <<'EOF' { ""kind"": ""Service"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Service |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Service |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-api-v1-namespaces-namespace-services-name]] === Get a Service in a namespace Read the specified Service ==== HTTP request ---- GET /api/v1/namespaces/$NAMESPACE/services/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Service |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-api-v1-services]] === Get all Services List or watch objects of kind Service ==== HTTP request ---- GET /api/v1/services HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/services ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ServiceList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-api-v1-namespaces-namespace-services]] === Get all Services in a namespace List or watch objects of kind Service ==== HTTP request ---- GET /api/v1/namespaces/$NAMESPACE/services HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ServiceList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-api-v1-watch-namespaces-namespace-services-name]] === Watch a Service in a namespace Watch changes to an object of kind Service ==== HTTP request ---- GET /api/v1/watch/namespaces/$NAMESPACE/services/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/watch/namespaces/$NAMESPACE/services/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-api-v1-watch-services]] === Watch all Services Watch individual changes to a list of Service ==== HTTP request ---- GET /api/v1/watch/services HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/watch/services ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-api-v1-watch-namespaces-namespace-services]] === Watch all Services in a namespace Watch individual changes to a list of Service ==== HTTP request ---- GET /api/v1/watch/namespaces/$NAMESPACE/services HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/watch/namespaces/$NAMESPACE/services ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-api-v1-namespaces-namespace-services-name]] === Update a Service in a namespace Replace the specified Service ==== HTTP request ---- PUT /api/v1/namespaces/$NAMESPACE/services/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""Service"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME <<'EOF' { ""kind"": ""Service"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Service |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Service |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-api-v1-namespaces-namespace-services-name]] === Patch a Service in a namespace Partially update the specified Service ==== HTTP request ---- PATCH /api/v1/namespaces/$NAMESPACE/services/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Service |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-api-v1-namespaces-namespace-services-name]] === Delete a Service in a namespace Delete a Service ==== HTTP request ---- DELETE /api/v1/namespaces/$NAMESPACE/services/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-api-v1-namespaces-namespace-services-name-status]] === Get status of a Service in a namespace Read status of the specified Service ==== HTTP request ---- GET /api/v1/namespaces/$NAMESPACE/services/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/status ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Service |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Put-api-v1-namespaces-namespace-services-name-status]] === Update status of a Service in a namespace Replace status of the specified Service ==== HTTP request ---- PUT /api/v1/namespaces/$NAMESPACE/services/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""Service"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/status <<'EOF' { ""kind"": ""Service"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Service |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Service |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-api-v1-namespaces-namespace-services-name-status]] === Patch status of a Service in a namespace Partially update status of the specified Service ==== HTTP request ---- PATCH /api/v1/namespaces/$NAMESPACE/services/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/status <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Service |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Options-api-v1-namespaces-namespace-services-name-proxy]] === Proxy OPTIONS request to a Service in a namespace Connect OPTIONS requests to proxy of Service ==== HTTP request ---- OPTIONS /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X OPTIONS \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Post-api-v1-namespaces-namespace-services-name-proxy]] === Proxy POST request to a Service in a namespace Connect POST requests to proxy of Service ==== HTTP request ---- POST /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Head-api-v1-namespaces-namespace-services-name-proxy]] === Proxy HEAD request to a Service in a namespace Connect HEAD requests to proxy of Service ==== HTTP request ---- HEAD /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X HEAD \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Get-api-v1-namespaces-namespace-services-name-proxy]] === Proxy GET request to a Service in a namespace Connect GET requests to proxy of Service ==== HTTP request ---- GET /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Put-api-v1-namespaces-namespace-services-name-proxy]] === Proxy PUT request to a Service in a namespace Connect PUT requests to proxy of Service ==== HTTP request ---- PUT /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Patch-api-v1-namespaces-namespace-services-name-proxy]] === Proxy PATCH request to a Service in a namespace Connect PATCH requests to proxy of Service ==== HTTP request ---- PATCH /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Delete-api-v1-namespaces-namespace-services-name-proxy]] === Proxy DELETE request to a Service in a namespace Connect DELETE requests to proxy of Service ==== HTTP request ---- DELETE /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Options-api-v1-namespaces-namespace-services-name-proxy-path]] === Proxy OPTIONS request to a Service in a namespace (with path) Connect OPTIONS requests to proxy of Service ==== HTTP request ---- OPTIONS /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X OPTIONS \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |path|path to the resource |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Post-api-v1-namespaces-namespace-services-name-proxy-path]] === Proxy POST request to a Service in a namespace (with path) Connect POST requests to proxy of Service ==== HTTP request ---- POST /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |path|path to the resource |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Head-api-v1-namespaces-namespace-services-name-proxy-path]] === Proxy HEAD request to a Service in a namespace (with path) Connect HEAD requests to proxy of Service ==== HTTP request ---- HEAD /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X HEAD \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |path|path to the resource |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Get-api-v1-namespaces-namespace-services-name-proxy-path]] === Proxy GET request to a Service in a namespace (with path) Connect GET requests to proxy of Service ==== HTTP request ---- GET /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |path|path to the resource |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Put-api-v1-namespaces-namespace-services-name-proxy-path]] === Proxy PUT request to a Service in a namespace (with path) Connect PUT requests to proxy of Service ==== HTTP request ---- PUT /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |path|path to the resource |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Patch-api-v1-namespaces-namespace-services-name-proxy-path]] === Proxy PATCH request to a Service in a namespace (with path) Connect PATCH requests to proxy of Service ==== HTTP request ---- PATCH /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |path|path to the resource |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* [[Delete-api-v1-namespaces-namespace-services-name-proxy-path]] === Proxy DELETE request to a Service in a namespace (with path) Connect DELETE requests to proxy of Service ==== HTTP request ---- DELETE /api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/api/v1/namespaces/$NAMESPACE/services/$NAME/proxy/$PATH ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Service |namespace|object name and auth scope, such as for teams and projects |path|path to the resource |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |path|Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|string |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * \\*/* ",16149,True,2942.3405229067885,median "//Copyright (c) 2010, Charles Strahan // //All rights reserved. // // Original Showdown Copyright (c) 2007, John Fraser // //All rights reserved. // // Original Markdown copyright (c) 2004, John Gruber // //All rights reserved. // // Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are //met: // //* Redistributions of source code must retain the above copyright notice, //this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright //notice, this list of conditions and the following disclaimer in the //documentation and/or other materials provided with the distribution. // // * Neither the name ""Markdown"" nor the names of its contributors may //be used to endorse or promote products derived from this software //without specific prior written permission. // // This software is provided by the copyright holders and contributors ""as //is"" and any express or implied warranties, including, but not limited //to, the implied warranties of merchantability and fitness for a //particular purpose are disclaimed. In no event shall the copyright owner //or contributors be liable for any direct, indirect, incidental, special, //exemplary, or consequential damages (including, but not limited to, // procurement of substitute goods or services; loss of use, data, or // profits; or business interruption) however caused and on any theory of //liability, whether in contract, strict liability, or tort (including // negligence or otherwise) arising in any way out of the use of this //software, even if advised of the possibility of such damage. // // Showdown.as -- An ActionScript port of showdown.js // // Copyright (c) 2010 Charles Strahan. // // Original Showdown Copyright (c) 2007 John Fraser. // // // Original Markdown Copyright (c) 2004-2005 John Gruber // // // Redistributable under a BSD-style open source license. // See license.txt for more information. // // Usage: // // var text = ""Markdown *rocks*.""; // var html = Showdown.makeHtml(text); // package { public class Showdown { // Global hashes, used by various utility routines private static var g_urls:Array; private static var g_titles:Array; private static var g_html_blocks:Array; private static var g_extensions:Array = new Array(); ; // Used to track when we're inside an ordered or unordered list // (see _ProcessListItems() for details): private static var g_list_level:Number = 0; public static function addExtension(extension):void { if (g_extensions.indexOf(extension) == -1) g_extensions.push(extension); } public static function makeHtml(text:String):String { // Clear the global hashes. If we don't clear these, you get conflicts // from other articles when generating a page which contains more than // one article (e.g. an index page that shows the N most recent // articles): g_urls = new Array(); g_titles = new Array(); g_html_blocks = new Array(); // attacklab: Replace ~ with ~T // This lets us use tilde as an escape char to avoid md5 hashes // The choice of character is arbitray; anything that isn't // magic in Markdown will work. text = text.replace(/~/g,""~T""); // attacklab: Replace $ with ~D // RegExp interprets $ as a special character // when it's in a replacement string text = text.replace(/\\$/g,""~D""); // Standardize line endings text = text.replace(/\\r\\n/g,""\\n""); // DOS to Unix text = text.replace(/\\r/g,""\\n""); // Mac to Unix // Make sure text begins and ends with a couple of newlines: text = ""\\n\\n"" + text + ""\\n\\n""; // Convert all tabs to spaces. text = _Detab(text); // Strip any lines consisting only of spaces and tabs. // This makes subsequent regexen easier to write, because we can // match consecutive blank lines with /\\n+/ instead of something // contorted like /[ \\t]*\\n+/ . text = text.replace(/^[ \\t]+$/mg,""""); // Execute all extensions on processed text. for (var i=0; i? // url = $2 [ \\t]* \\n? // maybe one newline [ \\t]* (?: (\\n*) // any lines skipped = $3 attacklab: lookbehind removed [""(] (.+?) // title = $4 ["")] [ \\t]* )? // title is optional (?:\\n+|$) /gm, function(){...}); */ var text = text.replace(/^[ ]{0,3}\\[(.+)\\]:[ \\t]*\\n?[ \\t]*?[ \\t]*\\n?[ \\t]*(?:(\\n*)[""(](.+?)["")][ \\t]*)?(?:\\n+|\\Z)/gm, function (wholeMatch,m1,m2,m3,m4) { m1 = m1.toLowerCase(); g_urls[m1] = _EncodeAmpsAndAngles(m2); // Link IDs are case-insensitive if (m3) { // Oops, found blank lines, so it's not a title. // Put back the parenthetical statement we stole. return m3+m4; } else if (m4) { g_titles[m1] = m4.replace(/""/g,"""""); } // Completely remove the definition from the text return """"; } ); return text; } private static function _HashHTMLBlocks(text) { // attacklab: Double up blank lines to reduce lookaround text = text.replace(/\\n/g,""\\n\\n""); // Hashify HTML blocks: // We only want to do this for block-level HTML tags, such as headers, // lists, and tables. That's because we still want to wrap

s around // ""paragraphs"" that are wrapped in non-block-level tags, such as anchors, // phrase emphasis, and spans. The list of tags we're looking for is // hard-coded: var block_tags_a = ""p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del"" var block_tags_b = ""p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math"" // First, look for nested blocks, e.g.: //

//
// tags for inner block must be indented. //
//
// // The outermost tags must start at the left margin for this to match, and // the inner nested divs must be indented. // We need to do this before the next, more liberal match, because the next // match will start at the first `
` and stop at the first `
`. // attacklab: This regex can be expensive when it fails. /* var text = text.replace(/ ( // save in $1 ^ // start of line (with /m) <($block_tags_a) // start tag = $2 \\b // word break // attacklab: hack around khtml/pcre bug... [^\\r]*?\\n // any number of lines, minimally matching // the matching end tag [ \\t]* // trailing spaces/tabs (?=\\n+) // followed by a newline ) // attacklab: there are sentinel newlines at end of document /gm,function(){...}}; */ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\\b[^\\r]*?\\n<\\/\\2>[ \\t]*(?=\\n+))/gm,hashElement); // // Now match more liberally, simply from `\\n` to `\\n` // /* var text = text.replace(/ ( // save in $1 ^ // start of line (with /m) <($block_tags_b) // start tag = $2 \\b // word break // attacklab: hack around khtml/pcre bug... [^\\r]*? // any number of lines, minimally matching .* // the matching end tag [ \\t]* // trailing spaces/tabs (?=\\n+) // followed by a newline ) // attacklab: there are sentinel newlines at end of document /gm,function(){...}}; */ text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\\b[^\\r]*?.*<\\/\\2>[ \\t]*(?=\\n+)\\n)/gm,hashElement); // Special case just for
. It was easier to make a special case than // to make the other regex more complicated. /* text = text.replace(/ ( // save in $1 \\n\\n // Starting after a blank line [ ]{0,3} (<(hr) // start tag = $2 \\b // word break ([^<>])*? // \\/?>) // the matching end tag [ \\t]* (?=\\n{2,}) // followed by a blank line ) /g,hashElement); */ text = text.replace(/(\\n[ ]{0,3}(<(hr)\\b([^<>])*?\\/?>)[ \\t]*(?=\\n{2,}))/g,hashElement); // Special case for standalone HTML comments: /* text = text.replace(/ ( // save in $1 \\n\\n // Starting after a blank line [ ]{0,3} // attacklab: g_tab_width - 1 [ \\t]* (?=\\n{2,}) // followed by a blank line ) /g,hashElement); */ text = text.replace(/(\\n\\n[ ]{0,3}[ \\t]*(?=\\n{2,}))/g,hashElement); // PHP and ASP-style processor instructions ( and <%...%>) /* text = text.replace(/ (?: \\n\\n // Starting after a blank line ) ( // save in $1 [ ]{0,3} // attacklab: g_tab_width - 1 (?: <([?%]) // $2 [^\\r]*? \\2> ) [ \\t]* (?=\\n{2,}) // followed by a blank line ) /g,hashElement); */ text = text.replace(/(?:\\n\\n)([ ]{0,3}(?:<([?%])[^\\r]*?\\2>)[ \\t]*(?=\\n{2,}))/g,hashElement); // attacklab: Undo double lines (see comment at top of this function) text = text.replace(/\\n\\n/g,""\\n""); return text; } private static function hashElement(wholeMatch,m1,m2,m3,m4) { var blockText = m1; // Undo double lines blockText = blockText.replace(/\\n\\n/g,""\\n""); blockText = blockText.replace(/^\\n/,""""); // strip trailing blank lines blockText = blockText.replace(/\\n+$/g,""""); // Replace the element text with a marker (""~KxK"" where x is its key) blockText = ""\\n\\n~K"" + (g_html_blocks.push(blockText)-1) + ""K\\n\\n""; return blockText; }; private static function _RunBlockGamut(text) { // // These are all the transformations that form block-level // tags like paragraphs, headers, and list items. // text = _DoHeaders(text); // Do Horizontal Rules: var key = hashBlock(""
""); text = text.replace(/^[ ]{0,2}([ ]?\\*[ ]?){3,}[ \\t]*$/gm,key); text = text.replace(/^[ ]{0,2}([ ]?\\-[ ]?){3,}[ \\t]*$/gm,key); text = text.replace(/^[ ]{0,2}([ ]?\\_[ ]?){3,}[ \\t]*$/gm,key); text = _DoLists(text); text = _DoCodeBlocks(text); text = _DoBlockQuotes(text); // We already ran _HashHTMLBlocks() before, in Markdown(), but that // was to escape raw HTML in the original Markdown source. This time, // we're escaping the markup we've just created, so that we don't wrap //

tags around block-level tags. text = _HashHTMLBlocks(text); text = _FormParagraphs(text); return text; } private static function _RunSpanGamut(text) { // // These are all the transformations that occur *within* block-level // tags like paragraphs, headers, and list items. // text = _DoCodeSpans(text); text = _EscapeSpecialCharsWithinTagAttributes(text); text = _EncodeBackslashEscapes(text); // Process anchor and image tags. Images must come first, // because ![foo][f] looks like an anchor. text = _DoImages(text); text = _DoAnchors(text); // Make links out of things like `` // Must come after _DoAnchors(), because you can use < and > // delimiters in inline links like [this](). text = _DoAutoLinks(text); text = _EncodeAmpsAndAngles(text); text = _DoItalicsAndBold(text); // Do hard breaks: text = text.replace(/ +\\n/g,""
\\n""); return text; } private static function _EscapeSpecialCharsWithinTagAttributes(text) { // // Within tags -- meaning between < and > -- encode [\\ ` * _] so they // don't conflict with their use in Markdown for code, italics and strong. // // Build a regex to find HTML tags and comments. See Friedl's // ""Mastering Regular Expressions"", 2nd Ed., pp. 200-201. var regex = /(<[a-z\\/!$](""[^""]*""|'[^']*'|[^'"">])*>|)/gi; text = text.replace(regex, function(wholeMatch) { var tag = wholeMatch.replace(/(.)<\\/?code>(?=.)/g,""$1`""); tag = escapeCharacters(tag,""\\\\`*_""); return tag; }); return text; } private static function _DoAnchors(text) { // // Turn Markdown link shortcuts into XHTML tags. // // // First, handle reference-style links: [link text] [id] // /* text = text.replace(/ ( // wrap whole match in $1 \\[ ( (?: \\[[^\\]]*\\] // allow brackets nested one level | [^\\[] // or anything else )* ) \\] [ ]? // one optional space (?:\\n[ ]*)? // one optional newline followed by spaces \\[ (.*?) // id = $3 \\] )()()()() // pad remaining backreferences /g,_DoAnchors_callback); */ text = text.replace(/(\\[((?:\\[[^\\]]*\\]|[^\\[\\]])*)\\][ ]?(?:\\n[ ]*)?\\[(.*?)\\])()()()()/g,writeAnchorTag); // // Next, inline-style links: [link text](url ""optional title"") // /* text = text.replace(/ ( // wrap whole match in $1 \\[ ( (?: \\[[^\\]]*\\] // allow brackets nested one level | [^\\[\\]] // or anything else ) ) \\] \\( // literal paren [ \\t]* () // no id, so leave $3 empty ? // href = $4 [ \\t]* ( // $5 (['""]) // quote char = $6 (.*?) // Title = $7 \\6 // matching quote [ \\t]* // ignore any spaces/tabs between closing quote and ) )? // title is optional \\) ) /g,writeAnchorTag); */ text = text.replace(/(\\[((?:\\[[^\\]]*\\]|[^\\[\\]])*)\\]\\([ \\t]*()?[ \\t]*((['""])(.*?)\\6[ \\t]*)?\\))/g,writeAnchorTag); // // Last, handle reference-style shortcuts: [link text] // These must come last in case you've also got [link test][1] // or [link test](/foo) // /* text = text.replace(/ ( // wrap whole match in $1 \\[ ([^\\[\\]]+) // link text = $2; can't contain '[' or ']' \\] )()()()()() // pad rest of backreferences /g, writeAnchorTag); */ text = text.replace(/(\\[([^\\[\\]]+)\\])()()()()()/g, writeAnchorTag); return text; } private static function writeAnchorTag(wholeMatch,m1,m2,m3,m4,m5,m6,m7,m8,m9) { if (m7 == undefined) m7 = """"; var whole_match = m1; var link_text = m2; var link_id = m3.toLowerCase(); var url = m4; var title = m7; if (url == """") { if (link_id == """") { // lower-case and turn embedded newlines into spaces link_id = link_text.toLowerCase().replace(/ ?\\n/g,"" ""); } url = ""#""+link_id; if (g_urls[link_id] != undefined) { url = g_urls[link_id]; if (g_titles[link_id] != undefined) { title = g_titles[link_id]; } } else { if (whole_match.search(/\\(\\s*\\)$/m)>-1) { // Special case for explicit empty url url = """"; } else { return whole_match; } } } url = escapeCharacters(url,""*_""); var result = """" + link_text + """"; return result; } private static function _DoImages(text) { // // Turn Markdown image shortcuts into tags. // // // First, handle reference-style labeled images: ![alt text][id] // /* text = text.replace(/ ( // wrap whole match in $1 !\\[ (.*?) // alt text = $2 \\] [ ]? // one optional space (?:\\n[ ]*)? // one optional newline followed by spaces \\[ (.*?) // id = $3 \\] )()()()() // pad rest of backreferences /g,writeImageTag); */ text = text.replace(/(!\\[(.*?)\\][ ]?(?:\\n[ ]*)?\\[(.*?)\\])()()()()/g,writeImageTag); // // Next, handle inline images: ![alt text](url ""optional title"") // Don't forget: encode * and _ /* text = text.replace(/ ( // wrap whole match in $1 !\\[ (.*?) // alt text = $2 \\] \\s? // One optional whitespace character \\( // literal paren [ \\t]* () // no id, so leave $3 empty ? // src url = $4 [ \\t]* ( // $5 (['""]) // quote char = $6 (.*?) // title = $7 \\6 // matching quote [ \\t]* )? // title is optional \\) ) /g,writeImageTag); */ text = text.replace(/(!\\[(.*?)\\]\\s?\\([ \\t]*()?[ \\t]*((['""])(.*?)\\6[ \\t]*)?\\))/g,writeImageTag); return text; } private static function writeImageTag(wholeMatch,m1,m2,m3,m4,m5,m6,m7,m8,m9) { var whole_match = m1; var alt_text = m2; var link_id = m3.toLowerCase(); var url = m4; var title = m7; if (!title) title = """"; if (url == """") { if (link_id == """") { // lower-case and turn embedded newlines into spaces link_id = alt_text.toLowerCase().replace(/ ?\\n/g,"" ""); } url = ""#""+link_id; if (g_urls[link_id] != undefined) { url = g_urls[link_id]; if (g_titles[link_id] != undefined) { title = g_titles[link_id]; } } else { return whole_match; } } alt_text = alt_text.replace(/""/g,"""""); url = escapeCharacters(url,""*_""); var result = ""\\""""""; return result; } private static function _DoHeaders(text:String) { // Setext-style headers: // Header 1 // ======== // // Header 2 // -------- // text = text.replace(/^(.+)[ \\t]*\\n=+[ \\t]*\\n+/gm, function(wholeMatch,m1){return hashBlock(""

"" + _RunSpanGamut(m1) + ""

"");}); text = text.replace(/^(.+)[ \\t]*\\n-+[ \\t]*\\n+/gm, function(matchFound,m1){return hashBlock(""

"" + _RunSpanGamut(m1) + ""

"");}); // atx-style headers: // # Header 1 // ## Header 2 // ## Header 2 with closing hashes ## // ... // ###### Header 6 // /* text = text.replace(/ ^(\\#{1,6}) // $1 = string of #'s [ \\t]* (.+?) // $2 = Header text [ \\t]* \\#* // optional closing #'s (not counted) \\n+ /gm, function() {...}); */ text = text.replace(/^(\\#{1,6})[ \\t]*(.+?)[ \\t]*\\#*\\n+/gm, function(wholeMatch,m1,m2) { var h_level = m1.length; return hashBlock("""" + _RunSpanGamut(m2) + """"); }); return text; } private static function _DoLists(text) { // // Form HTML ordered (numbered) and unordered (bulleted) lists. // // attacklab: add sentinel to hack around khtml/safari bug: // http://bugs.webkit.org/show_bug.cgi?id=11231 text += ""~0""; // Re-usable pattern to match any entirel ul or ol list: /* var whole_list = / ( // $1 = whole list ( // $2 [ ]{0,3} // attacklab: g_tab_width - 1 ([*+-]|\\d+[.]) // $3 = first list item marker [ \\t]+ ) [^\\r]+? ( // $4 ~0 // sentinel for workaround; should be $ | \\n{2,} (?=\\S) (?! // Negative lookahead for another list item marker [ \\t]* (?:[*+-]|\\d+[.])[ \\t]+ ) ) )/g */ var whole_list = /^(([ ]{0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(~0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/gm; if (g_list_level) { text = text.replace(whole_list,function(wholeMatch,m1,m2) { var list = m1; var list_type = (m2.search(/[*+-]/g)>-1) ? ""ul"" : ""ol""; // Turn double returns into triple returns, so that we can make a // paragraph for the last item in a list, if necessary: list = list.replace(/\\n{2,}/g,""\\n\\n\\n"");; var result = _ProcessListItems(list); // Trim any trailing whitespace, to put the closing `` // up on the preceding line, to get it past the current stupid // HTML block parser. This is a hack to work around the terrible // hack that is the HTML block parser. result = result.replace(/\\s+$/,""""); result = ""<""+list_type+"">"" + result + ""\\n""; return result; }); } else { whole_list = /(\\n\\n|^\\n?)(([ ]{0,3}([*+-]|\\d+[.])[ \\t]+)[^\\r]+?(~0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.])[ \\t]+)))/g; text = text.replace(whole_list,function(wholeMatch,m1,m2,m3) { var runup = m1; var list = m2; var list_type = (m3.search(/[*+-]/g)>-1) ? ""ul"" : ""ol""; // Turn double returns into triple returns, so that we can make a // paragraph for the last item in a list, if necessary: var list = list.replace(/\\n{2,}/g,""\\n\\n\\n"");; var result = _ProcessListItems(list); result = runup + ""<""+list_type+"">\\n"" + result + ""\\n""; return result; }); } // attacklab: strip sentinel text = text.replace(/~0/,""""); return text; } private static function _ProcessListItems(list_str) { // // Process the contents of a single ordered or unordered list, splitting it // into individual list items. // // The $g_list_level global keeps track of when we're inside a list. // Each time we enter a list, we increment it; when we leave a list, // we decrement. If it's zero, we're not in a list anymore. // // We do this because when we're not inside a list, we want to treat // something like this: // // I recommend upgrading to version // 8. Oops, now this line is treated // as a sub-list. // // As a single paragraph, despite the fact that the second line starts // with a digit-period-space sequence. // // Whereas when we're inside a list (or sub-list), that line will be // treated as the start of a sub-list. What a kludge, huh? This is // an aspect of Markdown's syntax that's hard to parse perfectly // without resorting to mind-reading. Perhaps the solution is to // change the syntax rules such that sub-lists must start with a // starting cardinal number; e.g. ""1."" or ""a."". g_list_level++; // trim trailing blank lines: list_str = list_str.replace(/\\n{2,}$/,""\\n""); // attacklab: add sentinel to emulate \\z list_str += ""~0""; /* list_str = list_str.replace(/ (\\n)? // leading line = $1 (^[ \\t]*) // leading whitespace = $2 ([*+-]|\\d+[.]) [ \\t]+ // list marker = $3 ([^\\r]+? // list item text = $4 (\\n{1,2})) (?= \\n* (~0 | \\2 ([*+-]|\\d+[.]) [ \\t]+)) /gm, function(){...}); */ list_str = list_str.replace(/(\\n)?(^[ \\t]*)([*+-]|\\d+[.])[ \\t]+([^\\r]+?(\\n{1,2}))(?=\\n*(~0|\\2([*+-]|\\d+[.])[ \\t]+))/gm, function(wholeMatch,m1,m2,m3,m4){ var item = m4; var leading_line = m1; var leading_space = m2; if (leading_line || (item.search(/\\n{2,}/)>-1)) { item = _RunBlockGamut(_Outdent(item)); } else { // Recursion for sub-lists: item = _DoLists(_Outdent(item)); item = item.replace(/\\n$/,""""); // chomp(item) item = _RunSpanGamut(item); } return ""
  • "" + item + ""
  • \\n""; } ); // attacklab: strip sentinel list_str = list_str.replace(/~0/g,""""); g_list_level--; return list_str; } private static function _DoCodeBlocks(text:String) { // // Process Markdown `
    ` blocks.
    			//  
    			
    			/*
    			text = text.replace(text,
    			/(?:\\n\\n|^)
    			(								// $1 = the code block -- one or more lines, starting with a space/tab
    			(?:
    			(?:[ ]{4}|\\t)			// Lines must start with a tab or a tab-width of spaces - attacklab: g_tab_width
    			.*\\n+
    			)+
    			)
    			(\\n*[ ]{0,3}[^ \\t\\n]|(?=~0))	// attacklab: g_tab_width
    			/g,function(){...});
    			*/
    			
    			// attacklab: sentinel workarounds for lack of \\A and \\Z, safari\\khtml bug
    			text += ""~0"";
    			
    			text = text.replace(/(?:\\n\\n|^)((?:(?:[ ]{4}|\\t).*\\n+)+)(\\n*[ ]{0,3}[^ \\t\\n]|(?=~0))/g,
    				function(wholeMatch,m1,m2) {
    					var codeblock = m1;
    					var nextChar = m2;
    					
    					codeblock = _EncodeCode( _Outdent(codeblock));
    					codeblock = _Detab(codeblock);
    					codeblock = codeblock.replace(/^\\n+/g,""""); // trim leading newlines
    					codeblock = codeblock.replace(/\\n+$/g,""""); // trim trailing whitespace
    					
    					codeblock = ""
    "" + codeblock + ""\\n
    ""; return hashBlock(codeblock) + nextChar; } ); // attacklab: strip sentinel text = text.replace(/~0/,""""); return text; } private static function hashBlock(text) { text = text.replace(/(^\\n+|\\n+$)/g,""""); return ""\\n\\n~K"" + (g_html_blocks.push(text)-1) + ""K\\n\\n""; } private static function _DoCodeSpans(text:String) { // // * Backtick quotes are used for spans. // // * You can use multiple backticks as the delimiters if you want to // include literal backticks in the code span. So, this input: // // Just type ``foo `bar` baz`` at the prompt. // // Will translate to: // //

    Just type foo `bar` baz at the prompt.

    // // There's no arbitrary limit to the number of backticks you // can use as delimters. If you need three consecutive backticks // in your code, use four for delimiters, etc. // // * You can use spaces to get literal backticks at the edges: // // ... type `` `bar` `` ... // // Turns to: // // ... type `bar` ... // /* text = text.replace(/ (^|[^\\\\]) // Character before opening ` can't be a backslash (`+) // $2 = Opening run of ` ( // $3 = The code block [^\\r]*? [^`] // attacklab: work around lack of lookbehind ) \\2 // Matching closer (?!`) /gm, function(){...}); */ text = text.replace(/(^|[^\\\\])(`+)([^\\r]*?[^`])\\2(?!`)/gm, function(wholeMatch,m1,m2,m3,m4) { var c = m3; c = c.replace(/^([ \\t]*)/g,""""); // leading whitespace c = c.replace(/[ \\t]*$/g,""""); // trailing whitespace c = _EncodeCode(c); return m1+""""+c+""""; }); return text; } private static function _EncodeCode(text:String) { // // Encode/escape certain characters inside Markdown code runs. // The point is that in code, these characters are literals, // and lose their special Markdown meanings. // // Encode all ampersands; HTML entities are not // entities within a Markdown code span. text = text.replace(/&/g,""&""); // Do the angle bracket song and dance: text = text.replace(//g,"">""); // Now, escape characters that are magic in Markdown: text = escapeCharacters(text,""\\*_{}[]\\\\"",false); // jj the line above breaks this: //--- //* Item // 1. Subitem // special char: * //--- return text; } private static function _DoItalicsAndBold(text:String) { // must go first: text = text.replace(/(\\*\\*|__)(?=\\S)([^\\r]*?\\S[*_]*)\\1/g, ""$2""); text = text.replace(/(\\*|_)(?=\\S)([^\\r]*?\\S)\\1/g, ""$2""); return text; } private static function _DoBlockQuotes(text:String) { /* text = text.replace(/ ( // Wrap whole match in $1 ( ^[ \\t]*>[ \\t]? // '>' at the start of a line .+\\n // rest of the first line (.+\\n)* // subsequent consecutive lines \\n* // blanks )+ ) /gm, function(){...}); */ text = text.replace(/((^[ \\t]*>[ \\t]?.+\\n(.+\\n)*\\n*)+)/gm, function(wholeMatch,m1) { var bq = m1; // attacklab: hack around Konqueror 3.5.4 bug: // ""----------bug"".replace(/^-/g,"""") == ""bug"" bq = bq.replace(/^[ \\t]*>[ \\t]?/gm,""~0""); // trim one level of quoting // attacklab: clean up hack bq = bq.replace(/~0/g,""""); bq = bq.replace(/^[ \\t]+$/gm,""""); // trim whitespace-only lines bq = _RunBlockGamut(bq); // recurse bq = bq.replace(/(^|\\n)/g,""$1 ""); // These leading spaces screw with
     content, so we need to fix that:
    					bq = bq.replace(
    						/(\\s*
    [^\\r]+?<\\/pre>)/gm,
    						function(wholeMatch,m1) {
    							var pre = m1;
    							// attacklab: hack around Konqueror 3.5.4 bug:
    							pre = pre.replace(/^  /mg,""~0"");
    							pre = pre.replace(/~0/g,"""");
    							return pre;
    						});
    					
    					return hashBlock(""
    \\n"" + bq + ""\\n
    ""); }); return text; } private static function _FormParagraphs(text:String) { // // Params: // $text - string to process with html

    tags // // Strip leading and trailing lines: text = text.replace(/^\\n+/g,""""); text = text.replace(/\\n+$/g,""""); var grafs:Array = text.split(/\\n{2,}/g); var grafsOut:Array = new Array(); // // Wrap

    tags. // var end = grafs.length; for (var i=0; i= 0) { grafsOut.push(str); } else if (str.search(/\\S/) >= 0) { str = _RunSpanGamut(str); str = str.replace(/^([ \\t]*)/g,""

    ""); str += ""

    "" grafsOut.push(str); } } // // Unhashify HTML blocks // end = grafsOut.length; for (var i=0; i= 0) { var firstGroup:String = (/~K(\\d+)K/).exec(grafsOut[i])[1]; var blockText = g_html_blocks[firstGroup]; blockText = blockText.replace(/\\$/g,""$$$$""); // Escape any dollar signs grafsOut[i] = grafsOut[i].replace(/~K\\d+K/,blockText); } } return grafsOut.join(""\\n\\n""); } private static function _EncodeAmpsAndAngles(text:String) { // Smart processing for ampersands and angle brackets that need to be encoded. // Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin: // http://bumppo.net/projects/amputator/ text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)/g,""&""); // Encode naked <'s text = text.replace(/<(?![a-z\\/?\\$!])/gi,""<""); return text; } private static function _EncodeBackslashEscapes(text:String) { // // Parameter: String. // Returns: The string, with after processing the following backslash // escape sequences. // // attacklab: The polite way to do this is with the new // escapeCharacters() function: // // text = escapeCharacters(text,""\\\\"",true); // text = escapeCharacters(text,""`*_{}[]()>#+-.!"",true); // // ...but we're sidestepping its use of the (slow) RegExp constructor // as an optimization for Firefox. This function gets called a LOT. text = text.replace(/\\\\(\\\\)/g,escapeCharacters_callback); text = text.replace(/\\\\([`*_{}\\[\\]()>#+-.!])/g,escapeCharacters_callback); return text; } private static function _DoAutoLinks(text:String) { text = text.replace(/<((https?|ftp|dict):[^'"">\\s]+)>/gi,""$1""); // Email addresses: /* text = text.replace(/ < (?:mailto:)? ( [-.\\w]+ \\@ [-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+ ) > /gi, _DoAutoLinks_callback()); */ text = text.replace(/<(?:mailto:)?([-.\\w]+\\@[-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+)>/gi, function(wholeMatch,m1) { return _EncodeEmailAddress( _UnescapeSpecialChars(m1) ); } ); return text; } private static function _EncodeEmailAddress(addr:String) { // // Input: an email address, e.g. ""foo@example.com"" // // Output: the email address as a mailto link, with each character // of the address encoded as either a decimal or hex entity, in // the hopes of foiling most address harvesting spam bots. E.g.: // // foo // @example.com // // Based on a filter by Matthew Wickline, posted to the BBEdit-Talk // mailing list: // // attacklab: why can't javascript speak hex? function char2hex(ch:String) { var hexDigits = '0123456789ABCDEF'; var dec = ch.charCodeAt(0); return(hexDigits.charAt(dec>>4) + hexDigits.charAt(dec&15)); } var encode = [ function(ch){return ""&#""+ch.charCodeAt(0)+"";"";}, function(ch){return ""&#x""+char2hex(ch)+"";"";}, function(ch){return ch;} ]; addr = ""mailto:"" + addr; addr = addr.replace(/./g, function(ch) { if (ch == ""@"") { // this *must* be encoded. I insist. ch = encode[Math.floor(Math.random()*2)](ch); } else if (ch !="":"") { // leave ':' alone (to spot mailto: later) var r = Math.random(); // roughly 10% raw, 45% hex, 45% dec ch = ( r > .9 ? encode[2](ch) : r > .45 ? encode[1](ch) : encode[0](ch) ); } return ch; }); addr = """" + addr + """"; addr = addr.replace(/"">.+:/g,""\\"">""); // strip the mailto: from the visible part return addr; } private static function _UnescapeSpecialChars(text:String) { // // Swap back in all the special characters we've hidden. // text = text.replace(/~E(\\d+)E/g, function(wholeMatch,m1) { var charCodeToReplace = parseInt(m1); return String.fromCharCode(charCodeToReplace); } ); return text; } private static function _Outdent(text:String) { // // Remove one level of line-leading tabs or spaces // // attacklab: hack around Konqueror 3.5.4 bug: // ""----------bug"".replace(/^-/g,"""") == ""bug"" text = text.replace(/^(\\t|[ ]{1,4})/gm,""~0""); // attacklab: g_tab_width // attacklab: clean up hack text = text.replace(/~0/g,"""") return text; } private static function _Detab(text:String) { // attacklab: Detab's completely rewritten for speed. // In perl we could fix it by anchoring the regexp with \\G. // In javascript we're less fortunate. // expand first n-1 tabs text = text.replace(/\\t(?=\\t)/g,"" ""); // attacklab: g_tab_width // replace the nth with two sentinels text = text.replace(/\\t/g,""~A~B""); // use the sentinel to anchor our regex so it doesn't explode text = text.replace(/~B(.+?)~A/g, function(wholeMatch,m1,m2) { var leadingText = m1; var numSpaces = 4 - leadingText.length % 4; // attacklab: g_tab_width // there *must* be a better way to do this: for (var i=0; i; private var trackHighlightButtons: Vector.; private var markerComponents: Vector.; private var focusedThumbIndex: uint = 0; private var animatedThumb: SliderThumb; //------------------------------------------------------------------------------------------------- public function MultiThumbSliderBase() { super(); thumbs = new Vector.(); trackHighlightButtons = new Vector.(); markerComponents = new Vector.(); if(!newMinimum) minimum = DEFAULT_MINIMUM; if(!newMaximum) maximum = DEFAULT_MAXIMUM; this.addEventListener( FlexEvent.CREATION_COMPLETE, creationCompleteHandler ); } //------------------------------------------------------------------------------------------------- //------------------------------ PROPERTIES - START ------------------------------------------------------------------- private var minimumChanged: Boolean = false; private var newMinimum: Number; public function get minimum(): Number { if(minimumChanged) return newMinimum; else if(valueBasedLayout) return valueBasedLayout.minimum; else return 0; } public function set minimum(value: Number): void { if(value != minimum) { newMinimum = value; minimumChanged = true; invalidateProperties(); } } //------------------------------------------------------------------------------------------------- private var maximumChanged: Boolean = false; private var newMaximum: Number; public function get maximum(): Number { if(maximumChanged) return newMaximum; if(valueBasedLayout) return valueBasedLayout.maximum; else return 0; } public function set maximum(value: Number): void { if(value != maximum) { newMaximum = value; maximumChanged = true; invalidateProperties(); } } //------------------------------------------------------------------------------------------------- private var snapIntervalChanged: Boolean = false; private var _snapInterval: Number = DEFAULT_SNAP_INTERVAL; public function get snapInterval(): Number { return _snapInterval; } public function set snapInterval(value: Number): void { if(value != _snapInterval) { _snapInterval = value; snapIntervalChanged = true; invalidateProperties(); } } //------------------------------------------------------------------------------------------------- private var dataProviderChanged:Boolean; private var _dataProvider: IList = new ArrayCollection(); [Bindable(""dataProviderChanged"")] [Inspectable(category=""Data"")] public function get dataProvider():IList { return _dataProvider; } public function set dataProvider( value:IList ):void { if( value != _dataProvider ) { if (dataProvider) dataProvider.removeEventListener( CollectionEvent.COLLECTION_CHANGE, dataProvider_collectionChangeHandler ); _dataProvider = value; reactToDataProviderUpdate(); if (dataProvider) dataProvider.addEventListener( CollectionEvent.COLLECTION_CHANGE, dataProvider_collectionChangeHandler, false, 0, true ); dispatchEvent(new Event(""dataProviderChanged"")); dataProviderChanged = true; invalidateProperties(); } } //------------------------------------------------------------------------------------------------- private var markersChanged: Boolean = false; private var _markers: Array = new Array(); // Contains the values for which ""markers"" will be created on the track. // These will just be labels on the track, indicating the value at that point. // These markers will not be movable and their values will not be part of the ""values"" array. public function get markers(): Array { return _markers; } public function set markers(value: Array): void { if( value != _markers ) { _markers = value; markersChanged = true; invalidateProperties(); } } //------------------------------------------------------------------------------------------------- private var allowOverlapChanged: Boolean = false; private var _allowOverlap: Boolean = DEFAULT_ALLOW_OVERLAP; public function get allowOverlap(): Boolean { return _allowOverlap; } public function set allowOverlap(value: Boolean): void { if(value != _allowOverlap) { _allowOverlap = value; allowOverlapChanged = true; invalidateProperties(); } } //------------------------------------------------------------------------------------------------- private var _allowDuplicateValues: Boolean = true; public function get allowDuplicateValues(): Boolean { return _allowDuplicateValues; } public function set allowDuplicateValues(value: Boolean): void { if(value != _allowDuplicateValues) { _allowDuplicateValues = value; if( ! _allowDuplicateValues ) removeDataProviderDuplicateValues(); } } //------------------------------------------------------------------------------------------------- private var accentColorsChanged: Boolean = false; private var _accentColors:Array; [Bindable] public function get accentColors(): Array { return _accentColors; } public function set accentColors(colors:Array):void { _accentColors = colors; accentColorsChanged = true; invalidateProperties(); } //------------------------------------------------------------------------------------------------- private var showTrackHighlightChanged: Boolean = false; private var _showTrackHighlight:Boolean = true; [Bindable] public function get showTrackHighlight():Boolean { return _showTrackHighlight; } public function set showTrackHighlight(show:Boolean):void { _showTrackHighlight = show; showTrackHighlightChanged = true; invalidateProperties(); } //------------------------------------------------------------------------------------------------- private var _defaultTrackHighlightLabel: String = ""Label""; public function get defaultTrackHighlightLabel():String { return _defaultTrackHighlightLabel; } public function set defaultTrackHighlightLabel( value: String ):void { _defaultTrackHighlightLabel = value; } //------------------------------------------------------------------------------------------------- //---------------------------------- // valueField //---------------------------------- /** * @private */ private var _valueField:String = ""value""; /** * @private */ private var valueFieldChanged:Boolean; [Inspectable(category=""Data"", defaultValue=""value"")] /** * The name of the field in the data provider items to display * as the value. * * If valueField is set to an empty string (""""), no field will * be considered on the data provider to represent value. * * @default ""value"" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get valueField():String { return _valueField; } /** * @private */ public function set valueField(value:String):void { if (value == _valueField) return; _valueField = value; valueFieldChanged = true; invalidateProperties(); } //------------------------------------------------------------------------------------------------- //---------------------------------- // fixedValueField //---------------------------------- /** * @private */ private var _fixedValueField:String = ""fixedValue""; /** * @private */ private var fixedValueFieldChanged:Boolean; [Inspectable(category=""Data"", defaultValue=""fixedValue"")] /** * The name of the field in the data provider items to display * as the fixedValue. * * If fixedValueField is set to an empty string (""""), no field will * be considered on the data provider to represent fixedValue. * * @default ""fixedValue"" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get fixedValueField():String { return _fixedValueField; } /** * @private */ public function set fixedValueField(value:String):void { if (value == _fixedValueField) return; _fixedValueField = value; fixedValueFieldChanged = true; invalidateProperties(); } //------------------------------------------------------------------------------------------------- //---------------------------------- // labelField //---------------------------------- /** * @private */ private var _labelField:String = ""label""; /** * @private */ private var labelFieldChanged:Boolean; [Inspectable(category=""Data"", defaultValue=""label"")] /** * The name of the field in the data provider items to display * as the label. * * If labelField is set to an empty string (""""), no field will * be considered on the data provider to represent label. * * @default ""label"" * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get labelField():String { return _labelField; } /** * @private */ public function set labelField(value:String):void { if (value == _labelField) return; _labelField = value; labelFieldChanged = true; invalidateProperties(); } //------------------------------ PROPERTIES - END ------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- protected function creationCompleteHandler( event: FlexEvent ): void { // When the track highlights are created on initialization, the position and dimensions are set wrong // because the dimensions of the ""track"" component itself are not yet finalized. So, re-calculating the properties of the // track highlights when the track component has been fully created. for each( var track_highlight: SliderTrackHighlight in trackHighlightButtons ) { updateTrackHighlightDisplay( track_highlight ); } } //------------------------------------------------------------------------------------------------- override protected function partAdded(partName: String, instance: Object): void { super.partAdded( partName, instance ); if(partName == ""thumb"") { var instance_thumb: SliderThumb = SliderThumb( instance ); var slideDuration: Number = getStyle(""slideDuration""); instance_thumb.setStyle(""slideDuration"", slideDuration); instance_thumb.addEventListener(MouseEvent.MOUSE_DOWN, thumbMouseDownHandler); instance_thumb.addEventListener(ThumbMouseEvent.PRESS, thumbPressHandler); instance_thumb.addEventListener(ThumbKeyEvent.KEY_DOWN, thumbKeyDownHandler); instance_thumb.addEventListener(FlexEvent.VALUE_COMMIT, thumbValueCommitHandler); instance_thumb.addEventListener(ThumbEvent.ADD_THUMB_CLICKED, addThumb_clickHandler); instance_thumb.addEventListener(ThumbEvent.REMOVE_THUMB_CLICKED, removeThumb_clickHandler); instance_thumb.focusEnabled = true; } else if(partName == ""track"") { track.addEventListener(MouseEvent.MOUSE_DOWN, trackMouseDownHandler); track.focusEnabled = false; } else if(partName == ""trackHighlight"") { var instance_track_highlight: SliderTrackHighlight = SliderTrackHighlight( instance ); instance_track_highlight.addEventListener(ResizeEvent.RESIZE, trackHighlight_resizeHandler); instance_track_highlight.addEventListener( Event.CHANGE, trackHighlight_changeHandler); // track is only clickable if in mouse interactionMode if (getStyle(""interactionMode"") == InteractionMode.MOUSE) instance_track_highlight.addEventListener(MouseEvent.MOUSE_DOWN, trackHighlight_mouseDownHandler); } } //------------------------------------------------------------------------------------------------- override protected function partRemoved(partName: String, instance: Object): void { super.partRemoved(partName, instance); if(partName == ""thumb"") { var instance_thumb: SliderThumb = SliderThumb(instance); instance_thumb.removeEventListener(MouseEvent.MOUSE_DOWN, thumbMouseDownHandler); instance_thumb.removeEventListener(ThumbMouseEvent.PRESS, thumbPressHandler); instance_thumb.removeEventListener(ThumbKeyEvent.KEY_DOWN, thumbKeyDownHandler); instance_thumb.removeEventListener(FlexEvent.VALUE_COMMIT, thumbValueCommitHandler); instance_thumb.removeEventListener(ThumbEvent.ADD_THUMB_CLICKED, addThumb_clickHandler); instance_thumb.removeEventListener(ThumbEvent.REMOVE_THUMB_CLICKED, removeThumb_clickHandler); } else if(partName == ""track"") { var track: Button = Button(instance); track.removeEventListener(MouseEvent.MOUSE_DOWN, trackMouseDownHandler); } else if(partName == ""trackHighlight"") { var instance_track_highlight: SliderTrackHighlight = SliderTrackHighlight( instance ); instance_track_highlight.removeEventListener(MouseEvent.MOUSE_DOWN, trackHighlight_mouseDownHandler); instance_track_highlight.removeEventListener( Event.CHANGE, trackHighlight_changeHandler); instance_track_highlight.removeEventListener(ResizeEvent.RESIZE, trackHighlight_resizeHandler); } } //------------------------------------------------------------------------------------------------- /** * @private */ override public function styleChanged(styleProp:String):void { var anyStyle:Boolean = styleProp == null || styleProp == ""styleName""; super.styleChanged(styleProp); if (styleProp == ""showTrackHighlight"" || anyStyle) { showTrackHighlightChanged = true; invalidateProperties(); } if (styleProp == ""accentColors"" || anyStyle) { accentColorsChanged = true; invalidateProperties(); } invalidateDisplayList(); } //------------------------------------------------------------------------------------------------- override protected function commitProperties(): void { super.commitProperties(); if(dataProviderChanged || minimumChanged || maximumChanged || snapIntervalChanged || allowOverlapChanged) { if(valueBasedLayout) { if(minimumChanged) valueBasedLayout.minimum = newMinimum; if(maximumChanged) valueBasedLayout.maximum = newMaximum; } // Compare newValues to the existing values. // Add and remove thumbs accordingly. var currentValues: Vector. = getValuesFromThumbs(); for each( var current_value: Number in currentValues ) { // Check if the current value exists in the new thumbs array. // If not found, remove the thumb at the current value. if( -1 == newValues.indexOf( current_value ) ) removeThumbAt( current_value ); } for each( var dp_item: Object in dataProvider ) { var new_value: Number = Number( dp_item[ valueField ] ); // Check if the new value already exists in the existing thumbs array. // If not found, add the thumb at the new value. if( -1 == currentValues.indexOf( new_value ) ) { addThumbAt( dp_item ); } else { // If a thumb at the value already exists, then just update its properties. var thumb_component: SliderThumb = getThumbAtValue( new_value ); updateThumbProperties( thumb_component, dp_item ); } } if( contentGroupHighlight && trackHighlight ) { removeAllTrackHighlights(); createTrackHighlightsFromDataProvider(); } dispatchEvent(new FlexEvent(FlexEvent.VALUE_COMMIT)); minimumChanged = false; maximumChanged = false; snapIntervalChanged = false; dataProviderChanged = false; allowOverlapChanged = false; } if(thumbValueChanged && !animating && !isDraggingThumbWithLiveDraggingDisabled) { dispatchEvent(new Event(Event.CHANGE)); thumbValueChanged = false; } if( showTrackHighlightChanged ) { for each( var track_highlight: SliderTrackHighlight in trackHighlightButtons ) { track_highlight.visible = _showTrackHighlight; } showTrackHighlightChanged = false; } if( accentColorsChanged ) { for each( var _thl: SliderTrackHighlight in trackHighlightButtons ) { var data_provider_item: Object = _thl.dataProviderItem; var dp_value: Number = data_provider_item[ valueField ]; var index_of_dp_value: Number = newValues.indexOf( dp_value ); updateTrackHighlightColor( _thl, index_of_dp_value ); } accentColorsChanged = false; } if( markersChanged ) { if( contentGroupMarker && marker ) { removeAllMarkers(); createMarkersFrom( _markers ); } markersChanged = false; } } //------------------------------------------------------------------------------------------------- private function addThumbAt( dp_item: Object ): void { var thumb_component: SliderThumb = SliderThumb( createDynamicPartInstance(""thumb"") ); if( ! thumb_component ) throw new ArgumentError(""Thumb part must be of type "" + getQualifiedClassName(SliderThumb)); updateThumbProperties( thumb_component, dp_item ); var value: Number = Number( dp_item[ valueField ] ); thumb_component.value = value; addElement(thumb_component); thumbs.push(thumb_component); } //------------------------------------------------------------------------------------------------- private function updateThumbProperties( thumb_component: SliderThumb, dp_item: Object ): void { thumb_component.snapInterval = snapInterval; thumb_component.dataProviderItem = dp_item; var value: Number = Number( dp_item[ valueField ] ); var index_of_value: Number = newValues.indexOf( value ); // If the value is not a fixed_value. if( -1 == newFixedValues.indexOf( value ) ) { // If there is a neighboring thumb (previous) at a value lesser than this thumb, constrain this thumb to the previous thumb's value. if( index_of_value > 0 ) { var previous_value: Number = newValues[ index_of_value - 1 ]; var previous_thumb: SliderThumb = getThumbAtValue( previous_value ); if( previous_thumb ) thumb_component.constrainMinimumTo( previous_thumb, allowDuplicateValues ); else thumb_component.minimum = minimum; } else { thumb_component.minimum = minimum; } // If there is a neighboring thumb (next) at a value greater than this thumb, constrain this thumb to the next thumb's value. if( index_of_value < newValues.length - 1 ) { var next_value: Number = newValues[ index_of_value + 1 ]; var next_thumb: SliderThumb = getThumbAtValue( next_value ); if( next_thumb ) thumb_component.constrainMaximumTo( next_thumb, allowDuplicateValues ); else thumb_component.maximum = maximum; } else { thumb_component.maximum = maximum; } thumb_component.isValueFixed = false; } else { // If the value is a fixed value, then the max and min of the thumb should be the value itself. thumb_component.minimum = value; thumb_component.maximum = value; thumb_component.isValueFixed = true; } } //------------------------------------------------------------------------------------------------- private function createTrackHighlightsFromDataProvider(): void { for each( var dp_item: Object in dataProvider ) { var track_highlight: SliderTrackHighlight = SliderTrackHighlight( createDynamicPartInstance(""trackHighlight"") ); if( ! track_highlight ) throw new ArgumentError( ""Track highlight part must be of type "" + getQualifiedClassName(SliderTrackHighlight) ); track_highlight.value = dp_item[ valueField ]; track_highlight.dataProviderItem = dp_item; trackHighlightButtons.push( track_highlight ); // Update this track HL with the properties of the current DP item. updateTrackHighlightDisplay( track_highlight ); contentGroupHighlight.addElement( track_highlight ); } } //------------------------------------------------------------------------------------------------- /** * @protected */ protected function updateTrackHighlightDisplay( track_highlight: SliderTrackHighlight ):void { var dp_item: Object = track_highlight.dataProviderItem; var dp_value: Number = dp_item[ valueField ]; var index_of_dp_value: Number = newValues.indexOf( dp_value ); var _thumb: SliderThumb = getThumbAtValue( dp_value ); if( !_thumb || !track || !track_highlight ) return; var hl_x: Number; var hl_y: Number = 0; var hl_width: Number; var hl_height: Number = track.getLayoutBoundsHeight(); var track_width: Number = track.getLayoutBoundsWidth(); var range: Number = maximum - minimum; var thumb_track_x: Number; var thumb_global_position: Point; var parent_thumb_x: Number; // If first thumb. if( 0 == index_of_dp_value ) { hl_x = 0; // calculate thumb position. thumb_track_x = (range > 0) ? ((_thumb.value - minimum) / range) * track_width : 0; // convert to parent's coordinates. thumb_global_position = track.localToGlobal( new Point(thumb_track_x, 0) ); parent_thumb_x = _thumb.parent.globalToLocal( thumb_global_position ).x; hl_width = Math.round( parent_thumb_x ); } else { // Since newValues is sorted, the previous value would be at the previous index in the newValues vector. var previous_thumb_value: Number = newValues[ index_of_dp_value - 1]; var previous_thumb: SliderThumb = getThumbAtValue( previous_thumb_value ); // calculate previous thumb position. var previous_thumb_track_x: Number = (range > 0) ? ((previous_thumb.value - minimum) / range) * track_width : 0; // convert to parent's coordinates. var previous_thumb_global_position: Point = track.localToGlobal( new Point(previous_thumb_track_x, 0) ); var parent_previous_thumb_x: Number = previous_thumb.parent.globalToLocal( previous_thumb_global_position ).x; hl_x = parent_previous_thumb_x; // calculate thumb position. thumb_track_x = (range > 0) ? ((_thumb.value - minimum) / range) * track_width : 0; // convert to parent's coordinates. thumb_global_position = track.localToGlobal( new Point(thumb_track_x, 0) ); parent_thumb_x = _thumb.parent.globalToLocal( thumb_global_position ).x; hl_width = Math.round( parent_thumb_x - parent_previous_thumb_x ); } track_highlight.setLayoutBoundsPosition( hl_x, hl_y ); track_highlight.setLayoutBoundsSize( hl_width, hl_height ); updateTrackHighlightColor( track_highlight, index_of_dp_value ); track_highlight.visible = showTrackHighlight; if( dp_item.hasOwnProperty( labelField ) && dp_item[ labelField ] is String ) track_highlight.label = String( dp_item[ labelField ] ); else { dp_item[ labelField ] = defaultTrackHighlightLabel; track_highlight.label = defaultTrackHighlightLabel; } } //------------------------------------------------------------------------------------------------- protected function updateTrackHighlightColor( track_highlight: SliderTrackHighlight, index_of_dp_value: Number ): void { if( !track_highlight ) return; // Color of the track highlight var index_color_to_use: Number; if( index_of_dp_value <= accentColors.length - 1 ) index_color_to_use = index_of_dp_value; else index_color_to_use = index_of_dp_value % accentColors.length; track_highlight.setStyle( ""themeColor"", uint( accentColors[ index_color_to_use ] ) ); } //------------------------------------------------------------------------------------------------- private function createMarkersFrom(array_markers: Array): void { for(var index: int = 0; index < array_markers.length; index++) { var marker_component: SliderMarker = SliderMarker( createDynamicPartInstance(""marker"") ); if( ! marker_component ) throw new ArgumentError(""Slider Marker part must be of type "" + getQualifiedClassName( SliderMarker ) ); marker_component.value = array_markers[ index ]; markerComponents.push( marker_component ); contentGroupMarker.addElement( marker_component ); } } //------------------------------------------------------------------------------------------------- public function removeThumbAt( value: Number ): void { const _thumb: SliderThumb = getThumbAtValue( value ); if( ! _thumb ) throw new Error( ""No thumb found at "" + value ); removeThumb( _thumb ); } //------------------------------------------------------------------------------------------------- private function removeThumb( thumb_instance: SliderThumb ): void { removeDynamicPartInstance( ""thumb"", thumb_instance ); removeElement( thumb_instance ); const _index: Number = thumbs.indexOf( thumb_instance ); thumbs.splice( _index, 1 ); } //------------------------------------------------------------------------------------------------- private function removeAllTrackHighlights(): void { for each( var track_hl: SliderTrackHighlight in trackHighlightButtons ) { removeDynamicPartInstance( ""trackHighlight"", track_hl ); contentGroupHighlight.removeElement( track_hl ); } trackHighlightButtons.splice( 0, trackHighlightButtons.length ); } //------------------------------------------------------------------------------------------------- private function removeAllMarkers(): void { for each( var _marker: SliderMarker in markerComponents ) { removeDynamicPartInstance( ""marker"", _marker ); contentGroupMarker.removeElement( _marker ); } markerComponents.splice(0, markerComponents.length); } //------------------------------------------------------------------------------------------------- private function thumbPressHandler(event: ThumbMouseEvent): void { if(animating) animatedThumb.stopAnimation(); var thumb: SliderThumb = SliderThumb(event.currentTarget); // Store the delta between mouse pointer's position on thumb down and the current value of the thumb. // On dragging, this value is used to offset the new value, making it appear as // if the mouse pointer stays in the same position over the thumb. Can't trust the thumb's // own measurements here since it doesn't know how the layout is positioning it relative to its value. var thumbPressPoint: Point = contentGroup.globalToLocal(new Point(event.stageX, event.stageY)); var thumbPoint: Point = valueBasedLayout.valueToPoint(thumb.value); thumbPressOffset = new Point(thumbPoint.x - thumbPressPoint.x, thumbPoint.y - thumbPressPoint.y); thumb.addEventListener(ThumbMouseEvent.DRAGGING, thumbDraggingHandler); thumb.addEventListener(ThumbMouseEvent.RELEASE, thumbReleaseHandler); draggingThumb = true; dispatchChangeStart(); } //------------------------------------------------------------------------------------------------- private function thumbDraggingHandler(event: ThumbMouseEvent): void { var thumb: SliderThumb = SliderThumb(event.currentTarget); if(valueBasedLayout) { var draggedTo: Point = contentGroup.globalToLocal(new Point(event.stageX, event.stageY)); draggedTo.offset(thumbPressOffset.x, thumbPressOffset.y); thumb.value = valueBasedLayout.pointToValue(draggedTo); } } //------------------------------------------------------------------------------------------------- private function thumbReleaseHandler(event: ThumbMouseEvent): void { var thumb: SliderThumb = SliderThumb(event.currentTarget); thumb.removeEventListener(ThumbMouseEvent.DRAGGING, thumbDraggingHandler); thumb.removeEventListener(ThumbMouseEvent.RELEASE, thumbReleaseHandler); draggingThumb = false; dispatchChangeEnd(); invalidateThumbValues(); } //------------------------------------------------------------------------------------------------- private function thumbKeyDownHandler(event: ThumbKeyEvent): void { var thumb: SliderThumb = SliderThumb(event.currentTarget); if(animating) stopAnimation(); if(!keyDownOnThumb) { dispatchChangeStart(); keyDownOnThumb = true; thumb.addEventListener(ThumbKeyEvent.KEY_UP, thumbKeyUpHandler); } thumb.value = event.newValue; } //------------------------------------------------------------------------------------------------- private function thumbKeyUpHandler(event: ThumbKeyEvent): void { var thumb: SliderThumb = SliderThumb(event.currentTarget); dispatchChangeEnd(); keyDownOnThumb = false; thumb.removeEventListener(ThumbKeyEvent.KEY_UP, thumbKeyUpHandler); } //------------------------------------------------------------------------------------------------- private function thumbValueCommitHandler(event: FlexEvent): void { var _thumb: SliderThumb = SliderThumb( event.currentTarget ); if(!animating && !isDraggingThumbWithLiveDraggingDisabled) { invalidateThumbValues(); } if( _thumb.dataProviderItem && _thumb.dataProviderItem.hasOwnProperty( valueField ) ) { _thumb.dataProviderItem[ valueField ] = _thumb.value; dataProvider.itemUpdated( _thumb.dataProviderItem, valueField ); } // Constrain the neighboring thumbs only after the DP has been updated. // This is because the constrainNeighboringThumbs function uses the // newValues vector and it needs to be up-to-date. if(!allowOverlap && thumbs.length > 1) { constrainNeighboringThumbs( _thumb ); } contentGroup.invalidateDisplayList(); dispatchEvent( new MultiThumbSliderEvent( MultiThumbSliderEvent.VALUE_CHANGE ) ); } //------------------------------------------------------------------------------------------------- private function invalidateThumbValues(): void { if(!thumbValueChanged) { thumbValueChanged = true; invalidateProperties(); } } //------------------------------------------------------------------------------------------------- private function get isDraggingThumbWithLiveDraggingDisabled(): Boolean { return draggingThumb && !getStyle(""liveDragging""); } //------------------------------------------------------------------------------------------------- private function constrainNeighboringThumbs( thumb_component: SliderThumb ): void { var index_of_value: Number = newValues.indexOf( thumb_component.value ); var _thumb: SliderThumb; if( index_of_value > 0 ) { _thumb = getThumbAtValue( newValues[ index_of_value - 1 ] ); // If the thumb is a fixed_value thumb, then the constraints should not be messed with. if( _thumb && ! _thumb.isValueFixed ) _thumb.constrainMaximumTo( thumb_component, allowDuplicateValues ); } if( index_of_value < newValues.length - 1 ) { _thumb = getThumbAtValue( newValues[ index_of_value + 1 ] ); // If the thumb is a fixed_value thumb, then the constraints should not be messed with. if( _thumb && ! _thumb.isValueFixed ) _thumb.constrainMinimumTo( thumb_component, allowDuplicateValues ); } } //------------------------------------------------------------------------------------------------- private function trackMouseDownHandler(event: MouseEvent): void { if(valueBasedLayout) { var trackRelative: Point = track.globalToLocal(new Point(event.stageX, event.stageY)); var trackClickValue: Number = valueBasedLayout.pointToValue(trackRelative); var nearestThumb: SliderThumb = nearestThumbTo(trackClickValue); if( nearestThumb ) { if(getStyle(""slideDuration"") != 0) beginThumbAnimation(nearestThumb, trackClickValue); else nearestThumb.value = trackClickValue; } } } //------------------------------------------------------------------------------------------------- private function nearestThumbTo(value: Number): SliderThumb { var nearestValue: Number = valueBasedLayout.maximum; var nearestThumb: SliderThumb; for(var index: int = 0; index < thumbs.length; index++) { var thumb: SliderThumb = thumbs[index]; var valueDelta: Number = Math.abs(thumb.value - value); var valueInRange: Boolean = allowOverlap || (thumb.minimum <= value && thumb.maximum >= value); if(valueDelta < nearestValue && valueInRange) { nearestValue = valueDelta; nearestThumb = thumb; } } return nearestThumb; } //------------------------------------------------------------------------------------------------- private function beginThumbAnimation(thumb: SliderThumb, value: Number): void { if(animating) animatedThumb.stopAnimation(); animating = true; animatedThumb = thumb; animatedThumb.animateMovementTo(value, endAnimation); dispatchChangeStart(); } //------------------------------------------------------------------------------------------------- private function stopAnimation(): void { animatedThumb.stopAnimation(); endAnimation(); } //------------------------------------------------------------------------------------------------- private function endAnimation(): void { animatedThumb = null; animating = false; dispatchChangeEnd(); } //------------------------------------------------------------------------------------------------- private function addThumb_clickHandler( event: ThumbEvent ): void { const thumb_component: SliderThumb = SliderThumb( event.currentTarget ); var current_value: Number = thumb_component.value; var local_values: Vector. = ObjectUtil.copy( newValues.sort( Array.NUMERIC ) ) as Vector.; // To accommodate the new thumb, we may have to move some of the neighboring thumbs around. // To figure out in which direction we need to do the ""spreading out"", we first go in one // direction; if not successful, we then reset the changes of the first trial and try the other direction. // So, during these two ""trials"", we should not edit the actual dataProvider. We use a local copy. var local_data_provider: IList = ObjectUtil.copy( dataProvider ) as IList; const index_current_value: Number = local_values.indexOf( current_value ); var next_value: Number = local_values[ index_current_value + 1 ]; var gap_between_values: Number = next_value - current_value; var new_value: Number; var dp_item: Object; // The difference between the current and next values should be greater than // the snapInterval. Only then, we can insert another value between them. // NOTE: It is NOT enough if the gap is exactly the snapInterval, because we // are inserting a new thumb in this gap. // Contrastingly, in all other checks below, for all the other values, we are satisfied with // a gap of snapInterval, because we are not inserting a thumb in those gaps. if( gap_between_values <= snapInterval ) { // 1. Increment the next_value by snapInterval. // 2. Make sure that the new next_value and the value after it are separated // by at least snapInterval. // 3. If not, repeat (from step 1) for the value after the new next_value. // Before incrementing next_value, we also need to get the (local) DP item corresponding to it. // Even the value of the DP item should be incremented below. dp_item = getItemOfValue( next_value, local_data_provider ); next_value += snapInterval; if( next_value > maximum ) next_value = maximum; dp_item[ valueField ] = next_value; local_values[ index_current_value + 1 ] = next_value; var successfully_spread: Boolean = false; for( var i: Number = index_current_value + 1 ; i <= local_values.length - 1 ; i++ ) { var i_value: Number = local_values[ i ]; var i_plus_one_value: Number = ( i == local_values.length - 1 ) ? maximum : local_values[ i + 1 ]; // We are satisfied if the gap is at least snapInterval. if( i_plus_one_value - i_value >= snapInterval ) { successfully_spread = true; break; } else if( i == local_values.length - 1 ) { successfully_spread = false; break; } else { // Before incrementing i_plus_one_value, we also need to get the (local) DP item corresponding to it. // Even the value of the DP item should be incremented below. dp_item = getItemOfValue( i_plus_one_value, local_data_provider ); i_plus_one_value += snapInterval; if( i_plus_one_value > maximum ) i_plus_one_value = maximum; dp_item[ valueField ] = i_plus_one_value; local_values[ i + 1 ] = i_plus_one_value; } } if( ! successfully_spread ) { // Try spreading in the other direction. local_values = ObjectUtil.copy( newValues.sort( Array.NUMERIC ) ) as Vector.; local_data_provider = ObjectUtil.copy( dataProvider ) as IList; // Before decrementing current_value, we also need to get the (local) DP item corresponding to it. // Even the value of the DP item should be decremented below. dp_item = getItemOfValue( current_value, local_data_provider ); current_value -= snapInterval; if( current_value < minimum ) current_value = minimum; dp_item[ valueField ] = current_value; local_values[ index_current_value ] = current_value; for( var j: Number = index_current_value ; j >= 0 ; j-- ) { var j_value: Number = local_values[ j ]; var j_minus_one_value: Number = ( 0 == j ) ? minimum : local_values[ j - 1 ]; // We are satisfied if the gap is at least snapInterval. if( j_value - j_minus_one_value >= snapInterval ) { successfully_spread = true; break; } else if( 0 == j ) { successfully_spread = false; break; } else { // Before decrementing j_minus_one_value, we also need to get the (local) DP item corresponding to it. // Even the value of the DP item should be decremented below. dp_item = getItemOfValue( j_minus_one_value, local_data_provider ); j_minus_one_value -= snapInterval; if( j_minus_one_value < minimum ) j_minus_one_value = minimum; dp_item[ valueField ] = j_minus_one_value; local_values[ j - 1 ] = j_minus_one_value; } } if( ! successfully_spread ) { trace(""Can't insert new thumb because of lack of space.""); Alert.show( ""Sorry, no space for a new thumb!"", ""You have run out of thumbs!"" ); return; } } } current_value = local_values[ index_current_value ]; next_value = local_values[ index_current_value + 1 ]; gap_between_values = next_value - current_value; // The new value should be equi-distant between the two values. new_value = current_value + Math.round( gap_between_values / 2 ); var new_dp_item: Object = new Object(); new_dp_item[ valueField ] = new_value; new_dp_item[ labelField ] = defaultTrackHighlightLabel; local_data_provider.addItem( new_dp_item ); dataProvider = local_data_provider; var thumb_added_event: MultiThumbSliderEvent = new MultiThumbSliderEvent( MultiThumbSliderEvent.THUMB_ADDED, new_dp_item ); dispatchEvent( thumb_added_event ); } //------------------------------------------------------------------------------------------------- private function removeThumb_clickHandler( event: ThumbEvent ): void { const thumb_component: SliderThumb = SliderThumb( event.currentTarget ); // Make a copy of the thumb's DP item so it can be sent with the dispatched event. var data_provider_item: Object = ObjectUtil.copy( thumb_component.dataProviderItem ); dataProvider.removeItemAt( dataProvider.getItemIndex( thumb_component.dataProviderItem ) ); var thumb_removed_event: MultiThumbSliderEvent = new MultiThumbSliderEvent( MultiThumbSliderEvent.THUMB_REMOVED, data_provider_item ); dispatchEvent( thumb_removed_event ); } //------------------------------------------------------------------------------------------------- private function thumbMouseDownHandler(event: MouseEvent): void { visuallyMoveToFront(IVisualElement(event.currentTarget)); } //---------------------------------------Thumb Code - End---------------------------------------------------------- //-------------------------------------Track Highlight Code - Start------------------------------------------------------------ /** * @private */ private function trackHighlight_resizeHandler(event:Event):void { var track_highlight: SliderTrackHighlight = SliderTrackHighlight( event.currentTarget ); updateTrackHighlightDisplay( track_highlight ); } //------------------------------------------------------------------------------------------------- protected function trackHighlight_changeHandler( event: Event ): void { var track_highlight: SliderTrackHighlight = SliderTrackHighlight( event.currentTarget ); var dp_item: Object = track_highlight.dataProviderItem; dp_item[ labelField ] = track_highlight.label; dataProvider.itemUpdated( dp_item, labelField ); dispatchEvent( new MultiThumbSliderEvent( MultiThumbSliderEvent.LABEL_CHANGE ) ); } //------------------------------------------------------------------------------------------------- /** * @private * Handle mouse-down events for the slider track hightlight. We * calculate the value based on the new position and then * move the thumb to the correct location as well as * commit the value. */ protected function trackHighlight_mouseDownHandler(event:MouseEvent):void { trackMouseDownHandler(event); } //-------------------------------------Track Highlight Code - End------------------------------------------------------------ //------------------------------------------------------------------------------------------------- private function get valueBasedLayout(): IValueLayout { return (layout as IValueLayout); } //------------------------------------------------------------------------------------------------- private function getThumbAtValue( value: Number ): SliderThumb { var thumb_at_value: SliderThumb = null; for each( var _thumb: SliderThumb in thumbs ) { if( _thumb.value == value ) { thumb_at_value = _thumb; break; } } return thumb_at_value; } //------------------------------------------------------------------------------------------------- private function getTrackHighlightAtValue( value: Number ): SliderTrackHighlight { var track_highlight: SliderTrackHighlight = null; for each( var _thl: SliderTrackHighlight in trackHighlightButtons ) { if( _thl.value == value ) { track_highlight = _thl; break; } } return track_highlight; } //------------------------------------------------------------------------------------------------- private function getValuesFromThumbs(): Vector. { var thumbValues: Vector. = new Vector.(); for each( var _thumb: SliderThumb in thumbs ) { thumbValues.push( _thumb.value ); } return thumbValues.sort( Array.NUMERIC ); } //------------------------------------------------------------------------------------------------- private function visuallyMoveToFront(instance: IVisualElement): void { var lastIndexElement: IVisualElement = getElementAt(numElements - 1); if(instance != lastIndexElement) swapElements(instance, lastIndexElement); } //------------------------------------------------------------------------------------------------- private function dispatchChangeStart(): void { dispatchEvent(new FlexEvent(FlexEvent.CHANGE_START)); } //------------------------------------------------------------------------------------------------- private function dispatchChangeEnd(): void { dispatchEvent(new FlexEvent(FlexEvent.CHANGE_END)); } //------------------------------------------------------------------------------------------------- private function removeDataProviderDuplicateValues(): void { var duplicate_items: ArrayCollection = new ArrayCollection(); var vector_values: Vector. = new Vector.(); for each( var dp_item: Object in dataProvider ) { if( dp_item.hasOwnProperty( valueField ) && dp_item[ valueField ] is Number ) { var value: Number = Number( dp_item[ valueField ] ); if( -1 == vector_values.indexOf( value ) ) { vector_values.push( value ); } // If already seen - this is a duplicate item. else { duplicate_items.addItem( dp_item ); } } } // Remove duplicate items. for each( var duplicate_item: Object in duplicate_items ) { dataProvider.removeItemAt( dataProvider.getItemIndex( duplicate_item ) ); } } //------------------------------------------------------------------------------------------------- private function removeValuesOutOfBounds(): void { var items_out_of_bounds: ArrayCollection = new ArrayCollection(); for each( var dp_item: Object in dataProvider ) { if( dp_item.hasOwnProperty( valueField ) && dp_item[ valueField ] is Number ) { const _value: Number = Number( dp_item[ valueField ] ); if( _value < minimum || _value > maximum ) items_out_of_bounds.addItem( dp_item ); } } // Remove items out of bounds. for each( var item_out_of_bounds: Object in items_out_of_bounds ) { dataProvider.removeItemAt( dataProvider.getItemIndex( item_out_of_bounds ) ); } } //------------------------------------------------------------------------------------------------- private function getValuesFromDataProvider(): Vector. { var thumbValues: Vector. = new Vector.(); for each( var dp_item: Object in dataProvider ) { if( dp_item.hasOwnProperty( valueField ) && dp_item[ valueField ] is Number ) thumbValues.push( Number( dp_item[ valueField ] ) ); } return thumbValues.sort( Array.NUMERIC ); } //------------------------------------------------------------------------------------------------- private function getFixedValuesFromDataProvider(): Vector. { var fixed_values: Vector. = new Vector.(); for each( var dp_item: Object in dataProvider ) { if( ! dp_item.hasOwnProperty( fixedValueField ) || ( dp_item.hasOwnProperty( fixedValueField ) && ! (dp_item[ fixedValueField ] is Boolean) )) { dp_item[ fixedValueField ] = false; continue; } // If we reach this point, dp_item[ fixedValueField ] definitely exists. if( dp_item.hasOwnProperty( valueField ) && dp_item[ valueField ] is Number ) { var is_fixed_value: Boolean = Boolean( dp_item[ fixedValueField ] ); if( is_fixed_value ) fixed_values.push( Number( dp_item[ valueField ] ) ); } } return fixed_values.sort( Array.NUMERIC ); } //------------------------------------------------------------------------------------------------- private var newValues: Vector.; private var newFixedValues: Vector.; private function reactToDataProviderUpdate(): void { if( ! allowDuplicateValues ) removeDataProviderDuplicateValues(); removeValuesOutOfBounds(); newValues = getValuesFromDataProvider(); newFixedValues = getFixedValuesFromDataProvider(); } //------------------------------------------------------------------------------------------------- private function getTrackHighlightOfDataProviderItem( dp_item: Object ): SliderTrackHighlight { for each( var track_highlight: SliderTrackHighlight in trackHighlightButtons ) { if( dp_item == track_highlight.dataProviderItem ) return track_highlight; } return null; } //------------------------------------------------------------------------------------------------- private function getItemOfValue( value: Number, collection: IList ): Object { for each( var dp_item: Object in collection ) { if( dp_item.hasOwnProperty( valueField ) && dp_item[ valueField ] is Number ) { var dp_item_value: Number = Number( dp_item[ valueField ] ); if( value == dp_item_value ) return dp_item; } } return null; } //------------------------------------------------------------------------------------------------- /** * @private * Called when contents within the dataProvider changes. * * @param event The collection change event * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ protected function dataProvider_collectionChangeHandler( event: CollectionEvent ):void { // We need to temporarily disable the listener because in this handler we may make some updates to the // dataProvider (in ""reactToDataProviderUpdate"") which will further call the same events. It goes into // an endless loop. We will add the listener again at the end of this handler function. if (dataProvider) dataProvider.removeEventListener( CollectionEvent.COLLECTION_CHANGE, dataProvider_collectionChangeHandler ); var i: uint; switch (event.kind) { case CollectionEventKind.UPDATE: for each( var event_object: * in event.items ) { if (event_object is PropertyChangeEvent) { var property_change_event: PropertyChangeEvent = PropertyChangeEvent( event_object ); if( null != property_change_event ) { // Even if one valueField has been updated, refresh the slider. Hence the ""break"". if( valueField == property_change_event.property ) { reactToDataProviderUpdate(); dataProviderChanged = true; invalidateProperties(); break; } } } } break; default: reactToDataProviderUpdate(); dataProviderChanged = true; invalidateProperties(); } if (dataProvider) dataProvider.addEventListener( CollectionEvent.COLLECTION_CHANGE, dataProvider_collectionChangeHandler ); } //------------------------------------------------------------------------------------------------- } }",12390,False,2302.277922284171,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.controls.advancedDataGridClasses { /* import flash.display.DisplayObject; import flash.events.Event; */ import mx.controls.AdvancedDataGrid; import mx.controls.TextInput; import mx.controls.dataGridClasses.DataGridColumn; import mx.core.ClassFactory; import mx.core.IFactory; import mx.core.mx_internal; import mx.utils.StringUtil; import org.apache.royale.core.UIBase; import org.apache.royale.events.Event; use namespace mx_internal; //-------------------------------------- // Styles //-------------------------------------- //include ""../../styles/metadata/TextStyles.as""; /** * The background color of the column. * The default value is undefined, which means it uses the value of the * backgroundColor style of the associated AdvancedDataGrid control. * The default value for the AdvancedDataGrid control is 0xFFFFFF. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ [Style(name=""backgroundColor"", type=""uint"", format=""Color"", inherit=""no"")] /** * The name of a CSS style declaration for controlling other aspects of * the appearance of the column headers. * The default value is undefined, which means it uses the value of the * headerStyleName style of the associated AdvancedDataGrid control. * The default value for the AdvancedDataGrid control is * "".advancedDataGridStyles"". * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ [Style(name=""headerStyleName"", type=""String"", inherit=""no"")] /** * The number of pixels between the container's left border and its content * area. * There is no default value for this style. * An item renderer's setting of the paddingLeft property * is used to determine the default. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //[Style(name=""paddingLeft"", type=""Number"", format=""Length"", inherit=""no"")] /** * The number of pixels between the container's right border and its content * area. * There is no default value for this style. * An item renderer's setting of the paddingRight property * is used to determine the default. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //[Style(name=""paddingRight"", type=""Number"", format=""Length"", inherit=""no"")] /** * The AdvancedDataGridColumn class describes a column in an AdvancedDataGrid control. * There is one AdvancedDataGridColumn per displayable column, even if a column * is hidden or off-screen. * The data provider items of an AdvancedDataGrid control * can contain properties that are not displayed, * and therefore, do not need an AdvancedDataGridColumn. * An AdvancedDataGridColumn allows specification of the color and font of the text * in a column; specification of what kind of component displays the data for the column; * specification of whether the column is editable, sortable, or resizeable; * and specification of the text for the column header. * *

    Notes:

      *
    • An AdvancedDataGridColumn only holds information about a column; * it is not the parent of the item renderers in the column.
    • *
    • If you specify an AdvancedDataGridColumn class without a dataField * property, you must specify a sortCompareFunction * property. Otherwise, sort operations may cause run-time errors.
    *

    * * @mxml * *

    You use the <mx.AdvancedDataGridcolumn> tag to configure a column * of a AdvancedDataGrid control. * You specify the <mx.AdvancedDataGridcolumn> tag as a child * of the columns property in MXML. * The <mx.AdvancedDataGridcolumn> tag inherits all of the * tag attributes of its superclass, and adds the following tag attributes:

    * *
     *  <mx:AdvancedDataGridColumn
     *  Properties 
     *    dataField=""No default""
     *    dataTipField=""No default""
     *    dataTipFunction=""No default""
     *    editable=""true|false""
     *    editorDataField=""text""
     *    editorHeightOffset=""0""
     *    editorUsesEnterKey=""false|true""
     *    editorWidthOffset=""0""
     *    editorXOffset=""0""
     *    editorYOffset=""0""
     *    formatter=""null""
     *    headerRenderer=""AdvancedDataGridHeaderRenderer""
     *    headerText=""No default""
     *    headerWordWrap=""undefined""
     *    imeMode=""null""
     *    itemEditor=""TextInput""
     *    itemRenderer=""AdvancedDataGridItemRenderer""
     *    labelFunction=""No default""
     *    minWidth=""20""
     *    rendererIsEditor=""false|true""
     *    resizable=""true|false""
     *    showDataTips=""false|true""
     *    sortable=""true|false""
     *    sortCompareFunction=""No default""
     *    sortDescending=""false|true""
     *    styleFunction=""No default""
     *    visible=""true|false""
     *    width=""100""
     *    wordWrap=""false|true""
     * 
     *  Styles
     *    backgroundColor=""0xFFFFFF""
     *    color=""No default.""
     *    disabledColor=""0xAAB3B3""
     *    fontAntiAliasType=""advanced""
     *    fontFamily=""No default""
     *    fontGridFitType=""pixel""
     *    fontSharpness=""0""
     *    fontSize=""No default""
     *    fontStyle=""normal|italic""
     *    fontThickness=""0""
     *    fontWeight=""normal|bold""
     *    headerStyleName=""No default""
     *    kerning=""false|true""
     *    letterSpacing=""0""
     *    paddingLeft=""0""
     *    paddingRight=""0""
     *    textAlign=""right|center|left""
     *    textDecoration=""none|underline""
     *    textIndent=""0""
     *  />
     *  
    * * @see mx.controls.AdvancedDataGrid * * @see mx.styles.CSSStyleDeclaration * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 * @royalesuppresspublicvarwarning */ public class AdvancedDataGridColumn extends DataGridColumn {//extends CSSStyleDeclaration implements IIMESupport //include ""../../core/Version.as""; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- //---------------------------------- // embeddedFontRegistry //---------------------------------- // private static var noEmbeddedFonts:Boolean; /** * @private * Storage for the embeddedFontRegistry property. * This gets initialized on first access, * not at static initialization time, in order to ensure * that the Singleton registry has already been initialized. */ // private static var _embeddedFontRegistry:IEmbeddedFontRegistry; /** * @private * A reference to the embedded font registry. * Single registry in the system. * Used to look up the moduleFactory of a font. */ /* private static function get embeddedFontRegistry():IEmbeddedFontRegistry { if (!_embeddedFontRegistry && !noEmbeddedFonts) { try { _embeddedFontRegistry = IEmbeddedFontRegistry( Singleton.getInstance(""mx.core::IEmbeddedFontRegistry"")); } catch (e:Error) { noEmbeddedFonts = true; } } return _embeddedFontRegistry; } */ private static var _defaultItemEditorFactory:IFactory; mx_internal static function get defaultItemEditorFactory():IFactory { if (!_defaultItemEditorFactory) _defaultItemEditorFactory = new ClassFactory(TextInput); return _defaultItemEditorFactory; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param columnName The name of the field in the data provider * associated with the column, and the text for the header cell of this * column. This is equivalent to setting the dataField * and headerText properties. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public function AdvancedDataGridColumn(columnName:String = null) { super(columnName); /* if (columnName) { dataField = columnName; headerText = columnName; } */ } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- // mx_internal var list:UIBase; //BaseEx; /** * @private */ // mx_internal var explicitWidth:Number; /** * @private * Holds the last recorded value of the module factory used to create the font. */ // private var oldEmbeddedFontContext:IFlexModuleFactory = null; /** * @private * * true if font properties do not need to be set. */ // private var fontPropertiesSet:Boolean = false; /** * @private * True if createInFontContext has been called. */ // private var hasFontContextBeenSaved:Boolean = false; // preferred width is the number we should use when measuring // regular width will be changed if we shrink columns to fit. // mx_internal var preferredWidth:Number = 100; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- // ------------------------------------------------ // fontWeight // ------------------------------------------------ public function get fontWeight():String { return ""normal""; } public function set fontWeight(value:String):void { } // ------------------------------------------------ // fontSize // ------------------------------------------------ public function get fontSize():Number { return 11; } public function set fontSize(value:Number):void { } // ------------------------------------------------ // color // ------------------------------------------------ public function get color():uint { return 0x0B333C; } public function set color(value:uint):void { } //---------------------------------- // sortDescending //---------------------------------- /** * Indicates whether the column sort is * in ascending order, false, * or descending order, true. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ // public var sortDescending:Boolean = false; //---------------------------------- // dataTipField //---------------------------------- /** * @private * Storage for the dataTipField property. */ /* private var _dataTipField:String; [Bindable(""dataTipFieldChanged"")] [Inspectable(category=""Advanced"", defaultValue=""label"")] */ /** * The name of the field in the data provider to display as the data tip. * By default, the AdvancedDataGrid control looks for a property named * label on each data provider item and displays it. * However, if the data provider does not contain a label * property, you can set the dataTipField property to * specify a different property. * For example, you could set the value to ""FullName"" when a user views a * set of people's names included from a database. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function get dataTipField():String { return _dataTipField; } */ /** * @private */ /* public function set dataTipField(value:String):void { _dataTipField = value; if (owner) { owner.invalidateList(); } dispatchEvent(new Event(""dataTipChanged"")); } */ //---------------------------------- // dataTipFunction //---------------------------------- /** * @private * Storage for the dataTipFunction property. */ /* private var _dataTipFunction:Function; [Bindable(""dataTipFunctionChanged"")] [Inspectable(category=""Advanced"")] */ /** * Specifies a callback function to run on each item of the data provider * to determine its data tip. * This property is used by the itemToDataTip() method. * *

    By default, the control looks for a property named label * on each data provider item and displays it as its dataTip. * However, some data providers do not have a label property * or another property that you can use for displaying data * in the rows. * For example, you might have a data provider that contains a lastName * and firstName fields, but you want to display full names as the dataTip. * You can specify a function to the dataTipFunction property * that returns a single String containing the value of both fields. You * can also use the dataTipFunction property for handling * formatting and localization.

    * *

    The function must take a single Object parameter, and return a String. * For the header cell of a column, the Object parameter is of type AdvancedDataGridColumn. * For table cells, the Object parameter contains the data provider element for the cell.

    * *

    Shown below is an example implementation of the function. * For the header cell, return ""Column Name"". * For the table cells, return the name property of the Object:

    *
         *  private function tipFunc(value:Object):String
         *  {
         *      if (value is AdvancedDataGridColumn)
         *          return ""Column Name"";
         *                 
         *      // Use the 'name' property of the data provider element.
         *      return ""Name: "" + value[""name""];
         *  }
    * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function get dataTipFunction():Function { return _dataTipFunction; } */ /** * @private */ /* public function set dataTipFunction(value:Function):void { _dataTipFunction = value; if (owner) { owner.invalidateList(); } dispatchEvent(new Event(""labelFunctionChanged"")); } */ //---------------------------------- // draggable //---------------------------------- // [Inspectable(category=""General"")] /** * A flag that indicates whether the user is allowed to drag * the column to a new position * If true, the user can drag the * the column headers to a new position * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //public var draggable:Boolean = true; //---------------------------------- // editable //---------------------------------- //[Inspectable(category=""General"")] /** * A flag that indicates whether the items in the column are editable. * If true, and the AdvancedDataGrid's editable * property is also true, the items in a column are * editable and can be individually edited * by clicking an item or by navigating to the item with the * Tab and Arrow keys. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //public var editable:Boolean = true; //---------------------------------- // itemEditor //---------------------------------- //[Inspectable(category=""General"")] /** * A class factory for the instances of the item editor to use for the * column, when it is editable. * *

    The default value is the mx.controls.TextInput control.

    * * @see mx.controls.TextInput * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //public var itemEditor:IFactory = defaultItemEditorFactory; //---------------------------------- // editorDataField //---------------------------------- // [Inspectable(category=""General"")] /** * The name of the property of the item editor that contains the new * data for the list item. * For example, the default itemEditor is * TextInput, so the default value of the editorDataField * property is ""text"", which specifies the * text property of the TextInput control. * * @default ""text"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //public var editorDataField:String = ""text""; //---------------------------------- // editorHeightOffset //---------------------------------- [Inspectable(category=""General"", defaultValue=""0"")] /** * The height of the item editor, in pixels, relative to the size of the * item renderer. This property can be used to make the editor overlap * the item renderer by a few pixels to compensate for a border around the * editor. * Note that changing these values while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorHeightOffset:Number = 0; //---------------------------------- // editorWidthOffset //---------------------------------- //[Inspectable(category=""General"", defaultValue=""0"")] /** * The width of the item editor, in pixels, relative to the size of the * item renderer. This property can be used to make the editor overlap * the item renderer by a few pixels to compensate for a border around the * editor. * Note that changing these values while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorWidthOffset:Number = 0; //---------------------------------- // editorXOffset //---------------------------------- // [Inspectable(category=""General"", defaultValue=""0"")] /** * The x location of the upper-left corner of the item editor, * in pixels, relative to the upper-left corner of the item. * This property can be used to make the editor overlap * the item renderer by a few pixels to compensate for a border around the * editor. * Note that changing these values while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorXOffset:Number = 0; //---------------------------------- // editorYOffset //---------------------------------- //[Inspectable(category=""General"", defaultValue=""0"")] /** * The y location of the upper-left corner of the item editor, * in pixels, relative to the upper-left corner of the item. * This property can be used to make the editor overlap * the item renderer by a few pixels to compensate for a border around the * editor. * Note that changing these values while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorYOffset:Number = 0; //---------------------------------- // editorUsesEnterKey //---------------------------------- //[Inspectable(category=""General"", defaultValue=""false"")] /** * A flag that indicates whether the item editor uses Enter key. * If true the item editor uses the Enter key and the * AdvancedDataGrid will not look for the Enter key and move the editor in * response. * Note that changing this value while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorUsesEnterKey:Boolean = false; //---------------------------------- // headerRenderer //---------------------------------- /** * @private * Storage for the headerRenderer property. */ private var _headerRenderer:IFactory; [Bindable(""headerRendererChanged"")] [Inspectable(category=""Other"")] /** * The class factory for item renderer instances that display the * column header for the column. * You can specify a drop-in item renderer, * an inline item renderer, or a custom item renderer component as the * value of this property. * *

    The default item renderer is the AdvancedDataGridItemRenderer class, * which displays the item data as text.

    * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ override public function get headerRenderer():IFactory { return _headerRenderer; } /** * @private */ override public function set headerRenderer(value:IFactory):void { _headerRenderer = value; // rebuild the headers /* if (owner) { owner.invalidateList(); owner.columnRendererChanged(this); } dispatchEvent(new Event(""headerRendererChanged"")); */ } //---------------------------------- // headerWordWrap //---------------------------------- /** * @private * Storage for the headerWordWrap property. */ private var _headerWordWrap:*; [Inspectable(category=""Advanced"")] /** * Set to true to wrap the text in the column header * if it does not fit on one line. * If undefined, the AdvancedDataGrid control's wordWrap property * is used. * This property overrides the headerWordWrap property of * the AdvancedDataGrid control. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public function get headerWordWrap():* { return _headerWordWrap; } /** * @private */ public function set headerWordWrap(value:*):void { _headerWordWrap = value; /* if (owner) { owner.invalidateList(); } */ } //---------------------------------- // enableIME //---------------------------------- /** * A flag that indicates whether the IME should * be enabled when the component receives focus. * * If an editor is up, it will set enableIME * accordingly. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ /* public function get enableIME():Boolean { return false; } */ //---------------------------------- // imeMode //---------------------------------- /** * @private * Storage for the imeMode property. */ /* private var _imeMode:String; [Inspectable(category=""Other"")] */ /** * Specifies the IME (input method editor) mode. * The IME mode enables users to enter text in Chinese, Japanese, and Korean. * Flex sets the IME mode when the itemFocusIn event occurs, * and sets it back * to the previous value when the itemFocusOut event occurs. * The flash.system.IMEConversionMode class defines constants for * the valid values for this property. * *

    The default value is null, in which case it uses the value of the * AdvancedDataGrid control's imeMode property.

    * * @see flash.system.IMEConversionMode * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function get imeMode():String { return _imeMode; } */ /** * @private */ /* public function set imeMode(value:String):void { _imeMode = value; } */ /* //---------------------------------- // resizable //---------------------------------- [Inspectable(category=""General"")] /!** * Set to true if the user is allowed to resize * the width of the column. * If true, the user can drag the grid lines between * the column headers to resize the column. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public var resizable:Boolean = true; //---------------------------------- // showDataTips //---------------------------------- /!** * @private * Storage for the showDataTips property. *!/ private var _showDataTips:*; [Inspectable(category=""Advanced"")] /!** * Set to true to show data tips in the column. * If true, datatips are displayed for text in the rows. Datatips * are tooltips designed to show the text that is too long for the row. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public function get showDataTips():* { return _showDataTips; } /!** * @private *!/ public function set showDataTips(value:*):void { _showDataTips = value; /!* if (owner) { owner.invalidateList(); } *!/ } //---------------------------------- // sortable //---------------------------------- [Inspectable(category=""General"")] /!** * Set to true to indicate that the user can click on the * header of this column to sort the data provider. * If this property and the AdvancedDataGrid sortableColumns property * are both true, the AdvancedDataGrid control dispatches a * headerRelease event when a user releases the mouse button * on this column's header. * If no other handler calls the preventDefault() method on * the headerRelease event, the dataField * property or sortCompareFunction in the column is used * to reorder the items in the data provider. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public var sortable:Boolean = true; //---------------------------------- // sortCompareFunction //---------------------------------- /!** * @private * Storage for the sortCompareFunction property. *!/ private var _sortCompareFunction:Function; [Bindable(""sortCompareFunctionChanged"")] [Inspectable(category=""Advanced"")] /!** * * A callback function that gets called when sorting the data in * the column. If this property is not specified, the sort tries * to use a basic string or number sort on the data. * If the data is not a string or number or if the dataField * property is not a valid property of the data provider, the sort does * not work or will generate an exception. * If you specify a value of the labelFunction property, * you typically also provide a function to the sortCompareFunction property, * unless sorting is not allowed on this column. * That means you specify a function when the value from the column's dataField * does not sort in the same way as the computed value from the labelFunction property. * *

    The AdvancedDataGrid control uses this function to sort the elements of the data * provider collection. The function signature of * the callback function takes two parameters and has the following form:

    * *
    mySortCompareFunction(obj1:Object, obj2:Object):int 
    * *

    obj1 — A data element to compare.

    * *

    obj2 — Another data element to compare with obj1.

    * *

    The function should return a value based on the comparison * of the objects:

    *
      *
    • -1 if obj1 should appear before obj2 in ascending order.
    • *
    • 0 if obj1 = obj2.
    • *
    • 1 if obj1 should appear after obj2 in ascending order.
    • *
    * *

    Note: The obj1 and * obj2 parameters are entire data provider elements and not * just the data for the item.

    * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public function get sortCompareFunction():Function { return _sortCompareFunction; } /!** * @private *!/ public function set sortCompareFunction(value:Function):void { _sortCompareFunction = value; // dispatchEvent(new Event(""sortCompareFunctionChanged"")); } */ //---------------------------------- // sortCompareType //---------------------------------- /** * @private */ //private var _sortCompareType:String; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 11.8 * @playerversion AIR 3.8 * @productversion Flex 4.11 */ /* [Bindable(""sortCompareTypeChanged"")] public function get sortCompareType():String { return _sortCompareType; } */ /** * @private */ /* public function set sortCompareType(value:String):void { if (_sortCompareType != value) { _sortCompareType = value; dispatchEvent(new Event(""sortCompareTypeChanged"")); } } */ /* //---------------------------------- // visible //---------------------------------- /!** * @private * Storage for the visible property. *!/ private var _visible:Boolean = true; [Inspectable(category=""General"", defaultValue=""true"")] /!** * If true, the column is visible. * Set to false to hide the column. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public function get visible():Boolean { return _visible; } /!** * @private *!/ public function set visible(value:Boolean):void { if (_visible != value) { _visible = value; if (owner) { (owner as AdvancedDataGrid).columnsInvalid(); // columns invisible at init don't get a dataprovider so // force assignment by faking a dp change (owner as AdvancedDataGrid).model.dispatchEvent(new Event(""dataProviderChanged"")); //owner.invalidateProperties(); //owner.invalidateSize(); //owner.invalidateList(); } } }*/ //---------------------------------- // styleFunction //---------------------------------- /** * @private */ private var _styleFunction:Function; /** * A callback function that is called when rendering each cell. * The signature of the function should be: * *
    function myStyleFunction(data:Object, column:AdvancedDataGridColumn):Object
    * *

    data - data object associated with the item being rendered.

    *

    column - AdvancedDataGridColumn instance with * which the item renderer is associated.

    * *

    The return value should be a object with styles as properties * having the required values. * For example:

    * *
    { color:0xFF0000, fontWeight:""bold"" }
    * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public function get styleFunction():Function { return _styleFunction; } /** * @private */ public function set styleFunction(value:Function):void { _styleFunction = value; /* if (owner) owner.invalidateDisplayList(); */ } //---------------------------------- // formatter //---------------------------------- /** * @private */ //private var _formatter:IFormatter; /** * An instance of a subclasses of mx.formatters.Formatter. * The control use this class to format the column text. * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function get formatter():IFormatter { return _formatter; } */ /** * @private */ /* public function set formatter(value:IFormatter):void { _formatter = value; if (owner) owner.invalidateDisplayList(); } */ //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ /* override mx_internal function addStyleToProtoChain( chain:Object, target:DisplayObject, filterMap:Object = null):Object { var parentGrid:AdvancedDataGridBaseEx = owner; var item:IListItemRenderer = IListItemRenderer(target); chain = super.addStyleToProtoChain(chain, target); // If the target data is a AdvancedDataGridColumn and has a data // field in its data, then it is a header so add the // AdvancedDataGrid.headerStyleName object to the head of the proto chain. if (item.data && (item.data is AdvancedDataGridColumn)) { var s:Object; var headerStyleName:Object = parentGrid.getStyle(""headerStyleName""); if (headerStyleName) { if (headerStyleName is String) { chain = addStylesToProtoChain(String(headerStyleName), chain, target); } if (headerStyleName is CSSStyleDeclaration) chain = headerStyleName.addStyleToProtoChain(chain, target); } headerStyleName = getStyle(""headerStyleName""); if (headerStyleName) { if (headerStyleName is String) { chain = addStylesToProtoChain(String(headerStyleName), chain, target); } if (headerStyleName is CSSStyleDeclaration) chain = headerStyleName.addStyleToProtoChain(chain, target); } } // save the current font context if (!fontPropertiesSet) { fontPropertiesSet = true; saveFontContext(owner ? owner.moduleFactory : null); } return chain; } */ /** * @private */ /* override public function setStyle(styleProp:String, value:*):void { fontPropertiesSet = false; var oldValue:Object = getStyle(styleProp); var regenerate:Boolean = false; // If this AdvancedDataGridColumn didn't previously have a factory, defaultFactory, or // overrides object, then this AdvancedDataGridColumn hasn't been added to the item // renderers proto chains. In that case, we need to regenerate all the item // renderers proto chains. if (factory == null && defaultFactory == null && !overrides && (oldValue !== value)) // must be !== { regenerate = true; } super.setLocalStyle(styleProp, value); // The default implementation of setStyle won't always regenerate // the proto chain when headerStyleName is set, and we need to make sure // that they are regenerated if (styleProp == ""headerStyleName"") { if (owner) { owner.regenerateStyleCache(true); owner.notifyStyleChangeInChildren(""headerStyleName"", true); } return; } if (owner) { if (regenerate) { owner.regenerateStyleCache(true); } if (hasFontContextChanged(owner.moduleFactory)) { owner.columnRendererChanged(this); } owner.invalidateList(); } } */ /** * @private */ /* override public function get specificity():int { // Return 10 as there is a sorting mechanism based on specificity now // and there could be ancestor specificity also!! return 10; } */ //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Internal function to allow the AdvancedDataGrid to set the width of the * column without locking it as an explicitWidth mx_internal function setWidth(value:Number):void { _width = value; } */ /** * @private * * Apply column's Formatter if present. * */ /* private function applyFormatting(data:String):String { if (formatter != null && data != null) { var label:String = formatter.format(data); // Silently ignore formatter errors. For example, errors occur when // the property corresponding to the dataField is not present in the // row object i.e. it'll be empty and it's not anybody's fault that // it's an error. const mxFormatter:Formatter = formatter as Formatter; if (mxFormatter && mxFormatter.error) return null; return label; } else { return data; } } */ /** * Returns the String that the item renderer displays for the given data object. * If the AdvancedDataGridColumn or its AdvancedDataGrid control * has a non-null labelFunction * property, it applies the function to the data object. * Otherwise, the method extracts the contents of the field specified by the * dataField property, or gets the string value of the data object. * If the method cannot convert the parameter to a String, it returns a * single space. * * @param data Object to be rendered. * * @param withFormatting It true specifies to return * the String with any formatting applied to it. * * @return Displayable String based on the data. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function itemToLabel(data:Object, withFormatting:Boolean=true):String { var label:String = itemToLabelWithoutFormatting(data); if (withFormatting) return applyFormatting(label); return label; } */ /** * @private * * This is the original AdvancedDataGrid.itemToLabel() that has been wrapped with applyFormatting() * */ /* private function itemToLabelWithoutFormatting(data:Object):String { var headerInfo:AdvancedDataGridHeaderInfo = owner.mx_internal::getHeaderInfo(this); // In case of Column grouping, when a column has a parent with dataField/labelFunction set, this column is // supposed to take value from what its parent supplies it if (headerInfo != null && headerInfo.internalLabelFunction != null) data = headerInfo.internalLabelFunction(data, this); if (!data) return "" ""; if (labelFunction != null) return labelFunction(data, this); if (owner.labelFunction != null) return owner.labelFunction(data, this); if (typeof(data) == ""object"" || typeof(data) == ""xml"") { if (dataField != null && dataField in data) data = data[dataField]; else return "" ""; // stops ""[object Object]"" showing } if (data is String) return String(data); try { return data.toString(); } catch(e:Error) { } return "" ""; } */ /** * Returns a String that the item renderer displays as the data tip for the given data object, * based on the dataTipField and dataTipFunction properties. * If the method cannot convert the parameter to a String, it returns a * single space. * *

    This method is for use by developers who are creating subclasses * of the AdvancedDataGridColumn class. * It is not for use by application developers.

    * * @param data Object to be rendered. * * @return Displayable String based on the data. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function itemToDataTip(data:Object):String { if (dataTipFunction != null) return dataTipFunction(data); if (owner.dataTipFunction != null) return owner.dataTipFunction(data); // for header items, return the header text if (data is AdvancedDataGridColumn) return AdvancedDataGridColumn(data).headerText; if (typeof(data) == ""object"" || typeof(data) == ""xml"") { var field:String = dataTipField; if (!field) field = owner.dataTipField; if (field != null) { if (field in data && data[field] != null) data = data[field]; } else if (dataField != null) { if (dataField in data && data[dataField] != null) data = data[dataField]; else data = null; } } if (data is String) return String(data); try { return data.toString(); } catch(e:Error) { } return "" ""; } */ /** * @private * * Save the current font context to member fields. */ /* private function saveFontContext(flexModuleFactory:IFlexModuleFactory):void { // Save for hasFontContextChanged() hasFontContextBeenSaved = true; var fontName:String = StringUtil.trimArrayElements(getStyle(""fontFamily""), "",""); var fontWeight:String = getStyle(""fontWeight""); var fontStyle:String = getStyle(""fontStyle""); var bold:Boolean = fontWeight == ""bold""; var italic:Boolean = fontStyle == ""italic""; oldEmbeddedFontContext = (noEmbeddedFonts || !embeddedFontRegistry) ? null : embeddedFontRegistry.getAssociatedModuleFactory( fontName, bold, italic, this, flexModuleFactory, owner.systemManager); } */ /** * @private * Test if the current font context has changed * since that last time saveFontContext() was called. */ /* mx_internal function hasFontContextChanged( flexModuleFactory:IFlexModuleFactory):Boolean { // If the font has not been saved yet, then return false, // the font context has not changed. if (!hasFontContextBeenSaved) return false; var fontName:String = StringUtil.trimArrayElements(getStyle(""fontFamily""), "",""); var fontWeight:String = getStyle(""fontWeight""); var fontStyle:String = getStyle(""fontStyle""); // Check if the module factory has changed. var bold:Boolean = fontWeight == ""bold""; var italic:Boolean = fontStyle == ""italic""; var fontContext:IFlexModuleFactory = (noEmbeddedFonts || !embeddedFontRegistry) ? null : embeddedFontRegistry.getAssociatedModuleFactory( fontName, bold, italic, this, flexModuleFactory, owner.systemManager); return fontContext != oldEmbeddedFontContext; } */ /** * @private */ /* private function addStylesToProtoChain(styles:String, chain:Object, target:DisplayObject):Object { var styleNames:Array = styles.split(/\\s+/); for (var c:int=0; c < styleNames.length; c++) { if (styleNames[c].length) { var declaration:CSSStyleDeclaration = owner.styleManager.getMergedStyleDeclaration(""."" + styleNames[c]); if (declaration) chain = declaration.addStyleToProtoChain(chain, target); } } return chain; } */ /** * @private * * Sets the properties of this Object to the given column. * * It sets only the required properties. * * @param col AdvancedDataGridColumn in which the properties are to be set. * */ /* protected function copyProperties(col:AdvancedDataGridColumn):void { // copy properties col.defaultFactory = this.defaultFactory; col.editable = this.editable; col.editorDataField = this.editorDataField; col.editorHeightOffset = this.editorHeightOffset; col.editorUsesEnterKey = this.editorUsesEnterKey; col.editorWidthOffset = this.editorWidthOffset; col.editorXOffset = this.editorXOffset; col.editorYOffset = this.editorYOffset; col.factory = this.factory; col.itemEditor = this.itemEditor; col.rendererIsEditor = this.rendererIsEditor; col.resizable = this.resizable; col.sortable = this.sortable; col.sortDescending = this.sortDescending; col.dataField = this.dataField; col.dataTipField = this.dataTipField; col.dataTipFunction = this.dataTipFunction; col.formatter = this.formatter; col.headerRenderer = this.headerRenderer; col.headerText = this.headerText; col.headerWordWrap = this.headerWordWrap; col.imeMode = this.imeMode; col.itemRenderer = this.itemRenderer; col.labelFunction = this.labelFunction; col.minWidth = this.minWidth; col.showDataTips = this.showDataTips; col.sortCompareFunction = this.sortCompareFunction; col.styleFunction = this.styleFunction; col.visible = this.visible; col.width = this.width; col.wordWrap = this.wordWrap; // copy styles col.public::setStyle(""backgroundColor"",this.getStyle(""backgroundColor"")); col.public::setStyle(""headerStyleName"",this.getStyle(""headerStyleName"")); col.public::setStyle(""paddingLeft"",this.getStyle(""paddingLeft"")); col.public::setStyle(""paddingRight"",this.getStyle(""paddingRight"")); // copy text styles col.public::setStyle(""color"",this.getStyle(""color"")); col.public::setStyle(""disabledColor"",this.getStyle(""disabledColor"")); col.public::setStyle(""fontAntiAliasType"",this.getStyle(""fontAntiAliasType"")); col.public::setStyle(""fontFamily"",this.getStyle(""fontFamily"")); col.public::setStyle(""fontGridFitType"",this.getStyle(""fontGridFitType"")); col.public::setStyle(""fontSharpness"",this.getStyle(""fontSharpness"")); col.public::setStyle(""fontSize"",this.getStyle(""fontSize"")); col.public::setStyle(""fontStyle"",this.getStyle(""fontStyle"")); col.public::setStyle(""fontThickness"",this.getStyle(""fontThickness"")); col.public::setStyle(""fontWeight"",this.getStyle(""fontWeight"")); col.public::setStyle(""kerning"",this.getStyle(""kerning"")); col.public::setStyle(""letterSpacing"",this.getStyle(""letterSpacing"")); col.public::setStyle(""textAlign"",this.getStyle(""textAlign"")); col.public::setStyle(""textDecoration"",this.getStyle(""textDecoration"")); col.public::setStyle(""textIndent"",this.getStyle(""textIndent"")); } */ /** * * Clone this column and return a new Column with the * same properties and styles as this one. * * It does not set all the available properties * * @return col AdvancedDataGridColumn. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public function clone():AdvancedDataGridColumn { // make a new column var col:AdvancedDataGridColumn = new AdvancedDataGridColumn(); // copy the properties //copyProperties(col); return col; } } } ",12450,True,2639.4201577096264,median "// Use these for links to issue and pulls. Note issues and pulls redirect one to // each other on Github, so don't worry too much on using the right prefix. :issue: https://github.com/elastic/beats/issues/ :pull: https://github.com/elastic/beats/pull/ === Beats version HEAD https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD diff] ==== Breaking changes *Affecting all Beats* - Update to Golang 1.12.1. {pull}11330[11330] - Update to Golang 1.12.4. {pull}11782[11782] - Update to ECS 1.0.1. {pull}12284[12284] {pull}12317[12317] - Default of output.kafka.metadata.full is set to false by now. This reduced the amount of metadata to be queried from a kafka cluster. {pull}12738[12738] - Fixed a crash under Windows when fetching processes information. {pull}12833[12833] - Update to Golang 1.12.7. {pull}12931[12931] - Remove `in_cluster` configuration parameter for Kuberentes, now in-cluster configuration is used only if no other kubeconfig is specified {pull}13051[13051] - Disable Alibaba Cloud and Tencent Cloud metadata providers by default. {pull}13812[12812] - Libbeat HTTP's Server can listen to a unix socket using the `unix:///tmp/hello.sock` syntax. {pull}13655[13655] - Libbeat HTTP's Server can listen to a Windows named pipe using the `npipe:///hello` syntax. {pull}13655[13655] - By default, all Beats-created files and folders will have a umask of 0027 (on POSIX systems). {pull}14119[14119] - Adding new `Enterprise` license type to the licenser. {issue}14246[14246] - Change wording when we fail to load a CA file to the cert pool. {issue}14309[14309] - Allow Metricbeat's beat module to read monitoring information over a named pipe or unix domain socket. {pull}14558[14558] - Remove version information from default ILM policy for improved upgrade experience on custom policies. {pull}14745[14745] - Running `setup` cmd respects `setup.ilm.overwrite` setting for improved support of custom policies. {pull}14741[14741] - Libbeat: Do not overwrite agent.*, ecs.version, and host.name. {pull}14407[14407] *Auditbeat* - Auditd module: Normalized value of `event.category` field from `user-login` to `authentication`. {pull}11432[11432] - Auditd module: Unset `auditd.session` and `user.audit.id` fields are removed from audit events. {issue}11431[11431] {pull}11815[11815] - Socket dataset: Exclude localhost by default {pull}11993[11993] - Socket dataset: New implementation using Kprobes for finer-grained monitoring and UDP support. {pull}13058[13058] *Filebeat* - Add Filebeat Azure Dashboards {pull}14127[14127] - Add read_buffer configuration option. {pull}11739[11739] - `convert_timezone` option is removed and locale is always added to the event so timezone is used when parsing the timestamp, this behaviour can be overriden with processors. {pull}12410[12410] - Fix a race condition in the TCP input when close the client socket. {pull}13038[13038] - cisco/asa fileset: Renamed log.original to event.original and cisco.asa.list_id to cisco.asa.rule_name. {pull}13286[13286] - cisco/asa fileset: Fix parsing of 302021 message code. {pull}13476[13476] - google pubsub & httpjson inputs: HTTP User agent is now `Elastic-Heartbeat/Version` instead of `Elastic Heartbeat/Version` to stay RFC compliant. {pull}14748[14748] - CEF extensions are now mapped to the data types defined in the CEF guide. {pull}14342[14342] - Remove --machine-learning from setup subcommand. {pull}14705[14705] *Heartbeat* - Removed the `add_host_metadata` and `add_cloud_metadata` processors from the default config. These don't fit well with ECS for Heartbeat and were rarely used. - Fixed/altered redirect behavior. `max_redirects` now defaults to 0 (no redirects). Following redirects now works across hosts, but some timing fields will not be reported. {pull}14125[14125] - Removed `host.name` field that should never have been included. Heartbeat uses `observer.*` fields instead. {pull}14140[14140] - Changed default user-agent to be `Elastic-Heartbeat/VERSION (PLATFORM_INFO)` as the current default `Go-http-client/1.1` is often blacklisted. {pull}14291[14291] - JSON/Regex checks against HTTP bodies will only consider the first 100MiB of the HTTP body to prevent excessive memory usage. {pull}14223[pull] - Heartbeat now starts monitors scheduled with the '@every X' syntax instantaneously on startup, rather than waiting for the given interval to pass before running them. {pull}14890[14890] *Journalbeat* *Metricbeat* - Add new dashboards for Azure vms, vm guest metrics, vm scale sets {pull}14000[14000] - Add new Dashboard for PostgreSQL database stats {pull}13187[13187] - Add new dashboard for CouchDB database {pull}13198[13198] - Add new dashboard for Ceph cluster stats {pull}13216[13216] - Add new dashboard for Aerospike database stats {pull}13217[13217] - Add new dashboard for Couchbase cluster stats {pull}13212[13212] - Add new dashboard for Prometheus server stats {pull}13126[13126] - Add new dashboard for VSphere host cluster and virtual machine {pull}14135[14135] - Add new option `OpMultiplyBuckets` to scale histogram buckets to avoid decimal points in final events {pull}10994[10994] - system/raid metricset now uses /sys/block instead of /proc/mdstat for data. {pull}11613[11613] - kubernetes.container.cpu.limit.cores and kubernetes.container.cpu.requests.cores are now floats. {issue}11975[11975] - Add statistic option into cloudwatch metricset. If there is no statistic method specified, default is to collect Average, Sum, Maximum, Minimum and SampleCount. {issue}12370[12370] {pull}12840[12840] *Packetbeat* - Add support for mongodb opcode 2013 (OP_MSG). {issue}6191[6191] {pull}8594[8594] - NFSv4: Always use opname `ILLEGAL` when failed to match request to a valid nfs operation. {pull}11503[11503] *Winlogbeat* *Functionbeat* - Separate management and functions in Functionbeat. {pull}12939[12939] ==== Bugfixes *Affecting all Beats* - Make the behavior of clientWorker and netClientWorker consistent when error is returned from publisher pipeline - Fix a bug, publisher pipeline exits if output returns an error, irrespective of pipeline is closed or not - Fix typo in TLS renegotiation configuration and setting the option correctly {issue}10871[10871], {pull}12354[12354] - Ensure all beat commands respect configured settings. {pull}10721[10721] - Add missing fields and test cases for libbeat add_kubernetes_metadata processor. {issue}11133[11133], {pull}11134[11134] - decode_json_field: process objects and arrays only {pull}11312[11312] - decode_json_field: do not process arrays when flag not set. {pull}11318[11318] - Report faulting file when config reload fails. {pull}11304[11304] - Fix a typo in libbeat/outputs/transport/client.go by updating `c.conn.LocalAddr()` to `c.conn.RemoteAddr()`. {pull}11242[11242] - Management configuration backup file will now have a timestamps in their name. {pull}11034[11034] - [CM] Parse enrollment_token response correctly {pull}11648[11648] - Not hiding error in case of http failure using elastic fetcher {pull}11604[11604] - Escape BOM on JsonReader before trying to decode line {pull}11661[11661] - Fix matching of string arrays in contains condition. {pull}11691[11691] - Replace wmi queries with win32 api calls as they were consuming CPU resources {issue}3249[3249] and {issue}11840[11840] - Fix a race condition with the Kafka pipeline client, it is possible that `Close()` get called before `Connect()` . {issue}11945[11945] - Fix queue.spool.write.flush.events config type. {pull}12080[12080] - Fixed a memory leak when using the add_process_metadata processor under Windows. {pull}12100[12100] - Fix of docker json parser for missing ""log"" jsonkey in docker container's log {issue}11464[11464] - Fixed Beat ID being reported by GET / API. {pull}12180[12180] - Fixed setting bulk max size in kafka output. {pull}12254[12254] - Add host.os.codename to fields.yml. {pull}12261[12261] - Fix `@timestamp` being duplicated in events if `@timestamp` is set in a processor (or by any code utilizing `PutValue()` on a `beat.Event`). - Fix leak in script processor when using Javascript functions in a processor chain. {pull}12600[12600] - Add additional nil pointer checks to Docker client code to deal with vSphere Integrated Containers {pull}12628[12628] - Fixed `json.add_error_key` property setting for delivering error messages from beat events {pull}11298[11298] - Fix Central Management enroll under Windows {issue}12797[12797] {pull}12799[12799] - ILM: Use GET instead of HEAD when checking for alias to expose detailed error message. {pull}12886[12886] - Fix seccomp policy preventing some features to function properly on 32bit Linux systems. {issue}12990[12990] {pull}13008[13008] - Fix unexpected stops on docker autodiscover when a container is restarted before `cleanup_timeout`. {issue}12962[12962] {pull}13127[13127] - Fix install-service.ps1's ability to set Windows service's delay start configuration. {pull}13173[13173] - Fix some incorrect types and formats in field.yml files. {pull}13188[13188] - Load DLLs only from Windows system directory. {pull}13234[13234] {pull}13384[13384] - Fix mapping for kubernetes.labels and kubernetes.annotations in add_kubernetes_metadata. {issue}12638[12638] {pull}13226[13226] - Fix case insensitive regular expressions not working correctly. {pull}13250[13250] - Disable `add_kubernetes_metadata` if no matchers found. {pull}13709[13709] - Better wording for xpack beats when the _xpack endpoint is not reachable. {pull}13771[13771] - Recover from panics in the javascript process and log details about the failure to aid in future debugging. {pull}13690[13690] - Make the script processor concurrency-safe. {issue}13690[13690] {pull}13857[13857] - Kubernetes watcher at `add_kubernetes_metadata` fails with StatefulSets {pull}13905[13905] - Fix panics that could result from invalid TLS certificates. This can affect Beats that connect over TLS or Beats that accept connections over TLS and validate client certificates. {pull}14146[14146] - Support usage of custom builders without hints and mappers {pull}13839[13839] - Fix memory leak in kubernetes autodiscover provider and add_kubernetes_metadata processor happening when pods are terminated without sending a delete event. {pull}14259[14259] - Fix kubernetes `metaGenerator.ResourceMetadata` when parent reference controller is nil {issue}14320[14320] {pull}14329[14329] - Allow users to configure only `cluster_uuid` setting under `monitoring` namespace. {pull}14338[14338] - Fix bug with potential concurrent reads and writes from event.Meta map by Kafka output. {issue}14542[14542] {pull}14568[14568] *Auditbeat* - Process dataset: Fixed a memory leak under Windows. {pull}12100[12100] - Login dataset: Fix re-read of utmp files. {pull}12028[12028] - Package dataset: Fixed a crash inside librpm after Auditbeat has been running for a while. {issue}12147[12147] {pull}12168[12168] - Fix formatting of config files on macOS and Windows. {pull}12148[12148] - Fix direction of incoming IPv6 sockets. {pull}12248[12248] - Package dataset: Close librpm handle. {pull}12215[12215] - Package dataset: Auto-detect package directories. {pull}12289[12289] - Package dataset: Improve dpkg parsing. {pull}12325[12325] - System module: Start system module without host ID. {pull}12373[12373] - Host dataset: Fix reboot detection logic. {pull}12591[12591] - Add syscalls used by librpm for the system/package dataset to the default Auditbeat seccomp policy. {issue}12578[12578] {pull}12617[12617] - Process dataset: Do not show non-root warning on Windows. {pull}12740[12740] - Host dataset: Export Host fields to gob encoder. {pull}12940[12940] - Socket dataset: Fix start errors when IPv6 is disabled on the kernel. {issue}13953[13953] {pull}13966[13966] *Filebeat* - Add support for Cisco syslog format used by their switch. {pull}10760[10760] - Cover empty request data, url and version in Apache2 module{pull}10730[10730] - Fix registry entries not being cleaned due to race conditions. {pull}10747[10747] - Improve detection of file deletion on Windows. {pull}10747[10747] - Add missing Kubernetes metadata fields to Filebeat CoreDNS module, and fix a documentation error. {pull}11591[11591] - Reduce memory usage if long lines are truncated to fit `max_bytes` limit. The line buffer is copied into a smaller buffer now. This allows the runtime to release unused memory earlier. {pull}11524[11524] - Fix memory leak in Filebeat pipeline acker. {pull}12063[12063] - Fix goroutine leak caused on initialization failures of log input. {pull}12125[12125] - Fix goroutine leak on non-explicit finalization of log input. {pull}12164[12164] - Skipping unparsable log entries from docker json reader {pull}12268[12268] - Parse timezone in PostgreSQL logs as part of the timestamp {pull}12338[12338] - Load correct pipelines when system module is configured in modules.d. {pull}12340[12340] - Fix timezone offset parsing in system/syslog. {pull}12529[12529] - When TLS is configured for the TCP input and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584] - Apply `max_message_size` to incoming message buffer. {pull}11966[11966] - Syslog input will now omit the `process` object from events if it is empty. {pull}12700[12700] - Fix multiline pattern in Postgres which was too permissive {issue}12078[12078] {pull}13069[13069] - Allow path variables to be used in files loaded from modules.d. {issue}13184[13184] - Fix filebeat autodiscover fileset hint for container input. {pull}13296[13296] - Fix incorrect references to index patterns in AWS and CoreDNS dashboards. {pull}13303[13303] - Fix timezone parsing of system module ingest pipelines. {pull}13308[13308] - Fix timezone parsing of elasticsearch module ingest pipelines. {pull}13367[13367] - Change iis url path grok pattern from URIPATH to NOTSPACE. {issue}12710[12710] {pull}13225[13225] {issue}7951[7951] {pull}13378[13378] {pull}14754[14754] - Fix timezone parsing of nginx module ingest pipelines. {pull}13369[13369] - Fix incorrect field references in envoyproxy dashboard {issue}13420[13420] {pull}13421[13421] - Fixed early expiration of templates (Netflow v9 and IPFIX). {pull}13821[13821] - Fixed bad handling of sequence numbers when multiple observation domains were exported by a single device (Netflow V9 and IPFIX). {pull}13821[13821] - Fix timezone parsing of rabbitmq module ingest pipelines. {pull}13879[13879] - Fix conditions and error checking of date processors in ingest pipelines that use `event.timezone` to parse dates. {pull}13883[13883] - Fix timezone parsing of Cisco module ingest pipelines. {pull}13893[13893] - Fix timezone parsing of logstash module ingest pipelines. {pull}13890[13890] - cisco asa and ftd filesets: Fix parsing of message 106001. {issue}13891[13891] {pull}13903[13903] - Fix timezone parsing of iptables, mssql and panw module ingest pipelines. {pull}13926[13926] - Fix merging of fields specified in global scope with fields specified under an input's scope. {issue}3628[3628] {pull}13909[13909] - Fix delay in enforcing close_renamed and close_removed options. {issue}13488[13488] {pull}13907[13907] - Fix missing netflow fields in index template. {issue}13768[13768] {pull}13914[13914] - Fix cisco module's asa and ftd filesets parsing of domain names where an IP address is expected. {issue}14034[14034] - Fixed increased memory usage with large files when multiline pattern does not match. {issue}14068[14068] - panw module: Use geo.name instead of geo.country_iso_code for free-form location. {issue}13272[13272] - Fix azure fields names. {pull}14098[14098] - Fix calculation of `network.bytes` and `network.packets` for bi-directional netflow events. {pull}14111[14111] - Accept '-' as http.response.body.bytes in apache module. {pull}14137[14137] - Fix timezone parsing of MySQL module ingest pipelines. {pull}14130[14130] - Improve error message in s3 input when handleSQSMessage failed. {pull}14113[14113] - Close chan of Closer first before calling callback {pull}14231[14231] - Fix race condition in S3 input plugin. {pull}14359[14359] - Decode hex values in auditd module. {pull}14471[14471] - Fix parse of remote addresses that are not IPs in nginx logs. {pull}14505[14505] - Fix handling multiline log entries in nginx module. {issue}14349[14349] {pull}14499[14499] - Fix parsing of Elasticsearch node name by `elasticsearch/slowlog` fileset. {pull}14547[14547] - cisco/asa fileset: Fix parsing of 302021 message code. {pull}14519[14519] - Fix filebeat azure dashboards, event category should be `Alert`. {pull}14668[14668] - Update Logstash module's Grok patterns to support Logstash 7.4 logs. {pull}14743[14743] - Fix a problem in Filebeat input httpjson where interval is not used as time.Duration. {issue}14752[14752] {pull}14753[14753] - Fix SSL config in input.yml for Filebeat httpjson input in the MISP module. {pull}14767[14767] *Heartbeat* - Fix NPEs / resource leaks when executing config checks. {pull}11165[11165] - Fix duplicated IPs on `mode: all` monitors. {pull}12458[12458] - Fix integer comparison on JSON responses. {pull}13348[13348] - Fix storage of HTTP bodies to work when JSON/Regex body checks are enabled. {pull}14223[14223] - Fix recording of SSL cert metadata for Expired/Unvalidated x509 certs. {pull}13687[13687] - The heartbeat scheduler no longer drops scheduled items when under very high load causing missed deadlines. {pull}14890[14890] *Journalbeat* - Use backoff when no new events are found. {pull}11861[11861] - Iterate over journal correctly, so no duplicate entries are sent. {pull}12716[12716] - Preserve host name when reading from remote journal. {pull}12714[12714] *Metricbeat* - Change diskio metrics retrieval method (only for Windows) from wmi query to DeviceIOControl function using the IOCTL_DISK_PERFORMANCE control code {pull}11635[11635] - Call GetMetricData api per region instead of per instance. {issue}11820[11820] {pull}11882[11882] - Update documentation with cloudwatch:ListMetrics permission. {pull}11987[11987] - Check permissions in system socket metricset based on capabilities. {pull}12039[12039] - Get process information from sockets owned by current user when system socket metricset is run without privileges. {pull}12039[12039] - Avoid generating hints-based configuration with empty hosts when no exposed port is suitable for the hosts hint. {issue}8264[8264] {pull}12086[12086] - Fixed a socket leak in the postgresql module under Windows when SSL is disabled on the server. {pull}11393[11393] - Change some field type from scaled_float to long in aws module. {pull}11982[11982] - Fixed RabbitMQ `queue` metricset gathering when `consumer_utilisation` is set empty at the metrics source {pull}12089[12089] - Fix direction of incoming IPv6 sockets. {pull}12248[12248] - Refactored Windows perfmon metricset: replaced method to retrieve counter paths with PdhExpandWildCardPathW, separated code by responsibility, removed unused functions {pull}12212[12212] - Validate that kibana/status metricset cannot be used when xpack is enabled. {pull}12264[12264] - Ignore prometheus metrics when their values are NaN or Inf. {pull}12084[12084] {issue}10849[10849] - In the kibana/stats metricset, only log error (don't also index it) if xpack is enabled. {pull}12265[12265] - Fix an issue listing all processes when run under Windows as a non-privileged user. {issue}12301[12301] {pull}12475[12475] - The `elasticsearch/index_summary` metricset gracefully handles an empty Elasticsearch cluster when `xpack.enabled: true` is set. {pull}12489[12489] {issue}12487[12487] - When TLS is configured for the http metricset and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584] - Reuse connections in PostgreSQL metricsets. {issue}12504[12504] {pull}12603[12603] - PdhExpandWildCardPathW will not expand counter paths in 32 bit windows systems, workaround will use a different function. {issue}12590[12590] {pull}12622[12622] - In the elasticsearch/node_stats metricset, if xpack is enabled, make parsing of ES node load average optional as ES on Windows doesn't report load average. {pull}12866[12866] - Ramdisk is not filtered out when collecting disk performance counters in diskio metricset {issue}12814[12814] {pull}12829[12829] - Fix incoherent behaviour in redis key metricset when keyspace is specified both in host URL and key pattern {pull}12913[12913] - Fix connections leak in redis module {pull}12914[12914] {pull}12950[12950] - Fix wrong uptime reporting by system/uptime metricset under Windows. {pull}12915[12915] - Print errors that were being omitted in vSphere metricsets. {pull}12816[12816] - Fix redis key metricset dashboard references to index pattern. {pull}13303[13303] - Check if fields in DBInstance is nil in rds metricset. {pull}13294[13294] {issue}13037[13037] - Fix silent failures in kafka and prometheus module. {pull}13353[13353] {issue}13252[13252] - Fix issue with aws cloudwatch module where dimensions and/or namespaces that contain space are not being parsed correctly {pull}13389[13389] - Fix panic in Redis Key metricset when collecting information from a removed key. {pull}13426[13426] - Fix module-level fields in Kubernetes metricsets. {pull}13433[13433] {pull}13544[13544] - Fix reporting empty events in cloudwatch metricset. {pull}13458[13458] - Fix `docker.cpu.system.pct` calculation by using the reported number online cpus instead of the number of metrics per cpu. {pull}13691[13691] - Fix rds metricset dashboard. {pull}13721[13721] - Ignore prometheus untyped metrics with NaN value. {issue}13750[13750] {pull}13790[13790] - Change kubernetes.event.message to text. {pull}13964[13964] - Fix performance counter values for windows/perfmon metricset. {issue}14036[14036] {pull}14039[14039] - Add FailOnRequired when applying schema and fix metric names in mongodb metrics metricset. {pull}14143[14143] - Change `server_status_path` default setting for nginx module {issue}13806[13806] {pull}14099[14099] - Convert increments of 100 nanoseconds/ticks to milliseconds for WriteTime and ReadTime in diskio metricset (Windows) for consistency. {issue}14233[14233] - Limit some of the error messages to the logs only {issue}14317[14317] {pull}14327[14327] - Convert indexed ms-since-epoch timestamp fields in `elasticsearch/ml_job` metricset to ints from float64s. {issue}14220[14220] {pull}14222[14222] - Fix ARN parsing function to work for ELB ARNs. {pull}14316[14316] - Update azure configuration example. {issue}14224[14224] - Fix cloudwatch metricset with names and dimensions in config. {issue}14376[14376] {pull}14391[14391] - Fix marshaling of ms-since-epoch values in `elasticsearch/cluster_stats` metricset. {pull}14378[14378] - Fix checking tagsFilter using length in cloudwatch metricset. {pull}14525[14525] - Log bulk failures from bulk API requests to monitoring cluster. {issue}14303[14303] {pull}14356[14356] - Fixed bug with `elasticsearch/cluster_stats` metricset not recording license expiration date correctly. {issue}14541[14541] {pull}14591[14591] - Fix regular expression to detect instance name in perfmon metricset. {issue}14273[14273] {pull}14666[14666] - Vshpere module splits `virtualmachine.host` into `virtualmachine.host.id` and `virtualmachine.host.hostname`. {issue}7187[7187] {pull}7213[7213] - Fixed bug with `elasticsearch/cluster_stats` metricset not recording license ID in the correct field. {pull}14592[14592] - Fix perfmon expanding counter path/adding counter to query when OS language is not english. {issue}14684[14684] {pull}14800[14800] - Add extra check on `ignore_non_existent_counters` flag if the PdhExpandWildCardPathW returns no errors but does not expand the counter path successfully in windows/perfmon metricset. {pull}14797[14797] - Fix rds metricset from reporting same values for different instances. {pull}14702[14702] - Closing handler after verifying the registry key in diskio metricset. {issue}14683[14683] {pull}14759[14759] - Fix docker network stats when multiple interfaces are configured. {issue}14586[14586] {pull}14825[14825] - Fix ListMetrics pagination in aws module. {issue}14926[14926] {pull}14942[14942] *Packetbeat* - Prevent duplicate packet loss error messages in HTTP events. {pull}10709[10709] - Fixed a memory leak when using process monitoring under Windows. {pull}12100[12100] - Improved debug logging efficiency in PGQSL module. {issue}12150[12150] - Limit memory usage of Redis replication sessions. {issue}12657[12657] - Fix parsing the extended RCODE in the DNS parser. {pull}12805[12805] - Fix parsing of the HTTP host header when it contains a port or an IPv6 address. {pull}14215[14215] *Winlogbeat* - Fix data race affecting config validation at startup. {issue}13005[13005] - Set host.name to computername in Windows event logs & sysmon. Requires {pull}14407[14407] in libbeat to work {issue}13706[13706] *Functionbeat* - Fix function name reference for Kinesis streams in CloudFormation templates {pull}11646[11646] - Fix Cloudwatch logs timestamp to use timestamp of the log record instead of when the record was processed {pull}13291[13291] - Look for the keystore under the correct path. {pull}13332[13332] ==== Added *Affecting all Beats* - Decouple Debug logging from fail_on_error logic for rename, copy, truncate processors {pull}12451[12451] - Add an option to append to existing logs rather than always rotate on start. {pull}11953[11953] - Add `network` condition to processors for matching IP addresses against CIDRs. {pull}10743[10743] - Add if/then/else support to processors. {pull}10744[10744] - Add `community_id` processor for computing network flow hashes. {pull}10745[10745] - Add output test to kafka output {pull}10834[10834] - Gracefully shut down on SIGHUP {pull}10704[10704] - New processor: `copy_fields`. {pull}11303[11303] - Add `error.message` to events when `fail_on_error` is set in `rename` and `copy_fields` processors. {pull}11303[11303] - New processor: `truncate_fields`. {pull}11297[11297] - Allow a beat to ship monitoring data directly to an Elasticsearch monitoring cluster. {pull}9260[9260] - Updated go-seccomp-bpf library to v1.1.0 which updates syscall lists for Linux v5.0. {pull}11394[11394] - Add `add_observer_metadata` processor. {pull}11394[11394] - Add `decode_csv_fields` processor. {pull}11753[11753] - Add `convert` processor for converting data types of fields. {issue}8124[8124] {pull}11686[11686] - New `extract_array` processor. {pull}11761[11761] - Add number of goroutines to reported metrics. {pull}12135[12135] - Add `proxy_disable` output flag to explicitly ignore proxy environment variables. {issue}11713[11713] {pull}12243[12243] - Processor `add_cloud_metadata` adds fields `cloud.account.id` and `cloud.image.id` for AWS EC2. {pull}12307[12307] - Add configurable bulk_flush_frequency in kafka output. {pull}12254[12254] - Add `decode_base64_field` processor for decoding base64 field. {pull}11914[11914] - Add support for reading the `network.iana_number` field by default to the community_id processor. {pull}12701[12701] - Add aws overview dashboard. {issue}11007[11007] {pull}12175[12175] - Add `decompress_gzip_field` processor. {pull}12733[12733] - Add `timestamp` processor for parsing time fields. {pull}12699[12699] - Fail with error when autodiscover providers have no defined configs. {pull}13078[13078] - Add a check so alias creation explicitely fails if there is an index with the same name. {pull}13070[13070] - Update kubernetes watcher to use official client-go libraries. {pull}13051[13051] - Add support for unix epoch time values in the `timestamp` processor. {pull}13319[13319] - add_host_metadata is now GA. {pull}13148[13148] - Add an `ignore_missing` configuration option the `drop_fields` processor. {pull}13318[13318] - add_host_metadata is no GA. {pull}13148[13148] - Add `registered_domain` processor for deriving the registered domain from a given FQDN. {pull}13326[13326] - Add support for RFC3339 time zone offsets in JSON output. {pull}13227[13227] - Add autodetection mode for add_docker_metadata and enable it by default in included configuration files{pull}13374[13374] - Added `monitoring.cluster_uuid` setting to associate Beat data with specified ES cluster in Stack Monitoring UI. {pull}13182[13182] - Add autodetection mode for add_kubernetes_metadata and enable it by default in included configuration files. {pull}13473[13473] - Add `providers` setting to `add_cloud_metadata` processor. {pull}13812[13812] - Use less restrictive API to check if template exists. {pull}13847[13847] - Do not check for alias when setup.ilm.check_exists is false. {pull}13848[13848] - Add support for numeric time zone offsets in timestamp processor. {pull}13902[13902] - Add condition to the config file template for add_kubernetes_metadata {pull}14056[14056] - Marking Central Management deprecated. {pull}14018[14018] - Add `keep_null` setting to allow Beats to publish null values in events. {issue}5522[5522] {pull}13928[13928] - Add shared_credential_file option in aws related config for specifying credential file directory. {issue}14157[14157] {pull}14178[14178] - GA the `script` processor. {pull}14325[14325] - Add `fingerprint` processor. {issue}11173[11173] {pull}14205[14205] - Add support for API keys in Elasticsearch outputs. {pull}14324[14324] - Ensure that init containers are no longer tailed after they stop {pull}14394[14394] - Add consumer_lag in Kafka consumergroup metricset {pull}14822[14822] - Make use of consumer_lag in Kafka dashboard {pull}14863[14863] - Refactor kubernetes autodiscover to enable different resource based discovery {pull}14738[14738] *Auditbeat* - Auditd module: Add `event.outcome` and `event.type` for ECS. {pull}11432[11432] - Process: Add file hash of process executable. {pull}11722[11722] - Socket: Add network.transport and network.community_id. {pull}12231[12231] - Host: Fill top-level host fields. {pull}12259[12259] - Socket: Add DNS enrichment. {pull}14004[14004] *Filebeat* - Add more info to message logged when a duplicated symlink file is found {pull}10845[10845] - Add option to configure docker input with paths {pull}10687[10687] - Add Netflow module to enrich flow events with geoip data. {pull}10877[10877] - Set `event.category: network_traffic` for Suricata. {pull}10882[10882] - Allow custom default settings with autodiscover (for example, use of CRI paths for logs). {pull}12193[12193] - Allow to disable hints based autodiscover default behavior (fetching all logs). {pull}12193[12193] - Change Suricata module pipeline to handle `destination.domain` being set if a reverse DNS processor is used. {issue}10510[10510] - Add the `network.community_id` flow identifier to field to the IPTables, Suricata, and Zeek modules. {pull}11005[11005] - New Filebeat coredns module to ingest coredns logs. It supports both native coredns deployment and coredns deployment in kubernetes. {pull}11200[11200] - New module for Cisco ASA logs. {issue}9200[9200] {pull}11171[11171] - Added support for Cisco ASA fields to the netflow input. {pull}11201[11201] - Configurable line terminator. {pull}11015[11015] - Add Filebeat envoyproxy module. {pull}11700[11700] - Add apache2(httpd) log path (`/var/log/httpd`) to make apache2 module work out of the box on Redhat-family OSes. {issue}11887[11887] {pull}11888[11888] - Add support to new MongoDB additional diagnostic information {pull}11952[11952] - New module `panw` for Palo Alto Networks PAN-OS logs. {pull}11999[11999] - Add RabbitMQ module. {pull}12032[12032] - Add new `container` input. {pull}12162[12162] - Add timeouts on communication with docker daemon. {pull}12310[12310] - `container` and `docker` inputs now support reading of labels and env vars written by docker JSON file logging driver. {issue}8358[8358] - Add specific date processor to convert timezones so same pipeline can be used when convert_timezone is enabled or disabled. {pull}12253[12253] - Add MSSQL module {pull}12079[12079] - Add ISO8601 date parsing support for system module. {pull}12568[12568] {pull}12578[12579] - Update Kubernetes deployment manifest to use `container` input. {pull}12632[12632] - Use correct OS path separator in `add_kubernetes_metadata` to support Windows nodes. {pull}9205[9205] - Add support for virtual host in Apache access logs {pull}12778[12778] - Add support for client addresses with port in Apache error logs {pull}12695[12695] - Add `google-pubsub` input type for consuming messages from a Google Cloud Pub/Sub topic subscription. {pull}12746[12746] - Add module for ingesting Cisco IOS logs over syslog. {pull}12748[12748] - Add module for ingesting Google Cloud VPC flow logs. {pull}12747[12747] - Report host metadata for Filebeat logs in Kubernetes. {pull}12790[12790] - Add netflow dashboards based on Logstash netflow. {pull}12857[12857] - Parse more fields from Elasticsearch slowlogs. {pull}11939[11939] - Update module pipelines to enrich events with autonomous system fields. {pull}13036[13036] - Add module for ingesting IBM MQ logs. {pull}8782[8782] - Add S3 input to retrieve logs from AWS S3 buckets. {pull}12640[12640] {issue}12582[12582] - Add aws module s3access metricset. {pull}13170[13170] {issue}12880[12880] - Update Suricata module to populate ECS DNS fields and handle EVE DNS version 2. {issue}13320[13320] {pull}13329[13329] - Update PAN-OS fileset to use the ECS NAT fields. {issue}13320[13320] {pull}13330[13330] - Add fields to the Zeek DNS fileset for ECS DNS. {issue}13320[13320] {pull}13324[13324] - Add container image in Kubernetes metadata {pull}13356[13356] {issue}12688[12688] - Add timezone information to apache error fileset. {issue}12772[12772] {pull}13304[13304] - Add module for ingesting Cisco FTD logs over syslog. {pull}13286[13286] - Update CoreDNS module to populate ECS DNS fields. {issue}13320[13320] {pull}13505[13505] - Parse query steps in PostgreSQL slowlogs. {issue}13496[13496] {pull}13701[13701] - Add filebeat azure module with activitylogs, auditlogs, signinlogs filesets. {pull}13776[13776] {pull}14033[14033] - Add support to set the document id in the json reader. {pull}5844[5844] - Add input httpjson. {issue}13545[13545] {pull}13546[13546] - Filebeat Netflow input: Remove beta label. {pull}13858[13858] - Remove `event.timezone` from events that don't need it in some modules that support log formats with and without timezones. {pull}13918[13918] - Add ExpandEventListFromField config option in the kafka input. {pull}13965[13965] - Add ELB fileset to AWS module. {pull}14020[14020] - Add module for MISP (Malware Information Sharing Platform). {pull}13805[13805] - Add `source.bytes` and `source.packets` for uni-directional netflow events. {pull}14111[14111] - Add support for gzipped files in S3 input. {pull}13980[13980] - Add support for all the ObjectCreated events in S3 input. {pull}14077[14077] - Add Kibana Dashboard for MISP module. {pull}14147[14147] - Add JSON options to autodiscover hints {pull}14208[14208] - Add more filesets to Zeek module. {pull}14150[14150] - Add `index` option to all inputs to directly set a per-input index value. {pull}14010[14010] - Remove beta flag for some filebeat modules. {pull}14374[14374] - Add support for http hostname in nginx filebeat module. {pull}14505[14505] - Add attack_pattern_kql field to MISP threat indicators. {pull}14470[14470] - Add fileset to the Zeek module for the intel.log. {pull}14404[14404] - Add vpc flow log fileset to AWS module. {issue}13880[13880] {pull}14345[14345] - New fileset googlecloud/firewall for ingesting Google Cloud Firewall logs. {pull}14553[14553] - Add document for Filebeat input httpjson. {pull}14602[14602] - Add more configuration options to the Netflow module. {pull}14628{14628} - Add dashboards to the CEF module (ported from the Logstash ArcSight module). - Add dashboards to the CEF module (ported from the Logstash ArcSight module). {pull}14342[14342] - Fix timezone parsing in haproxy pipeline. {pull}14755[14755] - Add module for ActiveMQ. {pull}14840[14840] - Add dashboards for the ActiveMQ Filebeat module. {pull}14880[14880] *Heartbeat* - Add non-privileged icmp on linux and darwin(mac). {pull}13795[13795] {issue}11498[11498] - Enable `add_observer_metadata` processor in default config. {pull}11394[11394] - Record HTTP body metadata and optionally contents in `http.response.body.*` fields. {pull}13022[13022] - Allow `hosts` to be used to configure http monitors {pull}13703[13703] - google-pubsub input: ACK pub/sub message when acknowledged by publisher. {issue}13346[13346] {pull}14715[14715] - Remove Beta label from google-pubsub input. {issue}13346[13346] {pull}14715[14715] *Journalbeat* *Metricbeat* - Add AWS SQS metricset. {pull}10684[10684] {issue}10053[10053] - Add AWS s3_request metricset. {pull}10949[10949] {issue}10055[10055] - Add s3_daily_storage metricset. {pull}10940[10940] {issue}10055[10055] - Add `coredns` metricbeat module. {pull}10585[10585] - Add SSL support for Metricbeat HTTP server. {pull}11482[11482] {issue}11457[11457] - The `elasticsearch.index` metricset (with `xpack.enabled: true`) now collects `refresh.external_total_time_in_millis` fields from Elasticsearch. {pull}11616[11616] - Allow module configurations to have variants {pull}9118[9118] - Add `timeseries.instance` field calculation. {pull}10293[10293] - Added new disk states and raid level to the system/raid metricset. {pull}11613[11613] - Added `path_name` and `start_name` to service metricset on windows module {issue}8364[8364] {pull}11877[11877] - Add check on object name in the counter path if the instance name is missing {issue}6528[6528] {pull}11878[11878] - Add AWS cloudwatch metricset. {pull}11798[11798] {issue}11734[11734] - Add `regions` in aws module config to specify target regions for querying cloudwatch metrics. {issue}11932[11932] {pull}11956[11956] - Keep `etcd` followers members from reporting `leader` metricset events {pull}12004[12004] - Add overview dashboard to Consul module {pull}10665[10665] - New fields were added in the mysql/status metricset. {pull}12227[12227] - Add Kubernetes metricset `proxy`. {pull}12312[12312] - Add Kubernetes proxy dashboard to Kubernetes module {pull}12734[12734] - Always report Pod UID in the `pod` metricset. {pull}12345[12345] - Add Vsphere Virtual Machine operating system to `os` field in Vsphere virtualmachine module. {pull}12391[12391] - Add validation for elasticsearch and kibana modules' metricsets when xpack.enabled is set to true. {pull}12386[12386] - Add CockroachDB module. {pull}12467[12467] - Add support for metricbeat modules based on existing modules (a.k.a. light modules) {issue}12270[12270] {pull}12465[12465] - Add a system/entropy metricset {pull}12450[12450] - Add kubernetes metricset `controllermanager` {pull}12409[12409] - Add Kubernetes controller manager dashboard to Kubernetes module {pull}12744[12744] - Allow redis URL format in redis hosts config. {pull}12408[12408] - Add tags into ec2 metricset. {issue}[12263]12263 {pull}12372[12372] - Add metrics to kubernetes apiserver metricset. {pull}12922[12922] - Add kubernetes metricset `scheduler` {pull}12521[12521] - Add Kubernetes scheduler dashboard to Kubernetes module {pull}12749[12749] - Add `beat` module. {pull}12181[12181] {pull}12615[12615] - Collect tags for cloudwatch metricset in aws module. {issue}[12263]12263 {pull}12480[12480] - Add AWS RDS metricset. {pull}11620[11620] {issue}10054[10054] - Add Oracle Module {pull}11890[11890] - Add Oracle Tablespaces Dashboard {pull}12736[12736] - Collect client provided name for rabbitmq connection. {issue}12851[12851] {pull}12852[12852] - Add support to load default aws config file to get credentials. {pull}12727[12727] {issue}12708[12708] - Add statistic option into cloudwatch metricset. {issue}12370[12370] {pull}12840[12840] - Add support for kubernetes cronjobs {pull}13001[13001] - Add cgroup memory stats to docker/memory metricset {pull}12916[12916] - Add AWS elb metricset. {pull}12952[12952] {issue}11701[11701] - Add AWS ebs metricset. {pull}13167[13167] {issue}11699[11699] - Add `metricset.period` field with the configured fetching period. {pull}13242[13242] {issue}12616[12616] - Add rate metrics for ec2 metricset. {pull}13203[13203] - Add refresh list of perf counters at every fetch {issue}13091[13091] - Add Performance metricset to Oracle module {pull}12547[12547] - Add proc/vmstat data to the system/memory metricset on linux {pull}13322[13322] - Use DefaultMetaGeneratorConfig in MetadataEnrichers to initialize configurations {pull}13414[13414] - Add module for statsd. {pull}13109[13109] - Add support for NATS version 2. {pull}13601[13601] - Add `docker.cpu.*.norm.pct` metrics for `cpu` metricset of Docker Metricbeat module. {pull}13695[13695] - Add `instance` label by default when using Prometheus collector. {pull}13737[13737] - Add azure module. {pull}13196[13196] {pull}13859[13859] {pull}13988[13988] - Add Apache Tomcat module {pull}13491[13491] - Add ECS `container.id` and `container.runtime` to kubernetes `state_container` metricset. {pull}13884[13884] - Add `job` label by default when using Prometheus collector. {pull}13878[13878] - Add `state_resourcequota` metricset for Kubernetes module. {pull}13693[13693] - Add tags filter in ec2 metricset. {pull}13872[13872] {issue}13145[13145] - Add cloud.account.id and cloud.account.name into events from aws module. {issue}13551[13551] {pull}13558[13558] - Add `metrics_path` as known hint for autodiscovery {pull}13996[13996] - Leverage KUBECONFIG when creating k8s client. {pull}13916[13916] - Add ability to filter by tags for cloudwatch metricset. {pull}13758[13758] {issue}13145[13145] - Release cloudwatch, s3_daily_storage, s3_request, sqs and rds metricset as GA. {pull}14114[14114] {issue}14059[14059] - Add Oracle overview dashboard {pull}14021[14021] - Release CoreDNS module as GA. {pull}14308[14308] - Release CouchDB module as GA. {pull}14300[14300] - Add `elasticsearch/enrich` metricset. {pull}14243[14243] {issue}14221[14221] - Add support for Application ELB and Network ELB. {pull}14123[14123] {issue}13538[13538] {issue}13539[13539] - Release aws ebs metricset as GA. {pull}14312[14312] {issue}14060[14060] - Add `connection.state` field for RabbitMQ module. {pull}13981[13981] - Add more TCP states to Metricbeat system socket_summary. {pull}14347[14347] - Add Kafka JMX metricsets. {pull}14330[14330] - Add metrics to envoyproxy server metricset and support for envoy proxy 1.12. {pull}14416[14416] {issue}13642[13642] - Release kubernetes modules `controllermanager`, `scheduler`, `proxy`, `state_cronjob` and `state_resourcequota` as GA. {pull}14584[14584] - Add module for ActiveMQ. {pull}14580[14580] - Enable script processor. {pull}14711[14711] - Add `kube-state-metrics` `state_service` metrics for kubernetes module. {pull}14794[14794] - Add usage metricset in aws modules. {pull}14925[14925] {issue}14935[14935] - Add billing metricset in aws modules. {pull}14801[14801] {issue}14934[14934] - Add AWS SNS metricset. {pull}14946[14946] *Packetbeat* - Update DNS protocol plugin to produce events with ECS fields for DNS. {issue}13320[13320] {pull}13354[13354] *Functionbeat* - New options to configure roles and VPC. {pull}11779[11779] - Export automation templates used to create functions. {pull}11923[11923] - Configurable Amazon endpoint. {pull}12369[12369] - Add timeout option to reference configuration. {pull}13351[13351] - Configurable tags for Lambda functions. {pull}13352[13352] - Add input for Cloudwatch logs through Kinesis. {pull}13317[13317] - Enable Logstash output. {pull}13345[13345] - Make `bulk_max_size` configurable in outputs. {pull}13493[13493] *Winlogbeat* - Add support for reading from .evtx files. {issue}4450[4450] - Add support for event ID 4634 and 4647 to the Security module. {pull}12906[12906] - Add `network.community_id` to Sysmon network events (event ID 3). {pull}13034[13034] - Add `event.module` to Winlogbeat modules. {pull}13047[13047] - Add `event.category: process` and `event.type: process_start/process_end` to Sysmon process events (event ID 1 and 5). {pull}13047[13047] - Add support for event ID 4672 to the Security module. {pull}12975[12975] - Add support for event ID 22 (DNS query) to the Sysmon module. {pull}12960[12960] - Add certain winlog.event_data.* fields to the index template. {issue}13700[13700] {pull}13704[13704] - Fill `event.provider`. {pull}13937[13937] - Add support for user management events to the Security module. {pull}13530[13530] - GA the Winlogbeat `sysmon` module. {pull}14326[14326] - Add support for event ID 4688 & 4689 (Process create & exit) to the Security module. {issue}14038[14038] ==== Deprecated *Affecting all Beats* *Filebeat* - `docker` input is deprecated in favour `container`. {pull}12162[12162] - `postgresql.log.timestamp` field is deprecated in favour of `@timestamp`. {pull}12338[12338] *Heartbeat* *Journalbeat* *Metricbeat* - `kubernetes.container.id` field for `state_container` is deprecated in favour of ECS `container.id` and `container.runtime`. {pull}13884[13884] *Packetbeat* *Winlogbeat* *Functionbeat* ==== Known Issue *Journalbeat* ",16298,True,3704.892501794135,median "package view { import flash.display.*; import flash.filters.*; import flash.events.MouseEvent; import flash.events.Event; import flash.events.EventDispatcher; import mx.core.UIComponent; import mx.core.MovieClipLoaderAsset; import mx.controls.Button; import mx.controls.Label; import org.libspark.thread.*; import org.libspark.thread.utils.*; import org.libspark.thread.threads.between.BeTweenAS3Thread; import model.DeckEditor; import model.Growth; import model.Combine; import model.WeaponCardInventory; import model.events.*; import view.image.edit.*; import view.scene.edit.*;; import view.scene.common.*;; import view.RealMoneyShopView; import controller.LobbyCtrl; import controller.GlobalChatCtrl; // test import model.Player; import model.CharaCard; import model.InventorySet; import view.scene.common.CharaCardClip; import view.utils.*; /** * 編集画面のビュークラス * */ public class DeckEditView extends Thread { // 翻訳データ CONFIG::LOCALE_JP private static const _TRANS_MSG :String = ""デッキ編集""; CONFIG::LOCALE_EN private static const _TRANS_MSG :String = ""Deck Editor""; CONFIG::LOCALE_TCN private static const _TRANS_MSG :String = ""編輯牌組""; CONFIG::LOCALE_SCN private static const _TRANS_MSG :String = ""卡组编辑""; CONFIG::LOCALE_KR private static const _TRANS_MSG :String = ""덱 편집""; CONFIG::LOCALE_FR private static const _TRANS_MSG :String = ""Modification de votre pioche.""; CONFIG::LOCALE_ID private static const _TRANS_MSG :String = ""デッキ編集""; CONFIG::LOCALE_TH private static const _TRANS_MSG :String = ""แก้ไขสำรับ""; // コントローラ private var _ctrl:LobbyCtrl = LobbyCtrl.instance; // エディットインスタンス private var _deckEdit:DeckEditor = DeckEditor.instance; // 成長インスタンス private var _growth:Growth = Growth.instance; // 合成インスタンス private var _combine:Combine = Combine.instance; // 親ステージ private var _stage:Sprite; // 表示コンテナ private var _container:UIComponent = new UIComponent(); // 合成コンテナ private var _compoContainer:UIComponent = new UIComponent(); // アバタービューコンテナ private var _avatarContainer:UIComponent = new UIComponent(); // 背景 private var _bg:BG = new BG(); // バインダー部分 private var _ccBinderArea:BinderArea = BinderArea.getCharaCardBinder(); private var _wpBinderArea:BinderArea = BinderArea.getWeaponCardBinder(); private var _eqBinderArea:BinderArea = BinderArea.getEquipCardBinder(); private var _evBinderArea:BinderArea = BinderArea.getEventCardBinder(); private var _mcBinderArea:BinderArea = BinderArea.getMonsterCardBinder(); private var _ocBinderArea:BinderArea = BinderArea.getOtherCardBinder(); // バインダーの配列 private var _binderArea:Array = [_ccBinderArea, _wpBinderArea, _eqBinderArea, _evBinderArea, _mcBinderArea, _ocBinderArea]; // デッキ部分 private var _ccDeckArea:DeckArea = DeckArea.getCharaCardDeck(); private var _wpDeckArea:DeckArea = DeckArea.getWeaponCardDeck(); //private var _eqDeckArea:DeckArea = DeckArea.getEquipCardDeck(); private var _evDeckArea:DeckArea = DeckArea.getEventCardDeck(); //private var _mcDeckArea:DeckArea = DeckArea.getMonsterCardDeck(); //private var _ocDeckArea:DeckArea = DeckArea.getOtherCardDeck(); // デッキの配列 # モンス・その他はキャラデッキを使う 2014/09/02 private var _deckArea:Array = [_ccDeckArea, _wpDeckArea, null, _evDeckArea, null, null]; // カードデータ部分 private var _ccDataArea:DataArea = DataArea.getCharaCardData(); private var _wpDataArea:DataArea = DataArea.getWeaponCardData(); //private var _eqDataArea:DataArea = DataArea.getEquipCardData(); private var _evDataArea:DataArea = DataArea.getEventCardData(); //private var _mcDataArea:DataArea = DataArea.getMonsterCardData(); //private var _ocDataArea:DataArea = DataArea.getOtherCardData(); // カードデータの配列 # モンス・その他はキャラデータを使う 2014/09/02 private var _dataArea:Array = [_ccDataArea, _wpDataArea, null, _evDataArea, null, null]; // ソート表示 private var _sortArea:SortArea = new SortArea(); private var _selectArea:SelectArea = new SelectArea(); // 複製確認パネル private var _dupeSendPanel:DupeSendPanel = new DupeSendPanel(); // デッキセット // private var _deckSetButton:DeckSetButton = new DeckSetButton(); // バインダーのタイプ private var _editType:int; // タイトル表示 private var _title:Label = new Label(); private var _titleJ:Label = new Label(); // 系統樹 private var _requirementsView:RequirementsView; // 合成 private var _combinesView:CombinesView; private var _avatarView:AvatarView = AvatarView.getPlayerAvatar(Const.PL_AVATAR_EDIT); private var _player:Player = Player.instance; // 定数 private const _TITLE_X:int = 15; private const _TITLE_Y:int = 5; private const _TITLE_WIDTH:int = 100; private const _TITLE_HEIGHT:int = 20; private const _J_TITLE_WIDTH:int = 100; private const _J_TITLE_HEIGHT:int = 20; // かけら販売フラグ private const _SELL_TIPS:Boolean = true; //テスト // private var _testcccs:Array = [] /** * コンストラクタ * @param stage 親ステージ */ public function DeckEditView(stage:Sprite) { _stage = stage; _dupeSendPanel.visible = false; // Unlight.GCW.watch(_bg,""BGです""); RaidHelpView.instance.isUpdate = true; } // スレッドのスタート override protected function run():void { _deckEdit.initialize(); // RMItemShopの更新が必要であれば行う RealMoneyShopView.itemReset(); // イベントの登録 _avatarView.exitButton.addEventListener(MouseEvent.CLICK, pushExitButtonHandler); _bg.deckDelete.addEventListener(MouseEvent.CLICK, pushDeleteButtonHandler); // _deckSetButton.addEventListener(MouseEvent.CLICK, pushCurrentButtonHandler); _bg.back.addEventListener(MouseEvent.CLICK, pushLeftButtonHandler); _bg.next.addEventListener(MouseEvent.CLICK, pushRightButtonHandler); _bg.binderNext.addEventListener(MouseEvent.CLICK, pushNextButtonHandler); _bg.binderPrev.addEventListener(MouseEvent.CLICK, pushPrevButtonHandler); _dupeSendPanel.yesButton.addEventListener(MouseEvent.CLICK, pushYesDupeButtonHandler); _dupeSendPanel.noButton.addEventListener(MouseEvent.CLICK, pushNoDupeButtonHandler); _ctrl.addEventListener(LobbyCtrl.REQUEST_COPY_CARD, showDupeSendPanelHandler); _ctrl.addEventListener(CharaCardEvent.COPY_CHARA_CARD, copyDoneHandler); _deckEdit.addEventListener(DeckEditor.CHANGE_TYPE, chnageEditTypeHandler); _dataArea[InventorySet.TYPE_CHARA].storyButton = _bg.story; _dataArea[InventorySet.TYPE_CHARA].compoButton = _bg.compo; _dataArea[InventorySet.TYPE_CHARA].dupeButton = _bg.dupe; _deckArea[InventorySet.TYPE_CHARA].addEventListener(DeckUpdatedEvent.UPDATED_CHARA_CARD, deckUpdatedHandler); // 武器合成アリか CONFIG::WEAPON_COMBINE_ON { _dataArea[InventorySet.TYPE_WEAPON].compoButton = _bg.compo; } //_dataArea[InventorySet.TYPE_MONSTER].storyButton = _bg.story; //_dataArea[InventorySet.TYPE_MONSTER].compoButton = _bg.compo; //_dataArea[InventorySet.TYPE_MONSTER].dupeButton = _bg.dupe; //_deckArea[InventorySet.TYPE_MONSTER].addEventListener(DeckUpdatedEvent.UPDATED_CHARA_CARD, deckUpdatedHandler); //_dataArea[InventorySet.TYPE_OTHER].storyButton = _bg.story; //_dataArea[InventorySet.TYPE_OTHER].compoButton = _bg.compo; //_dataArea[InventorySet.TYPE_OTHER].dupeButton = _bg.dupe; //_deckArea[InventorySet.TYPE_OTHER].addEventListener(DeckUpdatedEvent.UPDATED_CHARA_CARD, deckUpdatedHandler); RealMoneyShopView.shopCloseButton.addEventListener(MouseEvent.CLICK, rmShopCloseclickHandler); Player.instance.avatar.addEventListener(AvatarSaleEvent.SALE_FINISH, saleFinishHandler); // レイドヘルプイベント GlobalChatCtrl.instance.addEventListener(RaidHelpEvent.ACCEPT,helpAcceptHandler); next(initTitle); } // タイトルの初期化 private function initTitle():void { _avatarView.alpha = 0.0; _bg.alpha = 0.0; _sortArea.alpha = 0.0; _selectArea.alpha = 0.0; _binderArea[_editType].alpha = 0.0; // デッキとデータは一部共通化 if (_editType == _deckEdit.substanceEditType(_editType)) { _deckArea[_editType].alpha = 0.0; _dataArea[_editType].alpha = 0.0; } // _deckSetButton.alpha = 0.0; _title.x = _TITLE_X; _title.y = _TITLE_Y; _title.width = _TITLE_WIDTH; _title.height = _TITLE_HEIGHT; _title.text = ""DeckEdit""; _title.styleName = ""EditTitleLabel""; _title.filters = [new GlowFilter(0x000000, 1, 2, 2, 16, 1)]; _title.alpha = 0.0; _title.mouseEnabled = false; _title.mouseChildren = false; _titleJ.x = _TITLE_X + 85; _titleJ.y = _TITLE_Y + 7; _titleJ.width = _J_TITLE_WIDTH; _titleJ.height = _J_TITLE_HEIGHT; // _titleJ.text = ""デッキ編集""; _titleJ.text = _TRANS_MSG; _titleJ.filters = [new GlowFilter(0xFFFFFF, 1, 2, 2, 16, 1)]; _titleJ.alpha = 0.0; _titleJ.mouseEnabled = false; _titleJ.mouseChildren = false; _avatarView.refreshType() next(show); } // 配置オブジェの表示 private function show():void { var pExec:ParallelExecutor = new ParallelExecutor(); pExec.addThread(_bg.getShowThread(_container, 0)); // 背景 // pExec.addThread(_deckSetButton.getShowThread(_container, 1)); // デッキセットボタン pExec.addThread(_sortArea.getShowThread(_container, 21)); // ソート pExec.addThread(_selectArea.getShowThread(_container, 21)); pExec.addThread(_dataArea[InventorySet.TYPE_CHARA].getShowThread(_container, 3)); // カードデータ pExec.addThread(_dataArea[InventorySet.TYPE_WEAPON].getShowThread(_container, 4)); // カードデータ //pExec.addThread(_dataArea[InventorySet.TYPE_EQUIP].getShowThread(_container, 5)); // カードデータ pExec.addThread(_dataArea[InventorySet.TYPE_EVENT].getShowThread(_container, 6)); // カードデータ //pExec.addThread(_dataArea[InventorySet.TYPE_MONSTER].getShowThread(_container, 7)); // カードデータ //pExec.addThread(_dataArea[InventorySet.TYPE_OTHER].getShowThread(_container, 8)); // カードデータ pExec.addThread(_binderArea[InventorySet.TYPE_CHARA].getShowThread(_container, 9)); // バインダー pExec.addThread(_binderArea[InventorySet.TYPE_WEAPON].getShowThread(_container, 10)); // バインダー pExec.addThread(_binderArea[InventorySet.TYPE_EQUIP].getShowThread(_container, 11)); // バインダー pExec.addThread(_binderArea[InventorySet.TYPE_EVENT].getShowThread(_container, 12)); // バインダー pExec.addThread(_binderArea[InventorySet.TYPE_MONSTER].getShowThread(_container, 13)); // バインダー pExec.addThread(_binderArea[InventorySet.TYPE_OTHER].getShowThread(_container, 14)); // バインダー pExec.addThread(_deckArea[InventorySet.TYPE_CHARA].getShowThread(_container, 15)); // デッキ pExec.addThread(_deckArea[InventorySet.TYPE_WEAPON].getShowThread(_container, 16)); // デッキ //pExec.addThread(_deckArea[InventorySet.TYPE_EQUIP].getShowThread(_container, 17)); // デッキ pExec.addThread(_deckArea[InventorySet.TYPE_EVENT].getShowThread(_container, 18)); // デッキ //pExec.addThread(_deckArea[InventorySet.TYPE_MONSTER].getShowThread(_container, 19)); // デッキ //pExec.addThread(_deckArea[InventorySet.TYPE_OTHER].getShowThread(_container, 20)); // デッキ // _testcccs.forEach(function(item:*, index:int, array:Array):void{item.getShowThread(_container).start()}) pExec.start(); pExec.join(); _stage.addChildAt(_container, 1); _stage.addChildAt(_compoContainer, 2); _stage.addChildAt(_avatarContainer, 3); _stage.addChildAt(_dupeSendPanel, 4); _deckEdit.waiting(); _avatarContainer.addChild(_title); _avatarContainer.addChild(_titleJ); next(show2); } // 配置オブジェの表示 private function show2():void { _bg.tabChara.addEventListener(MouseEvent.CLICK, charaCardTabClickHandler); _bg.tabEquip.addEventListener(MouseEvent.CLICK, weaponCardTabClickHandler); _bg.tabEvent.addEventListener(MouseEvent.CLICK, eventCardTabClickHandler); _bg.tabMonster.addEventListener(MouseEvent.CLICK, monsterCardTabClickHandler); _bg.tabOther.addEventListener(MouseEvent.CLICK, otherCardTabClickHandler); _deckEdit.setEditType(InventorySet.TYPE_CHARA); var pExec:ParallelExecutor = new ParallelExecutor(); // _stage.addChildAt(_deckSetButton, 3); pExec.addThread(new BeTweenAS3Thread(_title, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.addThread(new BeTweenAS3Thread(_titleJ, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.addThread(new BeTweenAS3Thread(_bg, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.addThread(new BeTweenAS3Thread(_sortArea, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.addThread(new BeTweenAS3Thread(_selectArea, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.addThread(new BeTweenAS3Thread(_dataArea[_deckEdit.substanceEditType(_editType)], {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.addThread(new BeTweenAS3Thread(_binderArea[_editType], {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.addThread(new BeTweenAS3Thread(_deckArea[_deckEdit.substanceEditType(_editType)], {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); // pExec.addThread(new BeTweenAS3Thread(_avatarView, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.addThread(_avatarView.getShowThread(_avatarContainer,0)); // アバター情報 // pExec.addThread(new BeTweenAS3Thread(_deckSetButton, {alpha:1.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,true)); pExec.start(); pExec.join(); next(initPayment); } CONFIG::PAYMENT private function initPayment():void { if(_SELL_TIPS) { _container.addChild(RealMoneyShopView.onShopButton(RealMoneyShopView.TYPE_EX_CARD)); } next(waiting); } CONFIG::NOT_PAYMENT private function initPayment():void { // addChild(RealMoneyShopView.onShopButton(RealMoneyShopView.TYPE_EX_CARD)); next(waiting); } // ループ private function waiting():void { // ステートでループ if (_player.state == Player.STATE_LOGOUT) { next(hide); }else if(_deckEdit.state == DeckEditor.END) { next(hide); } else if(_growth.state == Growth.REQUIREMENTS) { next(requirements); } else if(_combine.state == Combine.COMBINES) { next(combines); } else { next(waiting); } } // 系統樹を表示 private function requirements():void { RaidHelpView.instance.isUpdate = false; var pExec:ParallelExecutor = new ParallelExecutor(); _requirementsView = new RequirementsView(_compoContainer, _growth.requirementsCardId) pExec.addThread(_requirementsView); // _deckSetButton.visible = false; // _avatarView.exitButton.visible = false; _avatarView.exitButton.removeEventListener(MouseEvent.CLICK, pushExitButtonHandler); _avatarView.exitButton.addEventListener(MouseEvent.CLICK, _requirementsView.exitHandler); _container.removeChild(_binderArea[_editType]); _binderArea[_editType].visible =false; _avatarView.stopUpdateTimer(); RealMoneyShopView.offShopButton(RealMoneyShopView.TYPE_AVATAR); pExec.start(); pExec.join(); next(requirementFinish) } private function requirementFinish():void { // _deckSetButton.visible = true; _binderArea[_editType].visible =true; _container.addChild(_binderArea[_editType]); // _avatarView.exitButton.visible = true; _avatarView.exitButton.removeEventListener(MouseEvent.CLICK, _requirementsView.exitHandler); _avatarView.exitButton.addEventListener(MouseEvent.CLICK, pushExitButtonHandler); _requirementsView = null; _binderArea[_editType].show(); // 選択済みのカードが枚数0だったら消す if (CharaCard.ID(_dataArea[_deckEdit.substanceEditType(_editType)].ccc.charaCard.id).num > 0) { _dataArea[_deckEdit.substanceEditType(_editType)].showCard(); }else{ _dataArea[_deckEdit.substanceEditType(_editType)].clearCard(); } _avatarView.startUpdateTimer(); _deckEdit.waiting(); RaidHelpView.instance.isUpdate = true; next(waiting); } // 合成画面を表示 private function combines():void { RaidHelpView.instance.isUpdate = false; var pExec:ParallelExecutor = new ParallelExecutor(); var selInvId:int = 0; var wci:WeaponCardInventory = _dataArea[_editType].selectInventory; if (wci) { selInvId = wci.inventoryID; } _combinesView = new CombinesView(_compoContainer, selInvId,_binderArea[_editType]) pExec.addThread(_combinesView); _avatarView.exitButton.removeEventListener(MouseEvent.CLICK, pushExitButtonHandler); _avatarView.exitButton.addEventListener(MouseEvent.CLICK, _combinesView.exitHandler); _container.removeChild(_binderArea[_editType]); _binderArea[_editType].visible =false; setTabBtnEnableCombine(false); pExec.start(); pExec.join(); next(combineFinish) } private function combineFinish():void { var pExec:ParallelExecutor = new ParallelExecutor(); _binderArea[_editType].visible =true; _container.addChild(_binderArea[_editType]); _avatarView.exitButton.removeEventListener(MouseEvent.CLICK, _combinesView.exitHandler); _avatarView.exitButton.addEventListener(MouseEvent.CLICK, pushExitButtonHandler); _combinesView = null; _binderArea[_editType].alpha = 1.0; _binderArea[_editType].show(); setTabBtnEnableCombine(true); _deckEdit.waiting(); pExec.start(); pExec.join(); tabDataAreaUpdate(InventorySet.TYPE_WEAPON); RaidHelpView.instance.isUpdate = true; next(waiting); } private function setTabBtnEnableCombine(f:Boolean):void { _bg.tabChara.mouseEnabled = f; _bg.tabEquip.mouseEnabled = f; _bg.tabEvent.mouseEnabled = f; _bg.tabMonster.mouseEnabled = f; _bg.tabOther.mouseEnabled = f; } private function deckUpdatedHandler(e:DeckUpdatedEvent):void { _deckEdit.updateCautions(e); } // 左にデッキ切り替え private function pushLeftButtonHandler(e:MouseEvent):void { var subType:uint = _deckEdit.substanceEditType(_editType); if(_deckArea[subType].flag) { SE.playClick(); _deckArea[subType].currentIndex = _deckArea[subType].currentIndex - 1; _deckArea[InventorySet.TYPE_CHARA].changeDeck(true); _deckArea[InventorySet.TYPE_WEAPON].changeDeck(true); //_deckArea[InventorySet.TYPE_EQUIP].changeDeck(true); _deckArea[InventorySet.TYPE_EVENT].changeDeck(true); //_deckArea[InventorySet.TYPE_MONSTER].changeDeck(true); //_deckArea[InventorySet.TYPE_OTHER].changeDeck(true); } } // 右にデッキ切り替え private function pushRightButtonHandler(e:MouseEvent):void { var subType:uint = _deckEdit.substanceEditType(_editType); if(_deckArea[subType].flag) { SE.playClick(); _deckArea[subType].currentIndex = _deckArea[subType].currentIndex + 1; _deckArea[InventorySet.TYPE_CHARA].changeDeck(false); _deckArea[InventorySet.TYPE_WEAPON].changeDeck(false); //_deckArea[InventorySet.TYPE_EQUIP].changeDeck(false); _deckArea[InventorySet.TYPE_EVENT].changeDeck(false); //_deckArea[InventorySet.TYPE_MONSTER].changeDeck(false); //_deckArea[InventorySet.TYPE_OTHER].changeDeck(false); } } // デッキを作成 private function pushCreateButtonHandler(e:MouseEvent):void { SE.playClick(); _deckEdit.createDeck(); log.writeLog(log.LV_INFO, this, ""push create deck""); } // デッキを削除 private function pushDeleteButtonHandler(e:MouseEvent):void { SE.playClick(); _deckEdit.deleteDeck(_deckEdit.selectIndex); log.writeLog(log.LV_INFO, this, ""push create deck""); } // カレントデッキ変更 private function pushCurrentButtonHandler(e:MouseEvent):void { SE.playClick(); _deckEdit.changeCurrentDeck(_deckEdit.selectIndex); log.writeLog(log.LV_INFO, this, ""push current change""); } // 終了 private function pushExitButtonHandler(e:MouseEvent):void { SE.playClick(); _deckEdit.finalize(); log.writeLog(log.LV_INFO, this, ""push exit""); } // タブのデータエリアをON/OFFする private function tabDataAreaUpdate(t:int):void { // 現在タブのカードのみ出す log.writeLog(log.LV_INFO, this, ""SHOWCARD TYPE"",t); log.writeLog(log.LV_INFO, this, ""_dataarea size?"",_dataArea.length); // 他タブのカードを隠す _dataArea.forEach(function(item:DataArea, index:int, array:Array):void{ if(t != index && _deckEdit.substanceEditType(t) != index && item != null) { log.writeLog(log.LV_INFO, this, ""HIDE TYPE"",index); item.hideCard(); } }); _dataArea[_deckEdit.substanceEditType(t)].showCard(); } // キャラカードを選択 private function charaCardTabClickHandler(e:MouseEvent):void { log.writeLog(log.LV_INFO, this, ""set edit type chara!!""); _deckEdit.setEditType(InventorySet.TYPE_CHARA); tabDataAreaUpdate(InventorySet.TYPE_CHARA); } // 武器カードを選択 private function weaponCardTabClickHandler(e:MouseEvent):void { _deckEdit.setEditType(InventorySet.TYPE_WEAPON); tabDataAreaUpdate(InventorySet.TYPE_WEAPON); } // 装備カードを選択 private function equipCardTabClickHandler(e:MouseEvent):void { _deckEdit.setEditType(InventorySet.TYPE_EQUIP); tabDataAreaUpdate(InventorySet.TYPE_EQUIP); } // イベントカードを選択 private function eventCardTabClickHandler(e:MouseEvent):void { _deckEdit.setEditType(InventorySet.TYPE_EVENT); tabDataAreaUpdate(InventorySet.TYPE_EVENT); } // モンスターカードを選択 private function monsterCardTabClickHandler(e:MouseEvent):void { _deckEdit.setEditType(InventorySet.TYPE_MONSTER); tabDataAreaUpdate(InventorySet.TYPE_MONSTER); } // その他カードを選択 private function otherCardTabClickHandler(e:MouseEvent):void { _deckEdit.setEditType(InventorySet.TYPE_OTHER); tabDataAreaUpdate(InventorySet.TYPE_OTHER); } // 編集タイプを変更 private function chnageEditTypeHandler(e:Event):void { setEditType(_deckEdit.editType); } // バインダーを進める private function pushNextButtonHandler(e:MouseEvent):void { log.writeLog (log.LV_DEBUG,this,""binder next""); _binderArea[_editType].page -=1; } // バインダーを戻す private function pushPrevButtonHandler(e:MouseEvent):void { log.writeLog (log.LV_DEBUG,this,""binder prev""); _binderArea[_editType].page +=1; } // 複製確認パネルを表示 private function showDupeSendPanelHandler(e:Event):void { _container.mouseEnabled = false; _container.mouseChildren = false; _dupeSendPanel.visible = true; } // 複製YES private function pushYesDupeButtonHandler(e:MouseEvent):void { // 表示中のカードをコピー if (_editType == InventorySet.TYPE_CHARA || _editType == InventorySet.TYPE_MONSTER || _editType == InventorySet.TYPE_OTHER) { _ctrl.copyCard(_dataArea[_deckEdit.substanceEditType(_editType)].ccc.charaCard.id); } _container.mouseEnabled = true; _container.mouseChildren = true; _dupeSendPanel.visible = false; } // 複製NO private function pushNoDupeButtonHandler(e:MouseEvent):void { _container.mouseEnabled = true; _container.mouseChildren = true; _dupeSendPanel.visible = false; } // 複製完了後ハンドラ private function copyDoneHandler(e:Event):void { if (_editType == InventorySet.TYPE_CHARA || _editType == InventorySet.TYPE_MONSTER || _editType == InventorySet.TYPE_OTHER) { _dataArea[_deckEdit.substanceEditType(_editType)].reloadDupeCount(); } } // セールの終了判定が出たときのハンドラ private function saleFinishHandler(e:AvatarSaleEvent):void { // log.writeLog (log.LV_INFO,this,""saleFinish!""); RealMoneyShopView.hideButtonSaleMC(RealMoneyShopView.TYPE_EX_CARD); // ショップアイテムリストの更新 RealMoneyShopView.itemReset(); } // レイドヘルプハンドラ private function helpAcceptHandler(e:RaidHelpEvent):void { _deckEdit.finalize(); log.writeLog(log.LV_INFO, this, ""raid help""); } // バインダーを戻す private function setEditType(val:int):void { switch (val) { case InventorySet.TYPE_CHARA: _binderArea[InventorySet.TYPE_CHARA].visible = true; _binderArea[InventorySet.TYPE_WEAPON].visible = false; _binderArea[InventorySet.TYPE_EQUIP].visible = false; _binderArea[InventorySet.TYPE_EVENT].visible = false; _binderArea[InventorySet.TYPE_MONSTER].visible = false; _binderArea[InventorySet.TYPE_OTHER].visible = false; _binderArea[InventorySet.TYPE_CHARA].addSortHandler(); _binderArea[InventorySet.TYPE_WEAPON].removeSortHandler(); _binderArea[InventorySet.TYPE_EQUIP].removeSortHandler(); _binderArea[InventorySet.TYPE_EVENT].removeSortHandler(); _binderArea[InventorySet.TYPE_MONSTER].removeSortHandler(); _binderArea[InventorySet.TYPE_OTHER].removeSortHandler(); _deckArea[InventorySet.TYPE_CHARA].visible = true; _deckArea[InventorySet.TYPE_WEAPON].visible = false; //_deckArea[InventorySet.TYPE_EQUIP].visible = false; _deckArea[InventorySet.TYPE_EVENT].visible = false; //_deckArea[InventorySet.TYPE_MONSTER].visible = false; //_deckArea[InventorySet.TYPE_OTHER].visible = false; // 選ばれたデッキは最前線に送る _container.setChildIndex(_deckArea[InventorySet.TYPE_CHARA],_container.numChildren-1); _dataArea[InventorySet.TYPE_CHARA].visible = true; _dataArea[InventorySet.TYPE_WEAPON].visible = false; //_dataArea[InventorySet.TYPE_EQUIP].visible = false; _dataArea[InventorySet.TYPE_EVENT].visible = false; //_dataArea[InventorySet.TYPE_MONSTER].visible = false; //_dataArea[InventorySet.TYPE_OTHER].visible = false; _dataArea[InventorySet.TYPE_CHARA].dupeCount.visible = false; _bg.tabChara.visible = false; _bg.tabEquip.visible = true; _bg.tabEvent.visible = true; _bg.tabMonster.visible = true; _bg.tabOther.visible = true; _bg.setCharaParameter(); break; case InventorySet.TYPE_WEAPON: _binderArea[InventorySet.TYPE_CHARA].visible = false; _binderArea[InventorySet.TYPE_WEAPON].visible = true; _binderArea[InventorySet.TYPE_EQUIP].visible = false; _binderArea[InventorySet.TYPE_EVENT].visible = false; _binderArea[InventorySet.TYPE_MONSTER].visible = false; _binderArea[InventorySet.TYPE_OTHER].visible = false; _binderArea[InventorySet.TYPE_CHARA].removeSortHandler(); _binderArea[InventorySet.TYPE_WEAPON].addSortHandler(); _binderArea[InventorySet.TYPE_EQUIP].removeSortHandler(); _binderArea[InventorySet.TYPE_EVENT].removeSortHandler(); _binderArea[InventorySet.TYPE_MONSTER].removeSortHandler(); _binderArea[InventorySet.TYPE_OTHER].removeSortHandler(); _deckArea[InventorySet.TYPE_CHARA].visible = true; _deckArea[InventorySet.TYPE_WEAPON].visible = true; //_deckArea[InventorySet.TYPE_EQUIP].visible = false; _deckArea[InventorySet.TYPE_EVENT].visible = false; //_deckArea[InventorySet.TYPE_MONSTER].visible = false; //_deckArea[InventorySet.TYPE_OTHER].visible = false; // 選ばれたデッキは最前線に送る _container.setChildIndex(_deckArea[InventorySet.TYPE_WEAPON],_container.numChildren-1); _dataArea[InventorySet.TYPE_CHARA].visible = false; _dataArea[InventorySet.TYPE_WEAPON].visible = true; //_dataArea[InventorySet.TYPE_EQUIP].visible = false; _dataArea[InventorySet.TYPE_EVENT].visible = false; //_dataArea[InventorySet.TYPE_MONSTER].visible = false; //_dataArea[InventorySet.TYPE_OTHER].visible = false; _bg.compo.visible = false; _bg.story.visible = false; _bg.dupe.visible = false; _bg.tabChara.visible = true; _bg.tabEquip.visible = false; _bg.tabEvent.visible = true; _bg.tabMonster.visible = true; _bg.tabOther.visible = true; _bg.setEquipParameter(); break; case InventorySet.TYPE_EQUIP: _binderArea[InventorySet.TYPE_CHARA].visible = false; _binderArea[InventorySet.TYPE_WEAPON].visible = false; _binderArea[InventorySet.TYPE_EQUIP].visible = true; _binderArea[InventorySet.TYPE_EVENT].visible = false; _binderArea[InventorySet.TYPE_MONSTER].visible = false; _binderArea[InventorySet.TYPE_OTHER].visible = false; _binderArea[InventorySet.TYPE_CHARA].removeSortHandler(); _binderArea[InventorySet.TYPE_WEAPON].removeSortHandler(); _binderArea[InventorySet.TYPE_EQUIP].addSortHandler(); _binderArea[InventorySet.TYPE_EVENT].removeSortHandler(); _binderArea[InventorySet.TYPE_MONSTER].removeSortHandler(); _binderArea[InventorySet.TYPE_OTHER].removeSortHandler(); _deckArea[InventorySet.TYPE_CHARA].visible = false; _deckArea[InventorySet.TYPE_WEAPON].visible = false; //_deckArea[InventorySet.TYPE_EQUIP].visible = true; _deckArea[InventorySet.TYPE_EVENT].visible = false; //_deckArea[InventorySet.TYPE_MONSTER].visible = false; //_deckArea[InventorySet.TYPE_OTHER].visible = false; // 選ばれたデッキは最前線に送る _container.setChildIndex(_deckArea[InventorySet.TYPE_EQUIP],_container.numChildren-1); _dataArea[InventorySet.TYPE_CHARA].visible = false; _dataArea[InventorySet.TYPE_WEAPON].visible = false; //_dataArea[InventorySet.TYPE_EQUIP].visible = true; _dataArea[InventorySet.TYPE_EVENT].visible = false; //_dataArea[InventorySet.TYPE_MONSTER].visible = false; //_dataArea[InventorySet.TYPE_OTHER].visible = false; _bg.compo.visible = false; _bg.story.visible = false; _bg.dupe.visible = false; _bg.tabChara.visible = true; _bg.tabEquip.visible = false; _bg.tabEvent.visible = true; _bg.tabMonster.visible = true; _bg.tabOther.visible = true; _bg.setEquipParameter(); break; case InventorySet.TYPE_EVENT: _binderArea[InventorySet.TYPE_CHARA].visible = false; _binderArea[InventorySet.TYPE_WEAPON].visible = false; _binderArea[InventorySet.TYPE_EQUIP].visible = false; _binderArea[InventorySet.TYPE_EVENT].visible = true; _binderArea[InventorySet.TYPE_MONSTER].visible = false; _binderArea[InventorySet.TYPE_OTHER].visible = false; _binderArea[InventorySet.TYPE_CHARA].removeSortHandler(); _binderArea[InventorySet.TYPE_WEAPON].removeSortHandler(); _binderArea[InventorySet.TYPE_EQUIP].removeSortHandler(); _binderArea[InventorySet.TYPE_EVENT].addSortHandler(); _binderArea[InventorySet.TYPE_MONSTER].removeSortHandler(); _binderArea[InventorySet.TYPE_OTHER].removeSortHandler(); _deckArea[InventorySet.TYPE_CHARA].visible = true; _deckArea[InventorySet.TYPE_WEAPON].visible = false; //_deckArea[InventorySet.TYPE_EQUIP].visible = false; _deckArea[InventorySet.TYPE_EVENT].visible = true; //_deckArea[InventorySet.TYPE_MONSTER].visible = false; //_deckArea[InventorySet.TYPE_OTHER].visible = false; // 選ばれたデッキは最前線に送る _container.setChildIndex(_deckArea[InventorySet.TYPE_EVENT],_container.numChildren-1); _dataArea[InventorySet.TYPE_CHARA].visible = false; _dataArea[InventorySet.TYPE_WEAPON].visible = false; //_dataArea[InventorySet.TYPE_EQUIP].visible = false; _dataArea[InventorySet.TYPE_EVENT].visible = true; //_dataArea[InventorySet.TYPE_MONSTER].visible = false; //_dataArea[InventorySet.TYPE_OTHER].visible = false; _bg.compo.visible = false; _bg.story.visible = false; _bg.dupe.visible = false; _bg.tabChara.visible = true; _bg.tabEquip.visible = true; _bg.tabEvent.visible = false; _bg.tabMonster.visible = true; _bg.tabOther.visible = true; _bg.setEventParameter(); break; case InventorySet.TYPE_MONSTER: _binderArea[InventorySet.TYPE_CHARA].visible = false; _binderArea[InventorySet.TYPE_WEAPON].visible = false; _binderArea[InventorySet.TYPE_EQUIP].visible = false; _binderArea[InventorySet.TYPE_EVENT].visible = false; _binderArea[InventorySet.TYPE_MONSTER].visible = true; _binderArea[InventorySet.TYPE_OTHER].visible = false; _binderArea[InventorySet.TYPE_CHARA].removeSortHandler(); _binderArea[InventorySet.TYPE_WEAPON].removeSortHandler(); _binderArea[InventorySet.TYPE_EQUIP].removeSortHandler(); _binderArea[InventorySet.TYPE_EVENT].removeSortHandler(); _binderArea[InventorySet.TYPE_MONSTER].addSortHandler(); _binderArea[InventorySet.TYPE_OTHER].removeSortHandler(); _deckArea[InventorySet.TYPE_CHARA].visible = true; _deckArea[InventorySet.TYPE_WEAPON].visible = false; //_deckArea[InventorySet.TYPE_EQUIP].visible = false; _deckArea[InventorySet.TYPE_EVENT].visible = false; //_deckArea[InventorySet.TYPE_MONSTER].visible = false; //_deckArea[InventorySet.TYPE_OTHER].visible = false; // 選ばれたデッキは最前線に送る _container.setChildIndex(_deckArea[InventorySet.TYPE_CHARA],_container.numChildren-1); _dataArea[InventorySet.TYPE_CHARA].visible = true; _dataArea[InventorySet.TYPE_WEAPON].visible = false; //_dataArea[InventorySet.TYPE_EQUIP].visible = false; _dataArea[InventorySet.TYPE_EVENT].visible = false; //_dataArea[InventorySet.TYPE_MONSTER].visible = true; //_dataArea[InventorySet.TYPE_OTHER].visible = false; _dataArea[InventorySet.TYPE_CHARA].dupeCount.visible = false; _bg.tabChara.visible = true; _bg.tabEquip.visible = true; _bg.tabEvent.visible = true; _bg.tabMonster.visible = false; _bg.tabOther.visible = true; _bg.setMonsterParameter(); break; case InventorySet.TYPE_OTHER: _binderArea[InventorySet.TYPE_CHARA].visible = false; _binderArea[InventorySet.TYPE_WEAPON].visible = false; _binderArea[InventorySet.TYPE_EQUIP].visible = false; _binderArea[InventorySet.TYPE_EVENT].visible = false; _binderArea[InventorySet.TYPE_MONSTER].visible = false; _binderArea[InventorySet.TYPE_OTHER].visible = true; _binderArea[InventorySet.TYPE_CHARA].removeSortHandler(); _binderArea[InventorySet.TYPE_WEAPON].removeSortHandler(); _binderArea[InventorySet.TYPE_EQUIP].removeSortHandler(); _binderArea[InventorySet.TYPE_EVENT].removeSortHandler(); _binderArea[InventorySet.TYPE_MONSTER].removeSortHandler(); _binderArea[InventorySet.TYPE_OTHER].addSortHandler(); _deckArea[InventorySet.TYPE_CHARA].visible = true; _deckArea[InventorySet.TYPE_WEAPON].visible = false; //_deckArea[InventorySet.TYPE_EQUIP].visible = false; _deckArea[InventorySet.TYPE_EVENT].visible = false; //_deckArea[InventorySet.TYPE_MONSTER].visible = false; //_deckArea[InventorySet.TYPE_OTHER].visible = true; // 選ばれたデッキは最前線に送る _container.setChildIndex(_deckArea[InventorySet.TYPE_CHARA],_container.numChildren-1); _dataArea[InventorySet.TYPE_CHARA].visible = true; _dataArea[InventorySet.TYPE_WEAPON].visible = false; //_dataArea[InventorySet.TYPE_EQUIP].visible = false; _dataArea[InventorySet.TYPE_EVENT].visible = false; //_dataArea[InventorySet.TYPE_MONSTER].visible = false; //_dataArea[InventorySet.TYPE_OTHER].visible = true; _dataArea[InventorySet.TYPE_CHARA].dupeCount.visible = false; _bg.tabChara.visible = true; _bg.tabEquip.visible = true; _bg.tabEvent.visible = true; _bg.tabMonster.visible = true; _bg.tabOther.visible = false; _bg.setOtherParameter(); break; } _editType = val; // タブがキャラの時だけ、表示 if (_editType == InventorySet.TYPE_CHARA) { _bg.search = true; } else { _bg.search = false; } } CONFIG::PAYMENT private function hide():void { if(_SELL_TIPS) { _container.removeChild(RealMoneyShopView.onShopButton(RealMoneyShopView.TYPE_EX_CARD)); } next(hide2); } CONFIG::NOT_PAYMENT private function hide():void { // addChild(RealMoneyShopView.onShopButton(RealMoneyShopView.TYPE_EX_CARD)); next(hide2); } private function hide2():void { var pExec:ParallelExecutor = new ParallelExecutor(); pExec.addThread(new BeTweenAS3Thread(_dupeSendPanel, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_title, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_titleJ, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_bg, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_sortArea, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_selectArea, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_dataArea[_deckEdit.substanceEditType(_editType)], {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_binderArea[_editType], {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_deckArea[_deckEdit.substanceEditType(_editType)], {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_deckArea[InventorySet.TYPE_CHARA], {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); // pExec.addThread(new BeTweenAS3Thread(_deckSetButton, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.addThread(new BeTweenAS3Thread(_avatarView, {alpha:0.0}, null, 0.8/Unlight.SPEED, BeTweenAS3Thread.EASE_OUT_SINE, 0.0 ,false)); pExec.start(); pExec.join(); if (_ctrl.cardInvUpdating) { Unlight.INS.loadingReset(); Unlight.INS.loadingStart(); next(updateWait); } else { next(hide3); } // next(hide3); } // データ更新待ち private function updateWait():void { log.writeLog(log.LV_DEBUG, this, ""updateWait""); if (_ctrl.cardInvUpdating) { next(updateWait); } else { log.writeLog(log.LV_DEBUG, this, ""updateWait end""); Unlight.INS.loadingEnd(); next(loadWait); } } // ロードオブジェ待ち private function loadWait():void { log.writeLog(log.LV_DEBUG, this, ""loadWait""); if (Unlight.INS.loadingDisable()) { log.writeLog(log.LV_DEBUG, this, ""loadWait end""); next(hide3); } else { next(loadWait); } } // 配置オブジェの表示 private function hide3():void { var pExec:ParallelExecutor = new ParallelExecutor(); pExec.addThread(_bg.getHideThread()); // 背景 pExec.addThread(_ccDataArea.getHideThread()); // データ pExec.addThread(_wpDataArea.getHideThread()); // データ //pExec.addThread(_eqDataArea.getHideThread()); // データ pExec.addThread(_evDataArea.getHideThread()); // データ //pExec.addThread(_mcDataArea.getHideThread()); // データ //pExec.addThread(_ocDataArea.getHideThread()); // データ pExec.addThread(_ccBinderArea.getHideThread()); // バインダー pExec.addThread(_wpBinderArea.getHideThread()); // バインダー pExec.addThread(_eqBinderArea.getHideThread()); // バインダー pExec.addThread(_evBinderArea.getHideThread()); // バインダー pExec.addThread(_mcBinderArea.getHideThread()); // バインダー pExec.addThread(_ocBinderArea.getHideThread()); // バインダー pExec.addThread(_ccDeckArea.getHideThread()); // デッキ pExec.addThread(_wpDeckArea.getHideThread()); // デッキ //pExec.addThread(_eqDeckArea.getHideThread()); // デッキ pExec.addThread(_evDeckArea.getHideThread()); // デッキ //pExec.addThread(_mcDeckArea.getHideThread()); // デッキ //pExec.addThread(_ocDeckArea.getHideThread()); // デッキ pExec.addThread(_selectArea.getHideThread()); pExec.addThread(_sortArea.getHideThread()); // ソート pExec.addThread(_avatarView.getHideThread()); // デッキ // pExec.addThread(_deckSetButton.getHideThread()); // デッキ pExec.start(); pExec.join(); next(exit); } private function exit():void { // イベントの消去 // _bg.exit.removeEventListener(MouseEvent.CLICK, pushExitButtonHandler); // _bg.deckCreate.removeEventListener(MouseEvent.CLICK, pushCreateButtonHandler); RealMoneyShopView.shopCloseButton.removeEventListener(MouseEvent.CLICK, rmShopCloseclickHandler); _avatarView.exitButton.removeEventListener(MouseEvent.CLICK, pushExitButtonHandler); _ctrl.removeEventListener(LobbyCtrl.REQUEST_COPY_CARD, showDupeSendPanelHandler); _ctrl.removeEventListener(CharaCardEvent.COPY_CHARA_CARD, copyDoneHandler); _dupeSendPanel.yesButton.removeEventListener(MouseEvent.CLICK, pushYesDupeButtonHandler); _dupeSendPanel.noButton.removeEventListener(MouseEvent.CLICK, pushNoDupeButtonHandler); _bg.deckDelete.removeEventListener(MouseEvent.CLICK, pushDeleteButtonHandler); _bg.back.removeEventListener(MouseEvent.CLICK, pushLeftButtonHandler); _bg.next.removeEventListener(MouseEvent.CLICK, pushRightButtonHandler); _bg.binderNext.removeEventListener(MouseEvent.CLICK, pushNextButtonHandler); _bg.binderPrev.removeEventListener(MouseEvent.CLICK, pushPrevButtonHandler); _bg.tabChara.removeEventListener(MouseEvent.CLICK, charaCardTabClickHandler); _bg.tabEquip.removeEventListener(MouseEvent.CLICK, weaponCardTabClickHandler); _bg.tabEvent.removeEventListener(MouseEvent.CLICK, eventCardTabClickHandler); _bg.tabMonster.removeEventListener(MouseEvent.CLICK, monsterCardTabClickHandler); _bg.tabOther.removeEventListener(MouseEvent.CLICK, otherCardTabClickHandler); _deckEdit.removeEventListener(DeckEditor.CHANGE_TYPE, chnageEditTypeHandler); Player.instance.avatar.removeEventListener(AvatarSaleEvent.SALE_FINISH, saleFinishHandler); // レイドヘルプイベント GlobalChatCtrl.instance.removeEventListener(RaidHelpEvent.ACCEPT,helpAcceptHandler); // _deckSetButton.removeEventListener(MouseEvent.CLICK, pushCurrentButtonHandler); _bg.final(); _bg = null; log.writeLog(log.LV_INFO, this, ""edit exit""); } // 終了関数 override protected function finalize():void { RemoveChild.apply(_title); RemoveChild.apply(_titleJ); RemoveChild.apply(_dupeSendPanel); RemoveChild.apply(_compoContainer); RemoveChild.apply(_avatarContainer); RemoveChild.apply(_container); log.writeLog (log.LV_WARN,this,""edit end""); } // バインダーを更新 private function rmShopCloseclickHandler(e:Event):void { _binderArea[_editType].update(); } } } ",12052,True,2789.401210432148,median "/* Copyright (c) 2012 Josh Tynjala 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. */ package feathers.themes { import feathers.controls.Alert; import feathers.controls.Button; import feathers.controls.ButtonGroup; import feathers.controls.Callout; import feathers.controls.Check; import feathers.controls.GroupedList; import feathers.controls.Header; import feathers.controls.ImageLoader; import feathers.controls.Label; import feathers.controls.List; import feathers.controls.NumericStepper; import feathers.controls.PageIndicator; import feathers.controls.Panel; import feathers.controls.PanelScreen; import feathers.controls.PickerList; import feathers.controls.ProgressBar; import feathers.controls.Radio; import feathers.controls.Screen; import feathers.controls.ScrollContainer; import feathers.controls.ScrollText; import feathers.controls.SimpleScrollBar; import feathers.controls.Slider; import feathers.controls.TabBar; import feathers.controls.TextInput; import feathers.controls.ToggleSwitch; import feathers.controls.popups.CalloutPopUpContentManager; import feathers.controls.popups.VerticalCenteredPopUpContentManager; import feathers.controls.renderers.BaseDefaultItemRenderer; import feathers.controls.renderers.DefaultGroupedListHeaderOrFooterRenderer; import feathers.controls.renderers.DefaultGroupedListItemRenderer; import feathers.controls.renderers.DefaultListItemRenderer; import feathers.controls.text.BitmapFontTextRenderer; import feathers.controls.text.StageTextTextEditor; import feathers.core.DisplayListWatcher; import feathers.core.FeathersControl; import feathers.core.PopUpManager; import feathers.display.Scale9Image; import feathers.layout.HorizontalLayout; import feathers.layout.VerticalLayout; import feathers.skins.SmartDisplayObjectStateValueSelector; import feathers.skins.StandardIcons; import feathers.system.DeviceCapabilities; import feathers.text.BitmapFontTextFormat; import feathers.textures.Scale3Textures; import feathers.textures.Scale9Textures; import feathers.utils.math.roundToNearest; import flash.display.BitmapData; import flash.geom.Rectangle; import flash.text.TextFormat; import flash.text.TextFormatAlign; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.DisplayObjectContainer; import starling.display.Image; import starling.display.Quad; import starling.events.Event; import starling.text.BitmapFont; import starling.textures.Texture; import starling.textures.TextureAtlas; import starling.textures.TextureSmoothing; public class MinimalMobileTheme extends DisplayListWatcher { public static const COMPONENT_NAME_PICKER_LIST_ITEM_RENDERER:String = ""feathers-mobile-picker-list-item-renderer""; [Embed(source=""/../assets/images/minimal.png"")] protected static const ATLAS_IMAGE:Class; [Embed(source=""/../assets/images/minimal.xml"",mimeType=""application/octet-stream"")] protected static const ATLAS_XML:Class; [Embed(source=""/../assets/fonts/pf_ronda_seven.fnt"",mimeType=""application/octet-stream"")] protected static const ATLAS_FONT_XML:Class; protected static const SCALE_9_GRID:Rectangle = new Rectangle(9, 9, 2, 2); protected static const BUTTON_SCALE_9_GRID:Rectangle = new Rectangle(5, 5, 1, 1); protected static const BUTTON_DOWN_SCALE_9_GRID:Rectangle = new Rectangle(9, 9, 1, 1); protected static const SCROLLBAR_THUMB_SCALE_9_GRID:Rectangle = new Rectangle(1, 1, 2, 2); protected static const TAB_SCALE_9_GRID:Rectangle = new Rectangle(25, 21, 1, 1); protected static const HEADER_SCALE_9_GRID:Rectangle = new Rectangle(0, 5, 3, 1); protected static const LIST_ITEM_SCALE_9_GRID:Rectangle = new Rectangle(5, 5, 1, 1); protected static const BACK_BUTTON_SCALE_REGION1:int = 30; protected static const BACK_BUTTON_SCALE_REGION2:int = 1; protected static const FORWARD_BUTTON_SCALE_REGION1:int = 9; protected static const FORWARD_BUTTON_SCALE_REGION2:int = 1; protected static const BACKGROUND_COLOR:uint = 0xf3f3f3; protected static const LIST_BACKGROUND_COLOR:uint = 0xf8f8f8; protected static const LIST_HEADER_BACKGROUND_COLOR:uint = 0xeeeeee; protected static const PRIMARY_TEXT_COLOR:uint = 0x666666; protected static const DISABLED_TEXT_COLOR:uint = 0x999999; protected static const MODAL_OVERLAY_COLOR:uint = 0x666666; protected static const MODAL_OVERLAY_ALPHA:Number = 0.8; protected static const ORIGINAL_DPI_IPHONE_RETINA:int = 326; protected static const ORIGINAL_DPI_IPAD_RETINA:int = 264; protected static function textRendererFactory():BitmapFontTextRenderer { const renderer:BitmapFontTextRenderer = new BitmapFontTextRenderer(); //since it's a pixel font, we don't want to smooth it. renderer.smoothing = TextureSmoothing.NONE; return renderer; } protected static function textEditorFactory():StageTextTextEditor { return new StageTextTextEditor(); } protected static function popUpOverlayFactory():DisplayObject { const quad:Quad = new Quad(100, 100, MODAL_OVERLAY_COLOR); quad.alpha = MODAL_OVERLAY_ALPHA; return quad; } public function MinimalMobileTheme(container:DisplayObjectContainer = null, scaleToDPI:Boolean = true) { if(!container) { container = Starling.current.stage; } super(container); Starling.current.nativeStage.color = BACKGROUND_COLOR; if(this.root.stage) { this.root.stage.color = BACKGROUND_COLOR; } else { this.root.addEventListener(Event.ADDED_TO_STAGE, root_addedToStageHandler); } this._scaleToDPI = scaleToDPI; this.initialize(); } protected var _originalDPI:int; public function get originalDPI():int { return this._originalDPI; } protected var _scaleToDPI:Boolean; public function get scaleToDPI():Boolean { return this._scaleToDPI; } protected var scale:Number; protected var fontSize:int; protected var inputFontSize:int; protected var atlas:TextureAtlas; protected var atlasBitmapData:BitmapData; protected var buttonUpSkinTextures:Scale9Textures; protected var buttonDownSkinTextures:Scale9Textures; protected var buttonDisabledSkinTextures:Scale9Textures; protected var buttonSelectedSkinTextures:Scale9Textures; protected var buttonSelectedDisabledSkinTextures:Scale9Textures; protected var buttonCallToActionUpSkinTextures:Scale9Textures; protected var buttonQuietUpSkinTextures:Scale9Textures; protected var buttonDangerUpSkinTextures:Scale9Textures; protected var buttonDangerDownSkinTextures:Scale9Textures; protected var buttonBackUpSkinTextures:Scale3Textures; protected var buttonBackDownSkinTextures:Scale3Textures; protected var buttonBackDisabledSkinTextures:Scale3Textures; protected var buttonForwardUpSkinTextures:Scale3Textures; protected var buttonForwardDownSkinTextures:Scale3Textures; protected var buttonForwardDisabledSkinTextures:Scale3Textures; protected var tabDownSkinTextures:Scale9Textures; protected var tabSelectedSkinTextures:Scale9Textures; protected var tabSelectedDisabledSkinTextures:Scale9Textures; protected var thumbSkinTextures:Scale9Textures; protected var thumbDisabledSkinTextures:Scale9Textures; protected var scrollBarThumbSkinTextures:Scale9Textures; protected var insetBackgroundSkinTextures:Scale9Textures; protected var insetBackgroundDisabledSkinTextures:Scale9Textures; protected var dropDownArrowTexture:Texture; protected var searchIconTexture:Texture; protected var listItemUpTextures:Scale9Textures; protected var listItemDownTextures:Scale9Textures; protected var listItemSelectedTextures:Scale9Textures; protected var pickerListItemSelectedIconTexture:Texture; protected var headerSkinTextures:Scale9Textures; protected var popUpBackgroundSkinTextures:Scale9Textures; protected var calloutTopArrowSkinTexture:Texture; protected var calloutBottomArrowSkinTexture:Texture; protected var calloutLeftArrowSkinTexture:Texture; protected var calloutRightArrowSkinTexture:Texture; protected var checkIconTexture:Texture; protected var checkDisabledIconTexture:Texture; protected var checkSelectedIconTexture:Texture; protected var checkSelectedDisabledIconTexture:Texture; protected var radioIconTexture:Texture; protected var radioDisabledIconTexture:Texture; protected var radioSelectedIconTexture:Texture; protected var radioSelectedDisabledIconTexture:Texture; protected var pageIndicatorNormalSkinTexture:Texture; protected var pageIndicatorSelectedSkinTexture:Texture; protected var bitmapFont:BitmapFont; protected var primaryTextFormat:BitmapFontTextFormat; protected var disabledTextFormat:BitmapFontTextFormat; override public function dispose():void { if(this.root) { this.root.removeEventListener(Event.ADDED_TO_STAGE, root_addedToStageHandler); } if(this.atlas) { this.atlas.dispose(); this.atlas = null; } if(this.atlasBitmapData) { this.atlasBitmapData.dispose(); this.atlasBitmapData = null; } super.dispose(); } protected function initialize():void { const scaledDPI:int = DeviceCapabilities.dpi / Starling.contentScaleFactor; if(this._scaleToDPI) { if(DeviceCapabilities.isTablet(Starling.current.nativeStage)) { this._originalDPI = ORIGINAL_DPI_IPAD_RETINA; } else { this._originalDPI = ORIGINAL_DPI_IPHONE_RETINA; } } else { this._originalDPI = scaledDPI; } //our min scale is 0.25 because lines in the graphics are four //pixels wide and this will keep them crisp. this.scale = Math.max(0.25, scaledDPI / this._originalDPI); //since it's a pixel font, we want a multiple of the original size, //which, in this case, is 8. this.fontSize = Math.max(4, roundToNearest(24 * this.scale, 8)); this.inputFontSize = 26 * this.scale; PopUpManager.overlayFactory = popUpOverlayFactory; Callout.stagePaddingTop = Callout.stagePaddingRight = Callout.stagePaddingBottom = Callout.stagePaddingLeft = 16 * this.scale; const atlasBitmapData:BitmapData = (new ATLAS_IMAGE()).bitmapData; this.atlas = new TextureAtlas(Texture.fromBitmapData(atlasBitmapData, false), XML(new ATLAS_XML())); if(Starling.handleLostContext) { this.atlasBitmapData = atlasBitmapData; } else { atlasBitmapData.dispose(); } this.bitmapFont = new BitmapFont(this.atlas.getTexture(""pf_ronda_seven_0""), XML(new ATLAS_FONT_XML())); this.buttonUpSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-up-skin""), BUTTON_SCALE_9_GRID); this.buttonDownSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-down-skin""), BUTTON_DOWN_SCALE_9_GRID); this.buttonDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-disabled-skin""), BUTTON_SCALE_9_GRID); this.buttonSelectedSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-selected-skin""), BUTTON_DOWN_SCALE_9_GRID); this.buttonSelectedDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-selected-disabled-skin""), BUTTON_DOWN_SCALE_9_GRID); this.buttonCallToActionUpSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-call-to-action-up-skin""), BUTTON_SCALE_9_GRID); this.buttonQuietUpSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-quiet-up-skin""), BUTTON_SCALE_9_GRID); this.buttonDangerUpSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-danger-up-skin""), BUTTON_SCALE_9_GRID); this.buttonDangerDownSkinTextures = new Scale9Textures(this.atlas.getTexture(""button-danger-down-skin""), BUTTON_DOWN_SCALE_9_GRID); this.buttonBackUpSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-back-up-skin""), BACK_BUTTON_SCALE_REGION1, BACK_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL); this.buttonBackDownSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-back-down-skin""), BACK_BUTTON_SCALE_REGION1, BACK_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL); this.buttonBackDisabledSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-back-disabled-skin""), BACK_BUTTON_SCALE_REGION1, BACK_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL); this.buttonForwardUpSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-forward-up-skin""), FORWARD_BUTTON_SCALE_REGION1, FORWARD_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL); this.buttonForwardDownSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-forward-down-skin""), FORWARD_BUTTON_SCALE_REGION1, FORWARD_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL); this.buttonForwardDisabledSkinTextures = new Scale3Textures(this.atlas.getTexture(""button-forward-disabled-skin""), FORWARD_BUTTON_SCALE_REGION1, FORWARD_BUTTON_SCALE_REGION2, Scale3Textures.DIRECTION_HORIZONTAL); this.tabDownSkinTextures = new Scale9Textures(this.atlas.getTexture(""tab-down-skin""), TAB_SCALE_9_GRID); this.tabSelectedSkinTextures = new Scale9Textures(this.atlas.getTexture(""tab-selected-skin""), TAB_SCALE_9_GRID); this.tabSelectedDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""tab-selected-disabled-skin""), TAB_SCALE_9_GRID); this.thumbSkinTextures = new Scale9Textures(this.atlas.getTexture(""thumb-skin""), SCALE_9_GRID); this.thumbDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""thumb-disabled-skin""), SCALE_9_GRID); this.scrollBarThumbSkinTextures = new Scale9Textures(this.atlas.getTexture(""scrollbar-thumb-skin""), SCROLLBAR_THUMB_SCALE_9_GRID); this.insetBackgroundSkinTextures = new Scale9Textures(this.atlas.getTexture(""inset-background-skin""), SCALE_9_GRID); this.insetBackgroundDisabledSkinTextures = new Scale9Textures(this.atlas.getTexture(""inset-background-disabled-skin""), SCALE_9_GRID); this.dropDownArrowTexture = this.atlas.getTexture(""drop-down-arrow""); this.searchIconTexture = this.atlas.getTexture(""search-icon""); this.listItemUpTextures = new Scale9Textures(this.atlas.getTexture(""list-item-up""), LIST_ITEM_SCALE_9_GRID); this.listItemDownTextures = new Scale9Textures(this.atlas.getTexture(""list-item-down""), LIST_ITEM_SCALE_9_GRID); this.listItemSelectedTextures = new Scale9Textures(this.atlas.getTexture(""list-item-selected""), LIST_ITEM_SCALE_9_GRID); this.pickerListItemSelectedIconTexture = this.atlas.getTexture(""picker-list-item-selected-icon""); this.headerSkinTextures = new Scale9Textures(this.atlas.getTexture(""header-skin""), HEADER_SCALE_9_GRID); this.popUpBackgroundSkinTextures = new Scale9Textures(this.atlas.getTexture(""callout-background-skin""), BUTTON_SCALE_9_GRID); this.calloutTopArrowSkinTexture = this.atlas.getTexture(""callout-arrow-top""); this.calloutBottomArrowSkinTexture = this.atlas.getTexture(""callout-arrow-bottom""); this.calloutLeftArrowSkinTexture = this.atlas.getTexture(""callout-arrow-left""); this.calloutRightArrowSkinTexture = this.atlas.getTexture(""callout-arrow-right""); this.checkIconTexture = this.atlas.getTexture(""check-icon""); this.checkDisabledIconTexture = this.atlas.getTexture(""check-disabled-icon""); this.checkSelectedIconTexture = this.atlas.getTexture(""check-selected-icon""); this.checkSelectedDisabledIconTexture = this.atlas.getTexture(""check-selected-disabled-icon""); this.radioIconTexture = this.atlas.getTexture(""radio-icon""); this.radioDisabledIconTexture = this.atlas.getTexture(""radio-disabled-icon""); this.radioSelectedIconTexture = this.atlas.getTexture(""radio-selected-icon""); this.radioSelectedDisabledIconTexture = this.atlas.getTexture(""radio-selected-disabled-icon""); this.pageIndicatorNormalSkinTexture = this.atlas.getTexture(""page-indicator-normal-skin""); this.pageIndicatorSelectedSkinTexture = this.atlas.getTexture(""page-indicator-selected-skin""); StandardIcons.listDrillDownAccessoryTexture = this.atlas.getTexture(""list-accessory-drill-down-icon""); this.primaryTextFormat = new BitmapFontTextFormat(bitmapFont, this.fontSize, PRIMARY_TEXT_COLOR); this.disabledTextFormat = new BitmapFontTextFormat(bitmapFont, this.fontSize, DISABLED_TEXT_COLOR); FeathersControl.defaultTextRendererFactory = textRendererFactory; FeathersControl.defaultTextEditorFactory = textEditorFactory; this.setInitializerForClassAndSubclasses(Screen, screenInitializer); this.setInitializerForClassAndSubclasses(PanelScreen, panelScreenInitializer); this.setInitializerForClass(Label, labelInitializer); this.setInitializerForClass(ScrollText, scrollTextInitializer); this.setInitializerForClass(BitmapFontTextRenderer, itemRendererAccessoryLabelInitializer, BaseDefaultItemRenderer.DEFAULT_CHILD_NAME_ACCESSORY_LABEL); this.setInitializerForClass(BitmapFontTextRenderer, alertMessageInitializer, Alert.DEFAULT_CHILD_NAME_MESSAGE); this.setInitializerForClass(Button, buttonInitializer); this.setInitializerForClass(Button, buttonCallToActionInitializer, Button.ALTERNATE_NAME_CALL_TO_ACTION_BUTTON); this.setInitializerForClass(Button, buttonQuietInitializer, Button.ALTERNATE_NAME_QUIET_BUTTON); this.setInitializerForClass(Button, buttonDangerInitializer, Button.ALTERNATE_NAME_DANGER_BUTTON); this.setInitializerForClass(Button, buttonBackInitializer, Button.ALTERNATE_NAME_BACK_BUTTON); this.setInitializerForClass(Button, buttonForwardInitializer, Button.ALTERNATE_NAME_FORWARD_BUTTON); this.setInitializerForClass(Button, buttonGroupButtonInitializer, ButtonGroup.DEFAULT_CHILD_NAME_BUTTON); this.setInitializerForClass(Button, sliderThumbInitializer, Slider.DEFAULT_CHILD_NAME_THUMB); this.setInitializerForClass(Button, simpleScrollBarThumbInitializer, SimpleScrollBar.DEFAULT_CHILD_NAME_THUMB); this.setInitializerForClass(Button, nothingInitializer, Slider.DEFAULT_CHILD_NAME_MINIMUM_TRACK); this.setInitializerForClass(Button, nothingInitializer, Slider.DEFAULT_CHILD_NAME_MAXIMUM_TRACK); this.setInitializerForClass(Button, toggleSwitchOnTrackInitializer, ToggleSwitch.DEFAULT_CHILD_NAME_ON_TRACK); this.setInitializerForClass(Button, toggleSwitchThumbInitializer, ToggleSwitch.DEFAULT_CHILD_NAME_THUMB); this.setInitializerForClass(Button, tabInitializer, TabBar.DEFAULT_CHILD_NAME_TAB); this.setInitializerForClass(Button, pickerListButtonInitializer, PickerList.DEFAULT_CHILD_NAME_BUTTON); this.setInitializerForClass(ButtonGroup, buttonGroupInitializer); this.setInitializerForClass(ButtonGroup, alertButtonGroupInitializer, Alert.DEFAULT_CHILD_NAME_BUTTON_GROUP); this.setInitializerForClass(Slider, sliderInitializer); this.setInitializerForClass(ToggleSwitch, toggleSwitchInitializer); this.setInitializerForClass(NumericStepper, numericStepperInitializer); this.setInitializerForClass(Check, checkInitializer); this.setInitializerForClass(Radio, radioInitializer); this.setInitializerForClass(DefaultListItemRenderer, itemRendererInitializer); this.setInitializerForClass(DefaultListItemRenderer, pickerListItemRendererInitializer, COMPONENT_NAME_PICKER_LIST_ITEM_RENDERER); this.setInitializerForClass(DefaultGroupedListItemRenderer, itemRendererInitializer); this.setInitializerForClass(DefaultGroupedListHeaderOrFooterRenderer, headerOrFooterRendererInitializer); this.setInitializerForClass(DefaultGroupedListHeaderOrFooterRenderer, insetHeaderOrFooterRendererInitializer, GroupedList.ALTERNATE_CHILD_NAME_INSET_HEADER_RENDERER); this.setInitializerForClass(DefaultGroupedListHeaderOrFooterRenderer, insetHeaderOrFooterRendererInitializer, GroupedList.ALTERNATE_CHILD_NAME_INSET_FOOTER_RENDERER); this.setInitializerForClass(List, listInitializer); this.setInitializerForClass(List, nothingInitializer, PickerList.DEFAULT_CHILD_NAME_LIST); this.setInitializerForClass(GroupedList, groupedListInitializer); this.setInitializerForClass(GroupedList, groupedListInsetInitializer, GroupedList.ALTERNATE_NAME_INSET_GROUPED_LIST); this.setInitializerForClass(PickerList, pickerListInitializer); this.setInitializerForClass(Header, headerInitializer); this.setInitializerForClass(Header, panelHeaderInitializer, Panel.DEFAULT_CHILD_NAME_HEADER); this.setInitializerForClass(Header, panelHeaderInitializer, Alert.DEFAULT_CHILD_NAME_HEADER); this.setInitializerForClass(TextInput, textInputInitializer); this.setInitializerForClass(TextInput, searchTextInputInitializer, TextInput.ALTERNATE_NAME_SEARCH_TEXT_INPUT); this.setInitializerForClass(TextInput, numericStepperTextInputInitializer, NumericStepper.DEFAULT_CHILD_NAME_TEXT_INPUT); this.setInitializerForClass(PageIndicator, pageIndicatorInitializer); this.setInitializerForClass(ProgressBar, progressBarInitializer); this.setInitializerForClass(Callout, calloutInitializer); this.setInitializerForClass(Panel, panelInitializer); this.setInitializerForClass(Alert, alertInitializer); this.setInitializerForClass(ScrollContainer, scrollContainerToolbarInitializer, ScrollContainer.ALTERNATE_NAME_TOOLBAR); } protected function pageIndicatorNormalSymbolFactory():DisplayObject { const symbol:ImageLoader = new ImageLoader(); symbol.source = this.pageIndicatorNormalSkinTexture; symbol.textureScale = this.scale; return symbol; } protected function pageIndicatorSelectedSymbolFactory():DisplayObject { const symbol:ImageLoader = new ImageLoader(); symbol.source = this.pageIndicatorSelectedSkinTexture; symbol.textureScale = this.scale; return symbol; } protected function imageLoaderFactory():ImageLoader { const image:ImageLoader = new ImageLoader(); image.smoothing = TextureSmoothing.NONE; image.textureScale = this.scale; return image; } protected function nothingInitializer(target:DisplayObject):void { //if this is assigned as an initializer, chances are the target will //be a subcomponent of something. the initializer for this //component's parent is probably handing the initializing for the //target too. } protected function screenInitializer(screen:Screen):void { screen.originalDPI = this._originalDPI; } protected function panelScreenInitializer(screen:PanelScreen):void { screen.originalDPI = this._originalDPI; } protected function labelInitializer(label:Label):void { label.textRendererProperties.textFormat = this.primaryTextFormat; label.textRendererProperties.disabledTextFormat = this.disabledTextFormat; } protected function itemRendererAccessoryLabelInitializer(renderer:BitmapFontTextRenderer):void { renderer.textFormat = this.primaryTextFormat; } protected function alertMessageInitializer(renderer:BitmapFontTextRenderer):void { renderer.wordWrap = true; renderer.textFormat = this.primaryTextFormat; } protected function scrollTextInitializer(text:ScrollText):void { text.textFormat = new TextFormat(""PF Ronda Seven,Roboto,Helvetica,Arial,_sans"", this.fontSize, PRIMARY_TEXT_COLOR); text.paddingTop = text.paddingBottom = text.paddingLeft = 32 * this.scale; text.paddingRight = 36 * this.scale; } protected function baseButtonInitializer(button:Button):void { button.defaultLabelProperties.textFormat = this.primaryTextFormat; button.disabledLabelProperties.textFormat = this.disabledTextFormat; button.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat; button.paddingTop = button.paddingBottom = 8 * this.scale; button.paddingLeft = button.paddingRight = 16 * this.scale; button.gap = 12 * this.scale; button.minWidth = 66 * this.scale; button.minHeight = 66 * this.scale; button.minTouchWidth = button.minTouchHeight = 88 * this.scale; } protected function buttonInitializer(button:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.buttonUpSkinTextures; skinSelector.defaultSelectedValue = this.buttonSelectedSkinTextures; skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, false); skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, true); skinSelector.setValueForState(this.buttonDisabledSkinTextures, Button.STATE_DISABLED, false); skinSelector.setValueForState(this.buttonSelectedDisabledSkinTextures, Button.STATE_DISABLED, true); skinSelector.displayObjectProperties = { width: 66 * this.scale, height: 66 * this.scale, textureScale: this.scale }; button.stateToSkinFunction = skinSelector.updateValue; this.baseButtonInitializer(button); } protected function buttonCallToActionInitializer(button:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.buttonCallToActionUpSkinTextures; skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, false); skinSelector.setValueForState(this.buttonDisabledSkinTextures, Button.STATE_DISABLED, false); skinSelector.displayObjectProperties = { width: 66 * this.scale, height: 66 * this.scale, textureScale: this.scale }; button.stateToSkinFunction = skinSelector.updateValue; this.baseButtonInitializer(button); } protected function buttonQuietInitializer(button:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.buttonQuietUpSkinTextures; skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, false); skinSelector.setValueForState(this.buttonDisabledSkinTextures, Button.STATE_DISABLED, false); skinSelector.displayObjectProperties = { width: 66 * this.scale, height: 66 * this.scale, textureScale: this.scale }; button.stateToSkinFunction = skinSelector.updateValue; this.baseButtonInitializer(button); } protected function buttonDangerInitializer(button:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.buttonDangerUpSkinTextures; skinSelector.setValueForState(this.buttonDangerDownSkinTextures, Button.STATE_DOWN, false); skinSelector.setValueForState(this.buttonDisabledSkinTextures, Button.STATE_DISABLED, false); skinSelector.displayObjectProperties = { width: 66 * this.scale, height: 66 * this.scale, textureScale: this.scale }; button.stateToSkinFunction = skinSelector.updateValue; this.baseButtonInitializer(button); } protected function buttonBackInitializer(button:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.buttonBackUpSkinTextures; skinSelector.setValueForState(this.buttonBackDownSkinTextures, Button.STATE_DOWN, false); skinSelector.setValueForState(this.buttonBackDisabledSkinTextures, Button.STATE_DISABLED, false); skinSelector.displayObjectProperties = { width: 66 * this.scale, height: 66 * this.scale, textureScale: this.scale }; button.stateToSkinFunction = skinSelector.updateValue; this.baseButtonInitializer(button); button.paddingLeft = 38 * this.scale; } protected function buttonForwardInitializer(button:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.buttonForwardUpSkinTextures; skinSelector.setValueForState(this.buttonForwardDownSkinTextures, Button.STATE_DOWN, false); skinSelector.setValueForState(this.buttonForwardDisabledSkinTextures, Button.STATE_DISABLED, false); skinSelector.displayObjectProperties = { width: 66 * this.scale, height: 66 * this.scale, textureScale: this.scale }; button.stateToSkinFunction = skinSelector.updateValue; this.baseButtonInitializer(button); button.paddingRight = 38 * this.scale } protected function buttonGroupButtonInitializer(button:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.buttonUpSkinTextures; skinSelector.defaultSelectedValue = this.buttonSelectedSkinTextures; skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, false); skinSelector.setValueForState(this.buttonDownSkinTextures, Button.STATE_DOWN, true); skinSelector.setValueForState(this.buttonSelectedSkinTextures, Button.STATE_DISABLED, false); skinSelector.setValueForState(this.buttonSelectedDisabledSkinTextures, Button.STATE_DISABLED, true); skinSelector.displayObjectProperties = { width: 88 * this.scale, height: 88 * this.scale, textureScale: this.scale }; button.stateToSkinFunction = skinSelector.updateValue; button.defaultLabelProperties.textFormat = this.primaryTextFormat; button.disabledLabelProperties.textFormat = this.disabledTextFormat; button.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat; button.paddingTop = button.paddingBottom = 8 * this.scale; button.paddingLeft = button.paddingRight = 16 * this.scale; button.gap = 12 * this.scale; button.minWidth = 88 * this.scale; button.minHeight = 88 * this.scale; button.minTouchWidth = button.minTouchHeight = 88 * this.scale; } protected function tabInitializer(tab:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.headerSkinTextures; skinSelector.defaultSelectedValue = this.tabSelectedSkinTextures; skinSelector.setValueForState(this.tabDownSkinTextures, Button.STATE_DOWN, false); skinSelector.setValueForState(this.tabSelectedDisabledSkinTextures, Button.STATE_DISABLED, true); skinSelector.displayObjectProperties = { width: 88 * this.scale, height: 88 * this.scale, textureScale: this.scale }; tab.stateToSkinFunction = skinSelector.updateValue; tab.defaultLabelProperties.textFormat = this.primaryTextFormat; tab.disabledLabelProperties.textFormat = this.disabledTextFormat; tab.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat; tab.iconPosition = Button.ICON_POSITION_TOP; tab.paddingTop = tab.paddingRight = tab.paddingBottom = tab.paddingLeft = 28 * this.scale; tab.gap = 12 * this.scale; tab.minWidth = tab.minHeight = 88 * this.scale; tab.minTouchWidth = tab.minTouchHeight = 88 * this.scale; } protected function simpleScrollBarThumbInitializer(thumb:Button):void { const defaultSkin:Scale9Image = new Scale9Image(scrollBarThumbSkinTextures, this.scale); defaultSkin.width = 8 * this.scale; defaultSkin.height = 8 * this.scale; thumb.defaultSkin = defaultSkin; thumb.minTouchWidth = thumb.minTouchHeight = 12 * this.scale; } protected function buttonGroupInitializer(group:ButtonGroup):void { group.minWidth = 560 * this.scale; group.gap = 16 * this.scale; } protected function alertButtonGroupInitializer(group:ButtonGroup):void { group.direction = ButtonGroup.DIRECTION_VERTICAL; group.horizontalAlign = ButtonGroup.HORIZONTAL_ALIGN_JUSTIFY; group.verticalAlign = ButtonGroup.VERTICAL_ALIGN_JUSTIFY; group.gap = 14 * this.scale; group.paddingTop = 14 * this.scale; group.paddingRight = 14 * this.scale; group.paddingBottom = 14 * this.scale; group.paddingLeft = 14 * this.scale; } protected function sliderInitializer(slider:Slider):void { slider.trackLayoutMode = Slider.TRACK_LAYOUT_MODE_SINGLE; const sliderTrackDefaultSkin:Scale9Image = new Scale9Image(insetBackgroundSkinTextures, this.scale); if(slider.direction == Slider.DIRECTION_VERTICAL) { sliderTrackDefaultSkin.width = 66 * this.scale; sliderTrackDefaultSkin.height = 198 * this.scale; } else //horizontal { sliderTrackDefaultSkin.width = 198 * this.scale; sliderTrackDefaultSkin.height = 66 * this.scale; } slider.minimumTrackProperties.defaultSkin = sliderTrackDefaultSkin; } protected function sliderThumbInitializer(thumb:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.thumbSkinTextures; skinSelector.defaultSelectedValue = this.thumbDisabledSkinTextures; skinSelector.displayObjectProperties = { width: 66 * this.scale, height: 66 * this.scale, textureScale: this.scale }; thumb.stateToSkinFunction = skinSelector.updateValue; thumb.minTouchWidth = thumb.minTouchHeight = 88 * this.scale; } protected function numericStepperInitializer(stepper:NumericStepper):void { stepper.buttonLayoutMode = NumericStepper.BUTTON_LAYOUT_MODE_SPLIT_HORIZONTAL; stepper.incrementButtonLabel = ""+""; stepper.decrementButtonLabel = ""-""; } protected function toggleSwitchInitializer(toggleSwitch:ToggleSwitch):void { toggleSwitch.trackLayoutMode = ToggleSwitch.TRACK_LAYOUT_MODE_SINGLE; toggleSwitch.defaultLabelProperties.textFormat = this.primaryTextFormat; toggleSwitch.disabledLabelProperties.textFormat = this.disabledTextFormat; } protected function toggleSwitchOnTrackInitializer(track:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.insetBackgroundSkinTextures; skinSelector.defaultSelectedValue = this.insetBackgroundDisabledSkinTextures; skinSelector.displayObjectProperties = { width: 148 * this.scale, height: 66 * this.scale, textureScale: this.scale }; track.stateToSkinFunction = skinSelector.updateValue; track.minTouchWidth = track.minTouchHeight = 88 * this.scale; } protected function toggleSwitchThumbInitializer(thumb:Button):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.thumbSkinTextures; skinSelector.defaultSelectedValue = this.thumbDisabledSkinTextures; skinSelector.displayObjectProperties = { width: 66 * this.scale, height: 66 * this.scale, textureScale: this.scale }; thumb.stateToSkinFunction = skinSelector.updateValue; thumb.minTouchWidth = thumb.minTouchHeight = 88 * this.scale; } protected function checkInitializer(check:Check):void { const iconSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); iconSelector.defaultValue = this.checkIconTexture; iconSelector.defaultSelectedValue = this.checkSelectedIconTexture; iconSelector.setValueForState(this.checkDisabledIconTexture, Button.STATE_DISABLED, false); iconSelector.setValueForState(this.checkSelectedDisabledIconTexture, Button.STATE_DISABLED, true); iconSelector.displayObjectProperties = { scaleX: this.scale, scaleY: this.scale }; check.stateToIconFunction = iconSelector.updateValue; check.defaultLabelProperties.textFormat = this.primaryTextFormat; check.disabledLabelProperties.textFormat = this.disabledTextFormat; check.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat; check.gap = 12 * this.scale; check.minTouchWidth = check.minTouchHeight = 88 * this.scale; check.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT; check.verticalAlign = Button.VERTICAL_ALIGN_MIDDLE; } protected function radioInitializer(radio:Radio):void { const iconSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); iconSelector.defaultValue = this.radioIconTexture; iconSelector.defaultSelectedValue = this.radioSelectedIconTexture; iconSelector.setValueForState(this.radioDisabledIconTexture, Button.STATE_DISABLED, false); iconSelector.setValueForState(this.radioSelectedDisabledIconTexture, Button.STATE_DISABLED, true); iconSelector.displayObjectProperties = { scaleX: this.scale, scaleY: this.scale }; radio.stateToIconFunction = iconSelector.updateValue; radio.defaultLabelProperties.textFormat = this.primaryTextFormat; radio.disabledLabelProperties.textFormat = this.disabledTextFormat; radio.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat; radio.gap = 12 * this.scale; radio.minTouchWidth = radio.minTouchHeight = 88 * this.scale; radio.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT; radio.verticalAlign = Button.VERTICAL_ALIGN_MIDDLE; } protected function itemRendererInitializer(renderer:BaseDefaultItemRenderer):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.listItemUpTextures; skinSelector.defaultSelectedValue = this.listItemSelectedTextures; skinSelector.setValueForState(this.listItemDownTextures, Button.STATE_DOWN, false); skinSelector.displayObjectProperties = { width: 88 * this.scale, height: 88 * this.scale, textureScale: this.scale }; renderer.stateToSkinFunction = skinSelector.updateValue; renderer.defaultLabelProperties.textFormat = this.primaryTextFormat; renderer.disabledLabelProperties.textFormat = this.disabledTextFormat; renderer.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat; renderer.paddingTop = renderer.paddingBottom = 11 * this.scale; renderer.paddingLeft = renderer.paddingRight = 16 * this.scale; renderer.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT; renderer.minWidth = renderer.minHeight = 88 * this.scale; renderer.gap = 10 * this.scale; renderer.iconPosition = Button.ICON_POSITION_LEFT; renderer.accessoryGap = Number.POSITIVE_INFINITY; renderer.accessoryPosition = BaseDefaultItemRenderer.ACCESSORY_POSITION_RIGHT; renderer.accessoryLoaderFactory = this.imageLoaderFactory; renderer.iconLoaderFactory = this.imageLoaderFactory; } protected function pickerListItemRendererInitializer(renderer:BaseDefaultItemRenderer):void { const skinSelector:SmartDisplayObjectStateValueSelector = new SmartDisplayObjectStateValueSelector(); skinSelector.defaultValue = this.listItemUpTextures; skinSelector.setValueForState(this.listItemDownTextures, Button.STATE_DOWN, false); skinSelector.displayObjectProperties = { width: 88 * this.scale, height: 88 * this.scale, textureScale: this.scale }; renderer.stateToSkinFunction = skinSelector.updateValue; const defaultSelectedIcon:ImageLoader = new ImageLoader(); defaultSelectedIcon.source = this.pickerListItemSelectedIconTexture; defaultSelectedIcon.textureScale = this.scale; defaultSelectedIcon.snapToPixels = true; renderer.defaultSelectedIcon = defaultSelectedIcon; const defaultIcon:Quad = new Quad(defaultSelectedIcon.width, defaultSelectedIcon.height, 0xff00ff); defaultIcon.alpha = 0; renderer.defaultIcon = defaultIcon; renderer.defaultLabelProperties.textFormat = this.primaryTextFormat; renderer.disabledLabelProperties.textFormat = this.disabledTextFormat; renderer.selectedDisabledLabelProperties.textFormat = this.disabledTextFormat; renderer.paddingTop = renderer.paddingBottom = 11 * this.scale; renderer.paddingLeft = renderer.paddingRight = 16 * this.scale; renderer.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT; renderer.minWidth = renderer.minHeight = 88 * this.scale; renderer.iconPosition = Button.ICON_POSITION_RIGHT; renderer.gap = Number.POSITIVE_INFINITY; renderer.accessoryLoaderFactory = this.imageLoaderFactory; renderer.iconLoaderFactory = this.imageLoaderFactory; } protected function headerOrFooterRendererInitializer(renderer:DefaultGroupedListHeaderOrFooterRenderer):void { const backgroundSkin:Quad = new Quad(44 * this.scale, 44 * this.scale, LIST_HEADER_BACKGROUND_COLOR); renderer.backgroundSkin = backgroundSkin; renderer.contentLabelProperties.textFormat = this.primaryTextFormat; renderer.paddingTop = renderer.paddingBottom = 6 * this.scale; renderer.paddingLeft = renderer.paddingRight = 24 * this.scale; renderer.minWidth = renderer.minHeight = 44 * this.scale; renderer.contentLoaderFactory = this.imageLoaderFactory; } protected function insetHeaderOrFooterRendererInitializer(renderer:DefaultGroupedListHeaderOrFooterRenderer):void { renderer.contentLabelProperties.textFormat = this.primaryTextFormat; renderer.paddingTop = renderer.paddingBottom = 6 * this.scale; renderer.paddingLeft = renderer.paddingRight = 24 * this.scale; renderer.minWidth = renderer.minHeight = 66 * this.scale; renderer.contentLoaderFactory = this.imageLoaderFactory; } protected function listInitializer(list:List):void { const backgroundSkin:Quad = new Quad(88 * this.scale, 88 * this.scale, LIST_BACKGROUND_COLOR); list.backgroundSkin = backgroundSkin; } protected function groupedListInitializer(list:GroupedList):void { const backgroundSkin:Quad = new Quad(88 * this.scale, 88 * this.scale, LIST_BACKGROUND_COLOR); list.backgroundSkin = backgroundSkin; } protected function groupedListInsetInitializer(list:GroupedList):void { list.headerRendererName = GroupedList.ALTERNATE_CHILD_NAME_INSET_HEADER_RENDERER; list.footerRendererName = GroupedList.ALTERNATE_CHILD_NAME_INSET_FOOTER_RENDERER; const layout:VerticalLayout = new VerticalLayout(); layout.useVirtualLayout = true; layout.padding = 24 * this.scale; layout.paddingTop = 4 * this.scale; layout.gap = 0; layout.horizontalAlign = VerticalLayout.HORIZONTAL_ALIGN_JUSTIFY; layout.verticalAlign = VerticalLayout.VERTICAL_ALIGN_TOP; list.layout = layout; } protected function pickerListInitializer(list:PickerList):void { if(DeviceCapabilities.isTablet(Starling.current.nativeStage)) { list.popUpContentManager = new CalloutPopUpContentManager(); } else { const centerStage:VerticalCenteredPopUpContentManager = new VerticalCenteredPopUpContentManager(); centerStage.marginTop = centerStage.marginRight = centerStage.marginBottom = centerStage.marginLeft = 16 * this.scale; list.popUpContentManager = centerStage; } const layout:VerticalLayout = new VerticalLayout(); layout.verticalAlign = VerticalLayout.VERTICAL_ALIGN_BOTTOM; layout.horizontalAlign = VerticalLayout.HORIZONTAL_ALIGN_JUSTIFY; layout.useVirtualLayout = true; layout.gap = 0; layout.paddingTop = layout.paddingRight = layout.paddingBottom = layout.paddingLeft = 0; list.listProperties.layout = layout; list.listProperties.verticalScrollPolicy = List.SCROLL_POLICY_ON; if(DeviceCapabilities.isTablet(Starling.current.nativeStage)) { list.listProperties.minWidth = 560 * this.scale; list.listProperties.maxHeight = 528 * this.scale; } else { const backgroundSkin:Scale9Image = new Scale9Image(popUpBackgroundSkinTextures, this.scale); backgroundSkin.width = 20 * this.scale; backgroundSkin.height = 20 * this.scale; list.listProperties.backgroundSkin = backgroundSkin; list.listProperties.paddingTop = list.listProperties.paddingRight = list.listProperties.paddingBottom = list.listProperties.paddingLeft = 4 * this.scale; } list.listProperties.itemRendererName = COMPONENT_NAME_PICKER_LIST_ITEM_RENDERER; } protected function pickerListButtonInitializer(button:Button):void { //we're going to expand on the standard button styles this.buttonInitializer(button); const defaultIcon:Image = new Image(dropDownArrowTexture); defaultIcon.scaleX = defaultIcon.scaleY = this.scale; button.defaultIcon = defaultIcon; button.gap = Number.POSITIVE_INFINITY, //fill as completely as possible button.iconPosition = Button.ICON_POSITION_RIGHT; button.horizontalAlign = Button.HORIZONTAL_ALIGN_LEFT; } protected function headerInitializer(header:Header):void { header.minWidth = 88 * this.scale; header.minHeight = 88 * this.scale; header.paddingTop = header.paddingRight = header.paddingBottom = header.paddingLeft = 14 * this.scale; header.gap = 8 * this.scale; header.titleGap = 12 * this.scale; const backgroundSkin:Scale9Image = new Scale9Image(headerSkinTextures, this.scale); backgroundSkin.width = 88 * this.scale; backgroundSkin.height = 88 * this.scale; header.backgroundSkin = backgroundSkin; header.titleProperties.textFormat = this.primaryTextFormat; header.titleProperties.disabledTextFormat = this.disabledTextFormat; } protected function panelHeaderInitializer(header:Header):void { header.minWidth = 88 * this.scale; header.minHeight = 88 * this.scale; header.paddingTop = header.paddingBottom = 18 * this.scale; header.paddingLeft = header.paddingRight = 14 * this.scale; header.gap = 8 * this.scale; header.titleGap = 12 * this.scale; const backgroundSkin:Scale9Image = new Scale9Image(popUpBackgroundSkinTextures, this.scale); backgroundSkin.width = 88 * this.scale; backgroundSkin.height = 88 * this.scale; header.backgroundSkin = backgroundSkin; header.titleProperties.textFormat = this.primaryTextFormat; header.titleProperties.disabledTextFormat = this.disabledTextFormat; } protected function baseTextInputInitializer(input:TextInput):void { input.minWidth = input.minHeight = 66 * this.scale; input.minTouchWidth = input.minTouchHeight = 66 * this.scale; input.gap = 8 * this.scale; input.paddingTop = 14 * this.scale; input.paddingBottom = 8 * this.scale; input.paddingLeft = input.paddingRight = 16 * this.scale; input.textEditorProperties.fontFamily = ""_sans""; input.textEditorProperties.fontSize = this.inputFontSize; input.textEditorProperties.color = PRIMARY_TEXT_COLOR; const backgroundSkin:Scale9Image = new Scale9Image(insetBackgroundSkinTextures, this.scale); backgroundSkin.width = 264 * this.scale; backgroundSkin.height = 66 * this.scale; input.backgroundSkin = backgroundSkin; const backgroundDisabledSkin:Scale9Image = new Scale9Image(insetBackgroundDisabledSkinTextures, this.scale); backgroundDisabledSkin.width = 264 * this.scale; backgroundDisabledSkin.height = 66 * this.scale; input.backgroundDisabledSkin = backgroundDisabledSkin; input.promptProperties.textFormat = this.primaryTextFormat; input.promptProperties.disabledTextFormat = this.disabledTextFormat; } protected function textInputInitializer(input:TextInput):void { this.baseTextInputInitializer(input); } protected function searchTextInputInitializer(input:TextInput):void { this.baseTextInputInitializer(input); var searchIcon:ImageLoader = new ImageLoader(); searchIcon.source = this.searchIconTexture; searchIcon.snapToPixels = true; input.defaultIcon = searchIcon; } protected function numericStepperTextInputInitializer(input:TextInput):void { input.minWidth = input.minHeight = 66 * this.scale; input.minTouchWidth = input.minTouchHeight = 66 * this.scale; input.gap = 12 * this.scale; input.paddingTop = input.paddingBottom = 14 * this.scale; input.paddingLeft = input.paddingRight = 16 * this.scale; input.isEditable = false; input.textEditorProperties.fontFamily = ""_sans""; input.textEditorProperties.fontSize = this.inputFontSize; input.textEditorProperties.color = PRIMARY_TEXT_COLOR; input.textEditorProperties.textAlign = TextFormatAlign.CENTER; const backgroundSkin:Scale9Image = new Scale9Image(insetBackgroundSkinTextures, this.scale); backgroundSkin.width = 66 * this.scale; backgroundSkin.height = 66 * this.scale; input.backgroundSkin = backgroundSkin; const backgroundDisabledSkin:Scale9Image = new Scale9Image(insetBackgroundDisabledSkinTextures, this.scale); backgroundDisabledSkin.width = 66 * this.scale; backgroundDisabledSkin.height = 66 * this.scale; input.backgroundDisabledSkin = backgroundDisabledSkin; } protected function pageIndicatorInitializer(pageIndicator:PageIndicator):void { pageIndicator.normalSymbolFactory = this.pageIndicatorNormalSymbolFactory; pageIndicator.selectedSymbolFactory = this.pageIndicatorSelectedSymbolFactory; pageIndicator.gap = 12 * this.scale; pageIndicator.paddingTop = pageIndicator.paddingRight = pageIndicator.paddingBottom = pageIndicator.paddingLeft = 12 * this.scale; pageIndicator.minTouchWidth = pageIndicator.minTouchHeight = 44 * this.scale; } protected function progressBarInitializer(progress:ProgressBar):void { const backgroundSkin:Scale9Image = new Scale9Image(insetBackgroundSkinTextures, this.scale); backgroundSkin.width = (progress.direction == ProgressBar.DIRECTION_HORIZONTAL ? 264 : 22) * this.scale; backgroundSkin.height = (progress.direction == ProgressBar.DIRECTION_HORIZONTAL ? 22 : 264) * this.scale; progress.backgroundSkin = backgroundSkin; const backgroundDisabledSkin:Scale9Image = new Scale9Image(insetBackgroundDisabledSkinTextures, this.scale); backgroundDisabledSkin.width = (progress.direction == ProgressBar.DIRECTION_HORIZONTAL ? 264 : 22) * this.scale; backgroundDisabledSkin.height = (progress.direction == ProgressBar.DIRECTION_HORIZONTAL ? 22 : 264) * this.scale; progress.backgroundDisabledSkin = backgroundDisabledSkin; const fillSkin:Scale9Image = new Scale9Image(buttonUpSkinTextures, this.scale); fillSkin.width = 12 * this.scale; fillSkin.height = 12 * this.scale; progress.fillSkin = fillSkin; const fillDisabledSkin:Scale9Image = new Scale9Image(buttonDisabledSkinTextures, this.scale); fillDisabledSkin.width = 12 * this.scale; fillDisabledSkin.height = 12 * this.scale; progress.fillDisabledSkin = fillDisabledSkin; } protected function calloutInitializer(callout:Callout):void { callout.minWidth = 20 * this.scale; callout.minHeight = 20 * this.scale; callout.paddingTop = callout.paddingRight = callout.paddingBottom = callout.paddingLeft = 12 * this.scale; const backgroundSkin:Scale9Image = new Scale9Image(popUpBackgroundSkinTextures, this.scale); backgroundSkin.width = 20 * this.scale; backgroundSkin.height = 20 * this.scale; callout.backgroundSkin = backgroundSkin; const topArrowSkin:Image = new Image(calloutTopArrowSkinTexture); topArrowSkin.scaleX = topArrowSkin.scaleY = this.scale; callout.topArrowSkin = topArrowSkin; callout.topArrowGap = -8 * this.scale; const bottomArrowSkin:Image = new Image(calloutBottomArrowSkinTexture); bottomArrowSkin.scaleX = bottomArrowSkin.scaleY = this.scale; callout.bottomArrowSkin = bottomArrowSkin; callout.bottomArrowGap = -8 * this.scale; const leftArrowSkin:Image = new Image(calloutLeftArrowSkinTexture); leftArrowSkin.scaleX = leftArrowSkin.scaleY = this.scale; callout.leftArrowSkin = leftArrowSkin; callout.leftArrowGap = -8 * this.scale; const rightArrowSkin:Image = new Image(calloutRightArrowSkinTexture); rightArrowSkin.scaleX = rightArrowSkin.scaleY = this.scale; callout.rightArrowSkin = rightArrowSkin; callout.rightArrowGap = -8 * this.scale; } protected function panelInitializer(panel:Panel):void { const backgroundSkin:Scale9Image = new Scale9Image(popUpBackgroundSkinTextures, this.scale); backgroundSkin.width = 20 * this.scale; backgroundSkin.height = 20 * this.scale; panel.backgroundSkin = backgroundSkin; panel.paddingTop = panel.paddingRight = panel.paddingBottom = panel.paddingLeft = 14 * this.scale; } protected function alertInitializer(alert:Alert):void { const backgroundSkin:Scale9Image = new Scale9Image(this.popUpBackgroundSkinTextures, this.scale); backgroundSkin.width = 20 * this.scale; backgroundSkin.height = 20 * this.scale; alert.backgroundSkin = backgroundSkin; alert.paddingTop = alert.paddingBottom = 16 * this.scale; alert.paddingLeft = alert.paddingRight = 32 * this.scale; alert.maxWidth = alert.maxHeight = 560 * this.scale; } protected function scrollContainerToolbarInitializer(container:ScrollContainer):void { if(!container.layout) { const layout:HorizontalLayout = new HorizontalLayout(); layout.paddingTop = layout.paddingRight = layout.paddingBottom = layout.paddingLeft = 14 * this.scale; layout.gap = 8 * this.scale; container.layout = layout; } container.minWidth = 88 * this.scale; container.minHeight = 88 * this.scale; const backgroundSkin:Scale9Image = new Scale9Image(headerSkinTextures, this.scale); backgroundSkin.width = 88 * this.scale; backgroundSkin.height = 88 * this.scale; container.backgroundSkin = backgroundSkin; } protected function root_addedToStageHandler(event:Event):void { DisplayObject(event.currentTarget).stage.color = BACKGROUND_COLOR; } } }",12267,False,2495.3184102323976,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.core { import flash.display.DisplayObject; import flash.display.InteractiveObject; import flash.events.ContextMenuEvent; import flash.events.ErrorEvent; import flash.events.Event; import flash.external.ExternalInterface; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.system.Capabilities; import flash.ui.ContextMenu; import flash.ui.ContextMenuItem; import flash.utils.setInterval; import mx.containers.utilityClasses.ApplicationLayout; import mx.effects.EffectManager; import mx.events.FlexEvent; import mx.managers.FocusManager; import mx.managers.IActiveWindowManager; import mx.managers.ILayoutManager; import mx.managers.ISystemManager; import mx.styles.CSSStyleDeclaration; import mx.styles.IStyleClient; import mx.utils.LoaderUtil; import mx.utils.Platform; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched after the Application has been initialized, * processed by the LayoutManager, and attached to the display list. * * @eventType mx.events.FlexEvent.APPLICATION_COMPLETE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""applicationComplete"", type=""mx.events.FlexEvent"")] /** * Dispatched when an HTTPService call fails. * * @eventType flash.events.ErrorEvent.ERROR * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""error"", type=""flash.events.ErrorEvent"")] //-------------------------------------- // Styles //-------------------------------------- include ""../styles/metadata/ModalTransparencyStyles.as""; /** * Specifies the alpha transparency values used for the background gradient fill of the application. * You should set this to an Array of two numbers. * Elements 0 and 1 specify the start and end values for an alpha gradient. * * @default [ 1.0, 1.0 ] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""backgroundGradientAlphas"", type=""Array"", arrayType=""Number"", inherit=""no"", theme=""halo"")] /** * Specifies the colors used to tint the background gradient fill of the application. * You should set this to an Array of two uint values that specify RGB colors. * Elements 0 and 1 specify the start and end values for a color gradient. * For a solid-color background, set the same color value for elements 0 and 1. * A value of undefined means background gradient is generated * based on the backgroundColor property. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""backgroundGradientColors"", type=""Array"", arrayType=""uint"", format=""Color"", inherit=""no"", theme=""halo"")] /** * Number of pixels between the application's bottom border * and its content area. * * @default 24 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""paddingBottom"", type=""Number"", format=""Length"", inherit=""no"")] /** * Number of pixels between the application's top border * and its content area. * * @default 24 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""paddingTop"", type=""Number"", format=""Length"", inherit=""no"")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name=""direction"", kind=""property"")] [Exclude(name=""icon"", kind=""property"")] [Exclude(name=""label"", kind=""property"")] [Exclude(name=""tabIndex"", kind=""property"")] [Exclude(name=""toolTip"", kind=""property"")] [Exclude(name=""x"", kind=""property"")] [Exclude(name=""y"", kind=""property"")] //-------------------------------------- // Other metadata //-------------------------------------- /** * The frameworks must be initialized by SystemManager. * This factoryClass will be automatically subclassed by any * MXML applications that don't explicitly specify a different * factoryClass. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Frame(factoryClass=""mx.managers.SystemManager"")] [ResourceBundle(""core"")] [Alternative(replacement=""spark.components.Application"", since=""4.0"")] /** * Flex defines a default, or Application, container that lets you start * adding content to your application without explicitly defining * another container. * Flex creates this container from the <mx:Application> * tag, the first tag in an MXML application file. * While you might find it convenient to use the Application container * as the only container in your application, in most cases you explicitly * define at least one more container before you add any controls * to your application. * *

    Applications support a predefined plain style that sets * a white background, left alignment, and removes all margins. * To use this style, do the following:

    * *
     *    <mx:Application styleName=""plain"" />
     *  
    * *

    This is equivalent to setting the following style attributes:

    * *
     *    backgroundColor=""0xFFFFFF""
     *    horizontalAlign=""left""
     *    paddingLeft=""0""
     *    paddingTop=""0""
     *    paddingBottom=""0""
     *    paddingRight=""0""
     *  
    * * @mxml * *

    The <mx:Application> tag inherits all of the tag * attributes of its superclass and adds the following tag attributes:

    * *
     *  <mx:Application
     *    Properties
     *    application=""No default""
     *    controlBar=""null""
     *    frameRate=""24""
     *    historyManagementEnabled=""true|false""
     *    layout=""vertical|horizontal|absolute""
     *    pageTitle""No default""
     *    preloader=""No default""
     *    resetHistory=""false|true""
     *    scriptRecursionLimit=""1000""
     *    scriptTimeLimit=""60""
     *    usePreloader=""true|false""
     *    viewSourceURL=""""
     *    xmlns:No default=""No default""
     * 
     *    Styles 
     *    backgroundGradientAlphas=""[ 1.0, 1.0 ]""
     *    backgroundGradientColors=""undefined""
     *    horizontalAlign=""center|left|right""
     *    horizontalGap=""8""
     *    modalTransparency=""0.5""
     *    modalTransparencyBlur=""3""
     *    modalTransparencyColor=""#DDDDDD""
     *    modalTransparencyDuration=""100""
     *    paddingBottom=""24""
     *    paddingTop=""24""
     *    verticalAlign=""top|bottom|middle""
     *    verticalGap=""6""
     *  
     *    Events
     *    applicationComplete=""No default""
     *    error=""No default""
     *  />
     *  
    * * @includeExample examples/SimpleApplicationExample.mxml * * @see mx.managers.CursorManager * @see mx.managers.LayoutManager * @see mx.managers.SystemManager * @see flash.events.EventDispatcher * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class Application extends LayoutContainer { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- /** * @private */ mx_internal static var useProgressiveLayout:Boolean = false; //-------------------------------------------------------------------------- // // Class properties // //-------------------------------------------------------------------------- /** * A reference to the top-level application. * *

    In general, there can be a hierarchy of Application objects, * because an Application can use a SWFLoader control to dynamically * load another Application. * The parentApplication property of a UIComponent can be * used to access the sub-Application in which that UIComponent lives, * and to walk up the hierarchy to the top-level Application.

    * *

    This property has been deprecated starting in Flex4. Note that this * property will still return applications of type mx.core.Application and * mx.core.WindowedApplication as in previous versions. Starting in Flex 4 * it will also return applications of type spark.components.Application or * spark.components.WindowedApplication.

    * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ /* * Note: here are two reasons that 'application' is typed as Object * rather than as Application. The first is for consistency with * the 'parentApplication' property of UIComponent. That property is not * typed as Application because it would make UIComponent dependent * on Application, slowing down compile times not only for SWCs * for also for MXML and AS components. Second, if it were typed * as Application, authors would not be able to access properties * and methods in the ' + ' ' + ' RRX9856' + ' 42.50' + ' ' + ' Red' + ' Navy' + ' Burgundy' + ' ' + ' ' + ' Red' + ' Navy' + ' Burgundy' + ' Black' + ' ' + ' ' + ' Navy' + ' Black' + ' ' + ' ' + ' Burgundy' + ' Black' + ' ' + ' ' + ' ' + ''; quotedXML = ; xml = new XML(xmlStr); text = ""hi""; xml2 = new XML('hiyeah!'); } [AfterClass] public static function tearDownAfterClass():void { xmlStr = null; quotedXML = null; xml = null; text = null; xml2 = null; } [Test] public function testSimpleAttributes():void { var xml1:XML = ; assertTrue( xml1.hasOwnProperty(""@baz""), ' should have attribute @baz'); assertFalse( xml1.hasOwnProperty(""@foo""), ' should not have attribute @foo'); assertFalse( xml1.hasOwnProperty(""baz""), ' should not have attribute baz'); assertTrue( xml1.toXMLString() == '', ' toXMLString should be '); assertTrue( xml1.@baz.toString() == 'true', 'xml1.@baz.toString() should be ""true""'); var baz:XMLList = xml1.@baz; assertTrue( baz.toString() == 'true', 'baz.toString() should be ""true""'); assertEquals( baz.length(),1, 'baz.length() should be 1'); var xml3:XML = ; xml3.bar.baz = ""baz""; xml3.foo.@boo = ""boo""; assertEquals( xml3.bar.baz,'baz', 'xml3.bar.baz should be ""baz""'); assertEquals( xml3.foo.@boo,'boo', 'xml3.foo.@boo should be ""boo""'); } [Test] public function testSimpleXMLList():void { var xml1:XML = ; assertTrue( xml1.@baz.toString() == ""true"", 'toString value should be ""true"" '); var xml3:XML = ; xml3.bar.baz = ""baz""; xml3.foo.@boo = ""boo""; assertEquals( xml3.bar.baz.toString(), ""baz"", 'toString value should be ""baz"" '); assertEquals( xml3.foo.@boo.toString(), ""boo"", 'toString value should be ""boo"" '); var newContent:XML = ; newContent.Properties.Leading.@type = ""string""; newContent.Properties.Leading = 36; assertEquals( newContent.Properties.Leading.@type, ""string"", ""Leading should be @type=string""); assertStrictlyEquals(newContent.Properties.Leading.toString(), ""36"", ""Leading should be 36""); assertStrictlyEquals( newContent.toXMLString(), ""\\n"" + "" \\n"" + "" 36\\n"" + "" \\n"" + """", ""unexpected toXMLString() value"" ); newContent.Properties.Leading = 72; assertStrictlyEquals(newContent.Properties.Leading.toString(), ""72"", ""Leading should be 72""); } [Test] public function testMinimum():void{ var xml:XML = new XML(); assertEquals(xml.nodeKind(), 'text', 'unexpected default nodeKind'); assertEquals(xml.toString(), '', 'unexpected default stringification'); } [Test] public function testXMLMethods1():void { var xml1:XML = ; var child:XML = ; xml1.appendChild(child); child = ; xml1.appendChild(child); assertTrue( xml1.pop[0].child.@name.toString() == 'Sam', 'unexpected child result'); assertTrue( xml1.pop[1].child.@name.toString() == 'George', 'unexpected child result'); } [TestVariance(variance=""JS"", description=""toLocaleString has a substantially different output in javascript"")] [TestVariance(variance=""SWF"", description=""(observed) some of the XML methods for SWF had incorrect results before swf version 21"")] [Test] public function testXMLMethods2():void { var xml1:XML = ; var child:XML = ; xml1.appendChild(child); child = ; xml1.appendChild(child); assertEquals( xml1.pop[0].toString(), '\\n' + ' \\n' + '', 'unexpected output with xml1.pop[0].toString()'); assertEquals( xml1.pop[1].toString(), '\\n' + ' \\n' + '', 'unexpected output with xml1.pop[1].toString()'); var pop:XMLList = xml1.pop; pop[pop.length()] = ; assertEquals( pop.toString(), '\\n' + ' \\n' + '\\n' + '\\n' + ' \\n' + '\\n' + '\\n' + ' \\n' + '', 'unexpected output with pop.toString()'); assertEquals( xml1.toString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected output with xml1.toString()'); pop[0] = ; assertEquals( pop.toString(), '\\n' + ' \\n' + '\\n' + '\\n' + ' \\n' + '\\n' + '\\n' + ' \\n' + '', 'unexpected output with pop.toString()'); assertEquals( xml1.toString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected output with xml1.toString()'); //toLocaleString //VARIANCE var expected:String = isJS ? '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + '' //js : '[object XML]';// swf assertEquals( xml1.toLocaleString(), expected, 'unexpected output with xml1.toLocaleString()'); expected = isJS ? '\\n' + ' \\n' + '\\n' + '\\n' + ' \\n' + '\\n' + '\\n' + ' \\n' + '' //js : '[object XMLList]';//swf assertEquals( xml1.pop.toLocaleString(), expected, 'unexpected output with xml1.pop.toLocaleString()'); var parentXML:XML = ; var childXML:XML = ; parentXML.appendChild(childXML); assertTrue( (childXML.parent() == parentXML), 'child/parent relationship was unexpected'); assertEquals( parentXML.toXMLString(), '\\n' + ' \\n' + '', 'unexpected output following re-parenting'); var newParent:XML = ; newParent.appendChild(childXML); if (getSwfVersion() < 21) { //I think, a bug in old swf version, some 'remnant' of the old 'child' is still present in the'old' parent expected = '\\n' + ' \\n' + '' } else { expected = ''; } assertEquals( parentXML.toXMLString(), expected, 'unexpected output following re-parenting'); assertEquals( newParent.toXMLString(), '\\n' + ' \\n' + '', 'unexpected output following re-parenting'); assertFalse( (childXML.parent() == parentXML), 'child/parent relationship was unexpected'); var expectedLength:uint = getSwfVersion() < 21 ? 1 : 0; //another bug in old swf version, some 'remnant' of the old 'child' is still present in the'old' parent assertTrue( (parentXML.children().length() == expectedLength), 'child/parent relationship was unexpected'); assertTrue( (childXML.parent() == newParent), 'child/parent relationship was unexpected'); childXML = • Some amazing content; var childXMLStr:String = childXML.text(); assertEquals( childXMLStr, '•Some amazing content', "" (should be) •Some amazing content""); } [Test] public function testInvalidAppendChild():void{ var root:XML = new XML('test'); root.appendChild('test'); assertEquals(root.toString(), 'test', 'testInvalidAppendChild 1 result is bad'); assertEquals(root.toXMLString(), 'test', 'testInvalidAppendChild 2 result is bad'); } [Test] public function testAppendNonXMLChild():void{ var root:XML = ; root.appendChild('test'); assertEquals(root.toString(), 'test', 'testAppendNonXMLChild 1 result is bad'); assertEquals(root.toXMLString(), 'test', 'testAppendNonXMLChild 2 result is bad'); root = ; root.appendChild('test'); assertEquals( root.toString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' test\\n' + '', 'testAppendNonXMLChild 3 result is bad'); assertEquals( root.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' test\\n' + '', 'testAppendNonXMLChild 4 result is bad'); } [Test] public function testXMLNormalize():void{ var xml:XML = ; xml.appendChild(""test1""); xml.appendChild(""test2""); xml.appendChild(); xml.appendChild(""test3""); xml.appendChild(""test4""); assertEquals( xml.toString(), '\\n' + ' test1\\n' + ' test2\\n' + ' \\n' + ' test3\\n' + ' test4\\n' + '', 'testXMLNormalize 1 result is bad'); assertEquals( xml.toXMLString(), '\\n' + ' test1\\n' + ' test2\\n' + ' \\n' + ' test3\\n' + ' test4\\n' + '', 'testXMLNormalize 2 result is bad'); xml.normalize(); assertEquals( xml.toString(), '\\n' + ' test1test2\\n' + ' \\n' + ' test3\\n' + ' test4\\n' + '', 'testXMLNormalize 3 result is bad'); assertEquals( xml.toXMLString(), '\\n' + ' test1test2\\n' + ' \\n' + ' test3\\n' + ' test4\\n' + '', 'testXMLNormalize 4 result is bad'); } [Test] public function testSVG():void { var svg:XML = ; var rects:XMLList = svg..rect; rects[1].@width = ""100px""; rects.(@id == 3).@height = ""100px""; var expected:String = '' + '\\n' + '' + '\\n' + '' + '\\n' + ''; assertTrue( rects.toXMLString() == expected, 'string output was unexpected'); } [Test] public function testChildList():void{ var xml:XML = asdasdas asdasqdasd; var list:XMLList = xml.*; assertEquals( 4, list.length(), 'Error in list length'); assertEquals( list.toXMLString(), 'asdasdas\\n' + '\\n' +'asdasqdasd\\n' +'', 'Error in list length'); list = xml.element; assertEquals( 1, list.length(), 'Error in list length'); assertEquals( list.toXMLString(),'', 'Error in list length'); list = xml.otherElement; assertEquals( 1, list.length(), 'Error in list length'); assertEquals( list.toXMLString(),'', 'Error in list length'); list = xml.otherElement; assertEquals( 1, list.length(), 'Error in list length'); } [Test] [TestVariance(variance=""JS"",description=""Some browsers (IE11/Edge legacy) can parse to a different order of attributes and namespace declarations (which affects stringified content comparisons)"")] public function testChildVariants():void{ var xml:XML = asdasdas asdasqdasd; var list:XMLList = xml.*::*; assertEquals( 4, list.length(), 'Error in list length'); //IE11/Edge issues /*assertEquals( list.toXMLString(), '\\n' + '\\n' + '\\n' + '', 'Error in list content');*/ assertEquals( list.toXMLString().length, 212, 'Error in list content'); list = xml.otherElement; assertEquals( 1, list.length(), 'Error in list length'); //IE11/Edge issues /* assertEquals( list.toXMLString(),'', 'Error in list content');*/ assertEquals( list.toXMLString().length,51, 'Error in list content'); list = xml.*; assertEquals( 6, list.length(), 'Error in list length'); /* assertEquals( list.toXMLString(),'asdasdas\\n' + '\\n' + 'asdasqdasd\\n' + '\\n' + '\\n' + '', 'Error in list content');*/ assertEquals( list.toXMLString().length,232, 'Error in list content'); } [Test] public function testNamespaceRetrieval():void{ var content:XML = ; var namespace:Namespace = content.children()[0].namespace(); assertEquals( namespace.prefix, 'x', 'Error in namespace prefix'); assertEquals( namespace.uri, 'adobe:ns:meta/', 'Error in namespace uri'); } [Test] [TestVariance(variance=""JS"",description=""Javascript does not support duplicate namespace declarations (Error thrown)"")] public function testNamespaceRetrieval2():void{ var caughtError:Boolean; try { var content:XML = ; } catch(e:Error) { caughtError = true; } if (isJS) { caughtError = !caughtError; } assertFalse( caughtError, 'Unexpected Error state with duplicate namespace declarations'); } [Test] public function testDuplicateAttributesError():void{ var caughtError:Boolean; try { var content:XML = ; } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'Unexpected Error state with duplicate attribute declarations'); } [Test] public function testParsingWhitespaceSetting1():void{ var originalSetting:Boolean = XML.ignoreWhitespace; XML.ignoreWhitespace = true; var script:XML = ; assertEquals(1, script.children().length(), 'unexpected children number after parsing'); assertEquals( '', script.toXMLString(), 'unexpected toString value after parsing'); XML.ignoreWhitespace = false; script = ; assertEquals(3, script.children().length(), 'unexpected children number after parsing'); assertEquals( '', script.toXMLString(), 'unexpected toString value after parsing'); XML.ignoreWhitespace = originalSetting; } [Test] public function testSingleProcessingInstructions():void{ var original:Boolean = XML.ignoreProcessingInstructions; XML.ignoreProcessingInstructions = true; var xml:XML = new XML(''); assertEquals( 'text', xml.nodeKind(), 'unexpected nodeKind with XML.ignoreProcessingInstructions = true'); assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreProcessingInstructions = true'); XML.ignoreProcessingInstructions = false; xml = new XML(''); assertEquals( 'processing-instruction', xml.nodeKind(), 'unexpected nodeKind with XML.ignoreProcessingInstructions = false'); assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreProcessingInstructions = false'); XML.ignoreProcessingInstructions = original; } [Test] public function testSingleCDATA():void{ var original:Boolean = XML.ignoreWhitespace; XML.ignoreWhitespace = true; var xml:XML = new XML(' '); assertEquals( 'text', xml.nodeKind(), 'unexpected cdata result with XML.ignoreWhitespace = true'); assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreWhitespace = true'); assertNull( xml.name(), 'unexpected name value with CDATA'); XML.ignoreWhitespace = false; var caughtError:Boolean = false; try { xml = new XML(' '); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error status for single cdata string parsing with XML.ignoreWhitespace = false'); XML.ignoreWhitespace = original; } [Test] public function testSingleText():void{ var original:Boolean = XML.ignoreWhitespace; XML.ignoreWhitespace = true; var xml:XML = new XML(' my text '); assertEquals( 'text', xml.nodeKind(), 'unexpected text result with XML.ignoreWhitespace = true'); assertEquals( 'my text', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreWhitespace = true'); assertNull( xml.name(), 'unexpected name value with text'); XML.ignoreWhitespace = false; var caughtError:Boolean = false; try { xml = new XML(' my text '); } catch(e:Error) { caughtError = true; } assertFalse( caughtError, 'unexpected error status for text string parsing with XML.ignoreWhitespace = false'); assertEquals( 'text', xml.nodeKind(), 'unexpected text result with XML.ignoreWhitespace = true'); assertEquals( ' my text ', xml.valueOf(), 'unexpected toXMLString with XML.ignoreWhitespace = true'); XML.ignoreWhitespace = original; } [Test] public function testSingleComment():void{ var original:Boolean = XML.ignoreWhitespace; var originalComments:Boolean = XML.ignoreComments; XML.ignoreWhitespace = true; XML.ignoreComments = false; var xml:XML = new XML(' '); assertEquals( 'comment', xml.nodeKind(), 'unexpected comment result with XML.ignoreWhitespace = true'); assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreWhitespace = true'); assertNull( xml.name(), 'unexpected name value with text'); XML.ignoreWhitespace = false; var caughtError:Boolean = false; try { xml = new XML(' '); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error status for comment parsing with XML.ignoreWhitespace = false'); xml = new XML(''); assertNull( xml.name(), 'unexpected name value with comment'); assertEquals( 'comment', xml.nodeKind(), 'unexpected comment result with XML.ignoreWhitespace = true'); assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreWhitespace = true'); XML.ignoreComments = true; xml = new XML(''); assertNull( xml.name(), 'unexpected name value with text'); assertEquals( 'text', xml.nodeKind(), 'unexpected comment result with XML.ignoreComments = true'); assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreComments = true'); XML.ignoreWhitespace = original; XML.ignoreComments = originalComments; } [Test] public function testIgnoreComments():void{ var original:Boolean = XML.ignoreWhitespace; var originalComments:Boolean = XML.ignoreComments; XML.ignoreWhitespace = true; XML.ignoreComments = false; var xml:XML = new XML(''); assertEquals( 1, xml.children().length(), 'unexpected comment result with XML.ignoreComments = false'); assertEquals( '\\n' + ' \\n' + '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreComments = false'); assertNull( xml.children()[0].name(), 'unexpected name value with comment'); XML.ignoreComments = true; xml = new XML(''); assertEquals( 0, xml.children().length(), 'unexpected comment result with XML.ignoreComments = true'); assertEquals( '', xml.toXMLString(), 'unexpected toXMLString with XML.ignoreComments = true'); XML.ignoreWhitespace = original; XML.ignoreComments = originalComments; } [Test] [TestVariance(variance=""JS"",description=""Some browsers (IE11/Edge legacy) can parse to a different order of attributes and namespace declarations (which affects stringified content comparisons)"")] public function testLargeComplex():void{ var xmlString:String = xml.toXMLString(); //IE and MS Edge: inlcude alternate output check //account for variation in output order of attributes and namespace declarations (from native DOMParser) assertTrue( xmlString.length == 2060, 'unexpected complex stringify results'); } [Test] public function testTopLevelProcessingInstructions():void{ var xmlSource:String = '\\n' + '\\n' + ''; XML.ignoreProcessingInstructions = true; var xml:XML = new XML(xmlSource); assertTrue( xml.toString() == '', 'unexpected toSting result'); assertTrue( xml.nodeKind() == 'text', 'unexpected nodeKind result'); XML.ignoreProcessingInstructions = false; var caughtError:Boolean; try { xml = new XML(xmlSource); } catch (e:Error) { //RoyaleUnitTestRunner.consoleOut(e.message); caughtError = true; } //RoyaleUnitTestRunner.consoleOut('testTopLevelProcessingInstructions '+xml.nodeKind()); assertTrue( caughtError, 'error was expected'); } [Test] public function testTopLevelWhitespace():void{ var original:Boolean = XML.ignoreWhitespace; var xmlSource:String = '\\n' +' test '; XML.ignoreWhitespace = true; var xml:XML = new XML(xmlSource); assertTrue( xml.toString() == 'test', 'unexpected toSting result'); assertTrue( xml.nodeKind() == 'element', 'unexpected nodeKind result'); XML.ignoreWhitespace = false; xml = new XML(xmlSource); assertTrue( xml.toString() == 'test', 'unexpected toSting result'); assertTrue( xml.nodeKind() == 'element', 'unexpected nodeKind result'); XML.ignoreWhitespace = original; } [Test] public function testTopLevelMultipleTypes():void{ var original:Object = XML.settings(); var xmlSource:String = '\\n' +' test '; XML.ignoreComments = false; XML.ignoreProcessingInstructions = false; XML.ignoreWhitespace = false; var xml:XML = new XML(xmlSource); assertTrue( xml.toString() == 'test', 'unexpected toSting result'); assertTrue( xml.nodeKind() == 'element', 'unexpected nodeKind result'); xmlSource = '\\n' +' '; var caughtError:Boolean = false; try { xml =new XML(xmlSource); } catch (e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error status'); assertTrue( xml.toString() == 'test', 'unexpected toSting result'); assertTrue( xml.nodeKind() == 'element', 'unexpected nodeKind result'); XML.setSettings(original) } [Test] public function testTopLevelVariants():void{ var original:Object = XML.settings(); //error 2 root tags var xmlSource:String = ' test test '; XML.ignoreComments = false; XML.ignoreProcessingInstructions = false; XML.ignoreWhitespace = false; var xml:XML; var caughtError:Boolean = false; try { xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error statust'); //repeat with all settings toggled (must remain an error) XML.ignoreComments = true; XML.ignoreProcessingInstructions = true; XML.ignoreWhitespace = true; try { caughtError = false; xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error statust'); //restore settings XML.ignoreComments = false; XML.ignoreProcessingInstructions = false; XML.ignoreWhitespace = false; //error multiple non-element nodes with whitespace xmlSource = ' '; try { caughtError = false; xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error status'); //repeat with whiteSpace toggled (must remain an error) XML.ignoreWhitespace = true; try { caughtError = false; xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error status'); XML.ignoreWhitespace = false; //repeat with ignoreProcessingInstructions toggled XML.ignoreProcessingInstructions = true; try { caughtError = false; xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error status'); XML.ignoreProcessingInstructions = false; //repeat with ignoreComments toggled XML.ignoreComments = true; try { caughtError = false; xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error status'); XML.ignoreComments = false; //repeat with all settings toggled XML.ignoreComments = true; XML.ignoreProcessingInstructions = true; XML.ignoreWhitespace = true; try { caughtError = false; xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertFalse( caughtError, 'unexpected error status'); assertTrue( xml.toString() == '', 'unexpected toSting result'); XML.ignoreComments = false; XML.ignoreProcessingInstructions = false; XML.ignoreWhitespace = false; //another one with top level cdata just to cover more: xmlSource = ' - ]]> '; try { caughtError = false; xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertTrue( caughtError, 'unexpected error status'); //repeat with all settings toggled XML.ignoreComments = true; XML.ignoreProcessingInstructions = true; XML.ignoreWhitespace = true; try { caughtError = false; xml = new XML(xmlSource); } catch(e:Error) { caughtError = true; } assertFalse( caughtError, 'unexpected error status'); assertTrue( xml.toString() == ' -- ', 'unexpected toSting result'); assertTrue( xml.toXMLString() == '- ]]>', 'unexpected toXMLString result'); XML.ignoreComments = false; XML.ignoreProcessingInstructions = false; XML.ignoreWhitespace = false; XML.setSettings(original) } [Test] public function testTopLevelCoercionFunction():void{ var localXml:XML; localXml = XML(true); assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected'); assertTrue( localXml.toString() == 'true', 'XML content was unexpected'); localXml = XML(false); assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected'); assertTrue( localXml.toString() == 'false', 'XML content was unexpected'); localXml = XML('string'); assertTrue( localXml.nodeKind() == 'text', 'XMLList content was unexpected'); assertTrue( localXml.toString() == 'string', 'XMLList content was unexpected'); localXml = XML(99.9); assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected'); assertTrue( localXml.toString() == '99.9', 'XML content was unexpected'); //as3 docs say this is an error, but it is not (in AVM) localXml = XML(null); assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected'); assertTrue( localXml.toString() == '', 'XML content was unexpected'); //as3 docs say this is an error, but it is not (in AVM) localXml = XML(undefined); assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected'); assertTrue( localXml.toString() == '', 'XML content was unexpected'); //as3 docs say this is an error, but it is not (in AVM) localXml = XML({}); assertTrue( localXml.nodeKind() == 'text', 'XML content was unexpected'); assertTrue( localXml.toString() == '[object Object]', 'XML content was unexpected'); var xmlContent:XML = xml; localXml = XML(xmlContent); assertTrue( localXml == xml, 'XML content was unexpected'); var sizes:XMLList = localXml..size.(@description == 'Small'); assertTrue( sizes.length() == 1, 'XML content was unexpected'); localXml = XML(sizes); assertTrue( localXml == sizes[0], 'XML content was unexpected'); } [Test] public function testChildren():void{ XML.setSettings(XML.defaultSettings()); var xml:XML = Something surrounded With Whitespace ; assertEquals(xml.children().length(),3 , 'unexpected default parsing children length'); assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' Something\\n' + ' surrounded With Whitespace\\n' + '' , 'unexpected default parsing string output'); XML.ignoreComments = false; xml = Something surrounded With Whitespace ; assertEquals(xml.children().length(),4 , 'unexpected parsing with ignoreComments = false children length'); assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' Something\\n' + ' \\n' + ' surrounded With Whitespace\\n' + '' , 'unexpected parsing with ignoreComments = false string output'); XML.ignoreProcessingInstructions= false; xml = Something surrounded With Whitespace ; assertEquals(xml.children().length(),5 , 'unexpected parsing with ignoreComments = false and ignoreProcessingInstructions= false children length'); assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' Something\\n' + ' \\n' + ' surrounded With Whitespace\\n' + '' , 'unexpected parsing with ignoreComments = false and ignoreProcessingInstructions= false string output'); XML.ignoreWhitespace= false; xml = Something surrounded With Whitespace ; assertEquals(xml.children().length(),6 , 'unexpected parsing with ignoreComments = false and ignoreProcessingInstructions= false and ignoreWhitespace= false children length'); assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' Something\\n' + ' \\n' + ' surrounded With Whitespace\\n' + '' , 'unexpected parsing with ignoreComments = false and ignoreProcessingInstructions= false and ignoreWhitespace= false string output'); //try something different XML.ignoreComments = true; xml = Something surrounded With Whitespace ; //because ignoreComments is true, the following is parsed as an empty test node: xml.appendChild(); assertEquals(xml.children().length(),6 , 'unexpected parsing with ignoreComments = true and ignoreProcessingInstructions= false and ignoreWhitespace= false and appending comment... children length'); assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' Something\\n' + ' surrounded With Whitespace\\n' + ' \\n' + '' , 'unexpected parsing with ignoreComments = true and ignoreProcessingInstructions= false and ignoreWhitespace= false and appending comment... string output'); XML.ignoreComments = false; var comment:XML = ; comment = comment.comments()[0]; assertEquals(comment.toXMLString(),'', 'unexpected toXMLString for comment'); XML.ignoreComments = true; xml = Something surrounded With Whitespace ; //because ignoreComments is true, the following is parsed as an empty test node: xml.appendChild(comment); assertEquals(xml.children().length(),6 , 'unexpected parsing with ignoreComments = true and ignoreProcessingInstructions= false and ignoreWhitespace= false and appending comment... children length'); assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' Something\\n' + ' surrounded With Whitespace\\n' + ' \\n' + '' , 'unexpected parsing with ignoreComments = true and ignoreProcessingInstructions= false and ignoreWhitespace= false and appending comment... string output'); XML.setSettings(XML.defaultSettings()); } [Test] public function testElements():void{ XML.setSettings(XML.defaultSettings()); var xml:XML = Something surrounded With Whitespace ; var elements:XMLList = xml.elements(); assertEquals( elements.toString(), '\\n' + '\\n' + '', 'elements only should be 3 elements'); elements = xml.elements('el1') assertEquals( elements.toXMLString(), '', 'elements query should return 1 element'); var el:XML = ; xml.appendChild(el) elements = xml.elements('el1') assertEquals( elements.toXMLString(), '\\n', 'elements query should return 2 elements'); } [Test] public function testDelete():void{ XML.setSettings(XML.defaultSettings()); XML.prettyPrinting = false; var xml:XML = ; delete xml.@name; assertEquals(xml.toString(),'',""name attribute should have been removed.""); delete xml.baz[0]; assertEquals(xml.toString(),'',""the first baz element should have been removed.""); xml = ; delete xml.baz; // delete xml.baz[0]; assertEquals(xml.toXMLString(),'',""the first baz element should have been removed.""); XML.setSettings(XML.defaultSettings()); } [Test] public function testDynamicAttributes():void{ var xml:XML = ; assertEquals(xml.attributes().length(),2, 'unexpected attributes count'); const MYAtt:String = 'myAtt1'; const MYAttTestVal:String = 'myAttTestVal'; delete xml.@[MYAtt]; assertEquals(xml.attributes().length(),1, 'unexpected attributes count'); xml.@[MYAtt] = MYAttTestVal; assertEquals(xml.attributes().length(),2, 'unexpected attributes count'); assertEquals(xml.@myAtt1,'myAttTestVal', 'unexpected attributes value'); } [Test] public function testAppendChildContentTransfer():void{ var source:XML = ; var sourceChildren:XMLList = source.children(); var attList:XMLList = source.@att; var att:XML = attList[0]; var orig1:XML = sourceChildren[0]; var dest:XML = ; assertTrue(orig1.parent() === source, 'unexpected parent'); assertTrue(att.parent() === source, 'unexpected parent'); dest.appendChild(sourceChildren); //element was re-parented: assertFalse(orig1.parent() === source, 'unexpected parent'); //attribute was not moved: assertTrue(att.parent() === source, 'unexpected parent'); assertTrue(orig1.parent() === dest, 'unexpected parent'); //at this point the actual nodes are present in both xml trees when iterating downwards, //but the 'parent()' evaluation only resolves to the latest parent //this is the swf behavior, but may not conform to standard assertEquals(source.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected source toXMLString') assertEquals(dest.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected dest toXMLString') dest.appendChild(attList); //swf has a strange variation here: var appendedAtt1:String = isJS ? ' attribute\\n' : ' attribute\\n' assertEquals(dest.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + appendedAtt1 + '', 'unexpected dest toXMLString'); dest.appendChild(att); assertEquals(dest.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + appendedAtt1 + ' attribute\\n' + '', 'unexpected dest toXMLString'); dest.appendChild(orig1); //the source remains unchanged assertEquals(source.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected source toXMLString'); //this is effectively a re-ordering inside dest var expected1:String = '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + appendedAtt1 + ' attribute\\n' + ' \\n' + '' var expected2:String = '\\n' + ' \\n' + //this seems to be the case in standalone debug player ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + appendedAtt1 + ' attribute\\n' + ' \\n' + '' var actual:String = dest.toXMLString(); assertTrue(actual==expected1 || actual==expected2 , 'unexpected dest toXMLString'); } [Test] public function testAssignXMLListVariants():void{ var xmlList:XMLList = new XMLList(); var xml:XML = ; xml.foobaz = xmlList; assertEquals(xml.toXMLString(), '\\n' + ' \\n' + '', 'unexpected empty XMLList assignment'); xmlList = new XMLList(''); xml.foobaz = xmlList; assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected XMLList assignment'); xml = ; xml.foobaz = xmlList; assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected XMLList assignment'); xml = ; xml.foobaz = xmlList; assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected XMLList assignment'); xml =; xml.foobaz = xmlList; assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected XMLList assignment'); xmlList = new XMLList(); xml.foobazzer = xmlList; assertEquals(xml.toXMLString(), '\\n' + ' \\n' + ' \\n' + ' \\n' + '', 'unexpected XMLList assignment') } //@todo - Passes in Swf, fails in browser: /*[Test] public function checkNumericAttributeSupported():void{ var xml:XML = XML(''); assertEquals(xml.toXMLString(), '', 'roundtripping with numeric attributes did not work'); }*/ } } ",12447,False,2394.0679500143065,median "[role=""xpack""] [testenv=""basic""] [[ml-find-file-structure]] === Find file structure API ++++ Find file structure ++++ experimental[] Finds the structure of a text file. The text file must contain data that is suitable to be ingested into {es}. [[ml-find-file-structure-request]] ==== {api-request-title} `POST _ml/find_file_structure` [[ml-find-file-structure-prereqs]] ==== {api-prereq-title} * If the {es} {security-features} are enabled, you must have `monitor_ml` or `monitor` cluster privileges to use this API. See {stack-ov}/security-privileges.html[Security privileges]. [[ml-find-file-structure-desc]] ==== {api-description-title} This API provides a starting point for ingesting data into {es} in a format that is suitable for subsequent use with other {ml} functionality. Unlike other {es} endpoints, the data that is posted to this endpoint does not need to be UTF-8 encoded and in JSON format. It must, however, be text; binary file formats are not currently supported. The response from the API contains: * A couple of messages from the beginning of the file. * Statistics that reveal the most common values for all fields detected within the file and basic numeric statistics for numeric fields. * Information about the structure of the file, which is useful when you write ingest configurations to index the file contents. * Appropriate mappings for an {es} index, which you could use to ingest the file contents. All this information can be calculated by the structure finder with no guidance. However, you can optionally override some of the decisions about the file structure by specifying one or more query parameters. Details of the output can be seen in the <>. If the structure finder produces unexpected results for a particular file, specify the `explain` query parameter. It causes an `explanation` to appear in the response, which should help in determining why the returned structure was chosen. [[ml-find-file-structure-query-parms]] ==== {api-query-parms-title} `charset` (Optional):: (string) The file's character set. It must be a character set that is supported by the JVM that {es} uses. For example, `UTF-8`, `UTF-16LE`, `windows-1252`, or `EUC-JP`. If this parameter is not specified, the structure finder chooses an appropriate character set. `column_names` (Optional):: (string) If you have set `format` to `delimited`, you can specify the column names in a comma-separated list. If this parameter is not specified, the structure finder uses the column names from the header row of the file. If the file does not have a header role, columns are named ""column1"", ""column2"", ""column3"", etc. `delimiter` (Optional):: (string) If you have set `format` to `delimited`, you can specify the character used to delimit the values in each row. Only a single character is supported; the delimiter cannot have multiple characters. If this parameter is not specified, the structure finder considers the following possibilities: comma, tab, semi-colon, and pipe (`|`). `explain` (Optional):: (boolean) If this parameter is set to `true`, the response includes a field named `explanation`, which is an array of strings that indicate how the structure finder produced its result. The default value is `false`. `format` (Optional):: (string) The high level structure of the file. Valid values are `ndjson`, `xml`, `delimited`, and `semi_structured_text`. If this parameter is not specified, the structure finder chooses one. `grok_pattern` (Optional):: (string) If you have set `format` to `semi_structured_text`, you can specify a Grok pattern that is used to extract fields from every message in the file. The name of the timestamp field in the Grok pattern must match what is specified in the `timestamp_field` parameter. If that parameter is not specified, the name of the timestamp field in the Grok pattern must match ""timestamp"". If `grok_pattern` is not specified, the structure finder creates a Grok pattern. `has_header_row` (Optional):: (boolean) If you have set `format` to `delimited`, you can use this parameter to indicate whether the column names are in the first row of the file. If this parameter is not specified, the structure finder guesses based on the similarity of the first row of the file to other rows. `line_merge_size_limit` (Optional):: (unsigned integer) The maximum number of characters in a message when lines are merged to form messages while analyzing semi-structured files. The default is 10000. If you have extremely long messages you may need to increase this, but be aware that this may lead to very long processing times if the way to group lines into messages is misdetected. `lines_to_sample` (Optional):: (unsigned integer) The number of lines to include in the structural analysis, starting from the beginning of the file. The minimum is 2; the default is 1000. If the value of this parameter is greater than the number of lines in the file, the analysis proceeds (as long as there are at least two lines in the file) for all of the lines. + + -- NOTE: The number of lines and the variation of the lines affects the speed of the analysis. For example, if you upload a log file where the first 1000 lines are all variations on the same message, the analysis will find more commonality than would be seen with a bigger sample. If possible, however, it is more efficient to upload a sample file with more variety in the first 1000 lines than to request analysis of 100000 lines to achieve some variety. -- `quote` (Optional):: (string) If you have set `format` to `delimited`, you can specify the character used to quote the values in each row if they contain newlines or the delimiter character. Only a single character is supported. If this parameter is not specified, the default value is a double quote (`""`). If your delimited file format does not use quoting, a workaround is to set this argument to a character that does not appear anywhere in the sample. `should_trim_fields` (Optional):: (boolean) If you have set `format` to `delimited`, you can specify whether values between delimiters should have whitespace trimmed from them. If this parameter is not specified and the delimiter is pipe (`|`), the default value is `true`. Otherwise, the default value is `false`. `timeout` (Optional):: (time) Sets the maximum amount of time that the structure analysis make take. If the analysis is still running when the timeout expires then it will be aborted. The default value is 25 seconds. `timestamp_field` (Optional):: (string) The name of the field that contains the primary timestamp of each record in the file. In particular, if the file were ingested into an index, this is the field that would be used to populate the `@timestamp` field. + + -- If the `format` is `semi_structured_text`, this field must match the name of the appropriate extraction in the `grok_pattern`. Therefore, for semi-structured file formats, it is best not to specify this parameter unless `grok_pattern` is also specified. For structured file formats, if you specify this parameter, the field must exist within the file. If this parameter is not specified, the structure finder makes a decision about which field (if any) is the primary timestamp field. For structured file formats, it is not compulsory to have a timestamp in the file. -- `timestamp_format` (Optional):: (string) The Java time format of the timestamp field in the file. + + -- NOTE: Only a subset of Java time format letter groups are supported: * `a` * `d` * `dd` * `EEE` * `EEEE` * `H` * `HH` * `h` * `M` * `MM` * `MMM` * `MMMM` * `mm` * `ss` * `XX` * `XXX` * `yy` * `yyyy` * `zzz` Additionally `S` letter groups (fractional seconds) of length one to nine are supported providing they occur after `ss` and separated from the `ss` by a `.`, `,` or `:`. Spacing and punctuation is also permitted with the exception of `?`, newline and carriage return, together with literal text enclosed in single quotes. For example, `MM/dd HH.mm.ss,SSSSSS 'in' yyyy` is a valid override format. One valuable use case for this parameter is when the format is semi-structured text, there are multiple timestamp formats in the file, and you know which format corresponds to the primary timestamp, but you do not want to specify the full `grok_pattern`. Another is when the timestamp format is one that the structure finder does not consider by default. If this parameter is not specified, the structure finder chooses the best format from a built-in set. -- [[ml-find-file-structure-request-body]] ==== {api-request-body-title} The text file that you want to analyze. It must contain data that is suitable to be ingested into {es}. It does not need to be in JSON format and it does not need to be UTF-8 encoded. The size is limited to the {es} HTTP receive buffer size, which defaults to 100 Mb. [[ml-find-file-structure-examples]] ==== {api-examples-title} Suppose you have a newline-delimited JSON file that contains information about some books. You can send the contents to the `find_file_structure` endpoint: [source,js] ---- POST _ml/find_file_structure {""name"": ""Leviathan Wakes"", ""author"": ""James S.A. Corey"", ""release_date"": ""2011-06-02"", ""page_count"": 561} {""name"": ""Hyperion"", ""author"": ""Dan Simmons"", ""release_date"": ""1989-05-26"", ""page_count"": 482} {""name"": ""Dune"", ""author"": ""Frank Herbert"", ""release_date"": ""1965-06-01"", ""page_count"": 604} {""name"": ""Dune Messiah"", ""author"": ""Frank Herbert"", ""release_date"": ""1969-10-15"", ""page_count"": 331} {""name"": ""Children of Dune"", ""author"": ""Frank Herbert"", ""release_date"": ""1976-04-21"", ""page_count"": 408} {""name"": ""God Emperor of Dune"", ""author"": ""Frank Herbert"", ""release_date"": ""1981-05-28"", ""page_count"": 454} {""name"": ""Consider Phlebas"", ""author"": ""Iain M. Banks"", ""release_date"": ""1987-04-23"", ""page_count"": 471} {""name"": ""Pandora's Star"", ""author"": ""Peter F. Hamilton"", ""release_date"": ""2004-03-02"", ""page_count"": 768} {""name"": ""Revelation Space"", ""author"": ""Alastair Reynolds"", ""release_date"": ""2000-03-15"", ""page_count"": 585} {""name"": ""A Fire Upon the Deep"", ""author"": ""Vernor Vinge"", ""release_date"": ""1992-06-01"", ""page_count"": 613} {""name"": ""Ender's Game"", ""author"": ""Orson Scott Card"", ""release_date"": ""1985-06-01"", ""page_count"": 324} {""name"": ""1984"", ""author"": ""George Orwell"", ""release_date"": ""1985-06-01"", ""page_count"": 328} {""name"": ""Fahrenheit 451"", ""author"": ""Ray Bradbury"", ""release_date"": ""1953-10-15"", ""page_count"": 227} {""name"": ""Brave New World"", ""author"": ""Aldous Huxley"", ""release_date"": ""1932-06-01"", ""page_count"": 268} {""name"": ""Foundation"", ""author"": ""Isaac Asimov"", ""release_date"": ""1951-06-01"", ""page_count"": 224} {""name"": ""The Giver"", ""author"": ""Lois Lowry"", ""release_date"": ""1993-04-26"", ""page_count"": 208} {""name"": ""Slaughterhouse-Five"", ""author"": ""Kurt Vonnegut"", ""release_date"": ""1969-06-01"", ""page_count"": 275} {""name"": ""The Hitchhiker's Guide to the Galaxy"", ""author"": ""Douglas Adams"", ""release_date"": ""1979-10-12"", ""page_count"": 180} {""name"": ""Snow Crash"", ""author"": ""Neal Stephenson"", ""release_date"": ""1992-06-01"", ""page_count"": 470} {""name"": ""Neuromancer"", ""author"": ""William Gibson"", ""release_date"": ""1984-07-01"", ""page_count"": 271} {""name"": ""The Handmaid's Tale"", ""author"": ""Margaret Atwood"", ""release_date"": ""1985-06-01"", ""page_count"": 311} {""name"": ""Starship Troopers"", ""author"": ""Robert A. Heinlein"", ""release_date"": ""1959-12-01"", ""page_count"": 335} {""name"": ""The Left Hand of Darkness"", ""author"": ""Ursula K. Le Guin"", ""release_date"": ""1969-06-01"", ""page_count"": 304} {""name"": ""The Moon is a Harsh Mistress"", ""author"": ""Robert A. Heinlein"", ""release_date"": ""1966-04-01"", ""page_count"": 288} ---- // CONSOLE // TEST If the request does not encounter errors, you receive the following result: [source,js] ---- { ""num_lines_analyzed"" : 24, <1> ""num_messages_analyzed"" : 24, <2> ""sample_start"" : ""{\\""name\\"": \\""Leviathan Wakes\\"", \\""author\\"": \\""James S.A. Corey\\"", \\""release_date\\"": \\""2011-06-02\\"", \\""page_count\\"": 561}\\n{\\""name\\"": \\""Hyperion\\"", \\""author\\"": \\""Dan Simmons\\"", \\""release_date\\"": \\""1989-05-26\\"", \\""page_count\\"": 482}\\n"", <3> ""charset"" : ""UTF-8"", <4> ""has_byte_order_marker"" : false, <5> ""format"" : ""ndjson"", <6> ""timestamp_field"" : ""release_date"", <7> ""joda_timestamp_formats"" : [ <8> ""ISO8601"" ], ""java_timestamp_formats"" : [ <9> ""ISO8601"" ], ""need_client_timezone"" : true, <10> ""mappings"" : { <11> ""@timestamp"" : { ""type"" : ""date"" }, ""author"" : { ""type"" : ""keyword"" }, ""name"" : { ""type"" : ""keyword"" }, ""page_count"" : { ""type"" : ""long"" }, ""release_date"" : { ""type"" : ""date"", ""format"" : ""iso8601"" } }, ""ingest_pipeline"" : { ""description"" : ""Ingest pipeline created by file structure finder"", ""processors"" : [ { ""date"" : { ""field"" : ""release_date"", ""timezone"" : ""{{ beat.timezone }}"", ""formats"" : [ ""ISO8601"" ] } } ] }, ""field_stats"" : { <12> ""author"" : { ""count"" : 24, ""cardinality"" : 20, ""top_hits"" : [ { ""value"" : ""Frank Herbert"", ""count"" : 4 }, { ""value"" : ""Robert A. Heinlein"", ""count"" : 2 }, { ""value"" : ""Alastair Reynolds"", ""count"" : 1 }, { ""value"" : ""Aldous Huxley"", ""count"" : 1 }, { ""value"" : ""Dan Simmons"", ""count"" : 1 }, { ""value"" : ""Douglas Adams"", ""count"" : 1 }, { ""value"" : ""George Orwell"", ""count"" : 1 }, { ""value"" : ""Iain M. Banks"", ""count"" : 1 }, { ""value"" : ""Isaac Asimov"", ""count"" : 1 }, { ""value"" : ""James S.A. Corey"", ""count"" : 1 } ] }, ""name"" : { ""count"" : 24, ""cardinality"" : 24, ""top_hits"" : [ { ""value"" : ""1984"", ""count"" : 1 }, { ""value"" : ""A Fire Upon the Deep"", ""count"" : 1 }, { ""value"" : ""Brave New World"", ""count"" : 1 }, { ""value"" : ""Children of Dune"", ""count"" : 1 }, { ""value"" : ""Consider Phlebas"", ""count"" : 1 }, { ""value"" : ""Dune"", ""count"" : 1 }, { ""value"" : ""Dune Messiah"", ""count"" : 1 }, { ""value"" : ""Ender's Game"", ""count"" : 1 }, { ""value"" : ""Fahrenheit 451"", ""count"" : 1 }, { ""value"" : ""Foundation"", ""count"" : 1 } ] }, ""page_count"" : { ""count"" : 24, ""cardinality"" : 24, ""min_value"" : 180, ""max_value"" : 768, ""mean_value"" : 387.0833333333333, ""median_value"" : 329.5, ""top_hits"" : [ { ""value"" : 180, ""count"" : 1 }, { ""value"" : 208, ""count"" : 1 }, { ""value"" : 224, ""count"" : 1 }, { ""value"" : 227, ""count"" : 1 }, { ""value"" : 268, ""count"" : 1 }, { ""value"" : 271, ""count"" : 1 }, { ""value"" : 275, ""count"" : 1 }, { ""value"" : 288, ""count"" : 1 }, { ""value"" : 304, ""count"" : 1 }, { ""value"" : 311, ""count"" : 1 } ] }, ""release_date"" : { ""count"" : 24, ""cardinality"" : 20, ""earliest"" : ""1932-06-01"", ""latest"" : ""2011-06-02"", ""top_hits"" : [ { ""value"" : ""1985-06-01"", ""count"" : 3 }, { ""value"" : ""1969-06-01"", ""count"" : 2 }, { ""value"" : ""1992-06-01"", ""count"" : 2 }, { ""value"" : ""1932-06-01"", ""count"" : 1 }, { ""value"" : ""1951-06-01"", ""count"" : 1 }, { ""value"" : ""1953-10-15"", ""count"" : 1 }, { ""value"" : ""1959-12-01"", ""count"" : 1 }, { ""value"" : ""1965-06-01"", ""count"" : 1 }, { ""value"" : ""1966-04-01"", ""count"" : 1 }, { ""value"" : ""1969-10-15"", ""count"" : 1 } ] } } } ---- // TESTRESPONSE[s/""sample_start"" : "".*"",/""sample_start"" : ""$body.sample_start"",/] // The substitution is because the ""file"" is pre-processed by the test harness, // so the fields may get reordered in the JSON the endpoint sees <1> `num_lines_analyzed` indicates how many lines of the file were analyzed. <2> `num_messages_analyzed` indicates how many distinct messages the lines contained. For NDJSON, this value is the same as `num_lines_analyzed`. For other file formats, messages can span several lines. <3> `sample_start` reproduces the first two messages in the file verbatim. This may help to diagnose parse errors or accidental uploads of the wrong file. <4> `charset` indicates the character encoding used to parse the file. <5> For UTF character encodings, `has_byte_order_marker` indicates whether the file begins with a byte order marker. <6> `format` is one of `ndjson`, `xml`, `delimited` or `semi_structured_text`. <7> The `timestamp_field` names the field considered most likely to be the primary timestamp of each document. <8> `joda_timestamp_formats` are used to tell Logstash how to parse timestamps. <9> `java_timestamp_formats` are the Java time formats recognized in the time fields. Elasticsearch mappings and Ingest pipeline use this format. <10> If a timestamp format is detected that does not include a timezone, `need_client_timezone` will be `true`. The server that parses the file must therefore be told the correct timezone by the client. <11> `mappings` contains some suitable mappings for an index into which the data could be ingested. In this case, the `release_date` field has been given a `keyword` type as it is not considered specific enough to convert to the `date` type. <12> `field_stats` contains the most common values of each field, plus basic numeric statistics for the numeric `page_count` field. This information may provide clues that the data needs to be cleaned or transformed prior to use by other {ml} functionality. The next example shows how it's possible to find the structure of some New York City yellow cab trip data. The first `curl` command downloads the data, the first 20000 lines of which are then piped into the `find_file_structure` endpoint. The `lines_to_sample` query parameter of the endpoint is set to 20000 to match what is specified in the `head` command. [source,js] ---- curl -s ""s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2018-06.csv"" | head -20000 | curl -s -H ""Content-Type: application/json"" -XPOST ""localhost:9200/_ml/find_file_structure?pretty&lines_to_sample=20000"" -T - ---- // NOTCONSOLE // Not converting to console because this shows how curl can be used -- NOTE: The `Content-Type: application/json` header must be set even though in this case the data is not JSON. (Alternatively the `Content-Type` can be set to any other supported by Elasticsearch, but it must be set.) -- If the request does not encounter errors, you receive the following result: [source,js] ---- { ""num_lines_analyzed"" : 20000, ""num_messages_analyzed"" : 19998, <1> ""sample_start"" : ""VendorID,tpep_pickup_datetime,tpep_dropoff_datetime,passenger_count,trip_distance,RatecodeID,store_and_fwd_flag,PULocationID,DOLocationID,payment_type,fare_amount,extra,mta_tax,tip_amount,tolls_amount,improvement_surcharge,total_amount\\n\\n1,2018-06-01 00:15:40,2018-06-01 00:16:46,1,.00,1,N,145,145,2,3,0.5,0.5,0,0,0.3,4.3\\n"", ""charset"" : ""UTF-8"", ""has_byte_order_marker"" : false, ""format"" : ""delimited"", <2> ""multiline_start_pattern"" : ""^.*?,\\""?\\\\d{4}-\\\\d{2}-\\\\d{2}[T ]\\\\d{2}:\\\\d{2}"", ""exclude_lines_pattern"" : ""^\\""?VendorID\\""?,\\""?tpep_pickup_datetime\\""?,\\""?tpep_dropoff_datetime\\""?,\\""?passenger_count\\""?,\\""?trip_distance\\""?,\\""?RatecodeID\\""?,\\""?store_and_fwd_flag\\""?,\\""?PULocationID\\""?,\\""?DOLocationID\\""?,\\""?payment_type\\""?,\\""?fare_amount\\""?,\\""?extra\\""?,\\""?mta_tax\\""?,\\""?tip_amount\\""?,\\""?tolls_amount\\""?,\\""?improvement_surcharge\\""?,\\""?total_amount\\""?"", ""column_names"" : [ <3> ""VendorID"", ""tpep_pickup_datetime"", ""tpep_dropoff_datetime"", ""passenger_count"", ""trip_distance"", ""RatecodeID"", ""store_and_fwd_flag"", ""PULocationID"", ""DOLocationID"", ""payment_type"", ""fare_amount"", ""extra"", ""mta_tax"", ""tip_amount"", ""tolls_amount"", ""improvement_surcharge"", ""total_amount"" ], ""has_header_row"" : true, <4> ""delimiter"" : "","", <5> ""quote"" : ""\\"""", <6> ""timestamp_field"" : ""tpep_pickup_datetime"", <7> ""joda_timestamp_formats"" : [ <8> ""YYYY-MM-dd HH:mm:ss"" ], ""java_timestamp_formats"" : [ <9> ""yyyy-MM-dd HH:mm:ss"" ], ""need_client_timezone"" : true, <10> ""mappings"" : { ""@timestamp"" : { ""type"" : ""date"" }, ""DOLocationID"" : { ""type"" : ""long"" }, ""PULocationID"" : { ""type"" : ""long"" }, ""RatecodeID"" : { ""type"" : ""long"" }, ""VendorID"" : { ""type"" : ""long"" }, ""extra"" : { ""type"" : ""double"" }, ""fare_amount"" : { ""type"" : ""double"" }, ""improvement_surcharge"" : { ""type"" : ""double"" }, ""mta_tax"" : { ""type"" : ""double"" }, ""passenger_count"" : { ""type"" : ""long"" }, ""payment_type"" : { ""type"" : ""long"" }, ""store_and_fwd_flag"" : { ""type"" : ""keyword"" }, ""tip_amount"" : { ""type"" : ""double"" }, ""tolls_amount"" : { ""type"" : ""double"" }, ""total_amount"" : { ""type"" : ""double"" }, ""tpep_dropoff_datetime"" : { ""type"" : ""date"", ""format"" : ""yyyy-MM-dd HH:mm:ss"" }, ""tpep_pickup_datetime"" : { ""type"" : ""date"", ""format"" : ""yyyy-MM-dd HH:mm:ss"" }, ""trip_distance"" : { ""type"" : ""double"" } }, ""ingest_pipeline"" : { ""description"" : ""Ingest pipeline created by file structure finder"", ""processors"" : [ { ""date"" : { ""field"" : ""tpep_pickup_datetime"", ""timezone"" : ""{{ beat.timezone }}"", ""formats"" : [ ""yyyy-MM-dd HH:mm:ss"" ] } } ] }, ""field_stats"" : { ""DOLocationID"" : { ""count"" : 19998, ""cardinality"" : 240, ""min_value"" : 1, ""max_value"" : 265, ""mean_value"" : 150.26532653265312, ""median_value"" : 148, ""top_hits"" : [ { ""value"" : 79, ""count"" : 760 }, { ""value"" : 48, ""count"" : 683 }, { ""value"" : 68, ""count"" : 529 }, { ""value"" : 170, ""count"" : 506 }, { ""value"" : 107, ""count"" : 468 }, { ""value"" : 249, ""count"" : 457 }, { ""value"" : 230, ""count"" : 441 }, { ""value"" : 186, ""count"" : 432 }, { ""value"" : 141, ""count"" : 409 }, { ""value"" : 263, ""count"" : 386 } ] }, ""PULocationID"" : { ""count"" : 19998, ""cardinality"" : 154, ""min_value"" : 1, ""max_value"" : 265, ""mean_value"" : 153.4042404240424, ""median_value"" : 148, ""top_hits"" : [ { ""value"" : 79, ""count"" : 1067 }, { ""value"" : 230, ""count"" : 949 }, { ""value"" : 148, ""count"" : 940 }, { ""value"" : 132, ""count"" : 897 }, { ""value"" : 48, ""count"" : 853 }, { ""value"" : 161, ""count"" : 820 }, { ""value"" : 234, ""count"" : 750 }, { ""value"" : 249, ""count"" : 722 }, { ""value"" : 164, ""count"" : 663 }, { ""value"" : 114, ""count"" : 646 } ] }, ""RatecodeID"" : { ""count"" : 19998, ""cardinality"" : 5, ""min_value"" : 1, ""max_value"" : 5, ""mean_value"" : 1.0656565656565653, ""median_value"" : 1, ""top_hits"" : [ { ""value"" : 1, ""count"" : 19311 }, { ""value"" : 2, ""count"" : 468 }, { ""value"" : 5, ""count"" : 195 }, { ""value"" : 4, ""count"" : 17 }, { ""value"" : 3, ""count"" : 7 } ] }, ""VendorID"" : { ""count"" : 19998, ""cardinality"" : 2, ""min_value"" : 1, ""max_value"" : 2, ""mean_value"" : 1.59005900590059, ""median_value"" : 2, ""top_hits"" : [ { ""value"" : 2, ""count"" : 11800 }, { ""value"" : 1, ""count"" : 8198 } ] }, ""extra"" : { ""count"" : 19998, ""cardinality"" : 3, ""min_value"" : -0.5, ""max_value"" : 0.5, ""mean_value"" : 0.4815981598159816, ""median_value"" : 0.5, ""top_hits"" : [ { ""value"" : 0.5, ""count"" : 19281 }, { ""value"" : 0, ""count"" : 698 }, { ""value"" : -0.5, ""count"" : 19 } ] }, ""fare_amount"" : { ""count"" : 19998, ""cardinality"" : 208, ""min_value"" : -100, ""max_value"" : 300, ""mean_value"" : 13.937719771977209, ""median_value"" : 9.5, ""top_hits"" : [ { ""value"" : 6, ""count"" : 1004 }, { ""value"" : 6.5, ""count"" : 935 }, { ""value"" : 5.5, ""count"" : 909 }, { ""value"" : 7, ""count"" : 903 }, { ""value"" : 5, ""count"" : 889 }, { ""value"" : 7.5, ""count"" : 854 }, { ""value"" : 4.5, ""count"" : 802 }, { ""value"" : 8.5, ""count"" : 790 }, { ""value"" : 8, ""count"" : 789 }, { ""value"" : 9, ""count"" : 711 } ] }, ""improvement_surcharge"" : { ""count"" : 19998, ""cardinality"" : 3, ""min_value"" : -0.3, ""max_value"" : 0.3, ""mean_value"" : 0.29915991599159913, ""median_value"" : 0.3, ""top_hits"" : [ { ""value"" : 0.3, ""count"" : 19964 }, { ""value"" : -0.3, ""count"" : 22 }, { ""value"" : 0, ""count"" : 12 } ] }, ""mta_tax"" : { ""count"" : 19998, ""cardinality"" : 3, ""min_value"" : -0.5, ""max_value"" : 0.5, ""mean_value"" : 0.4962246224622462, ""median_value"" : 0.5, ""top_hits"" : [ { ""value"" : 0.5, ""count"" : 19868 }, { ""value"" : 0, ""count"" : 109 }, { ""value"" : -0.5, ""count"" : 21 } ] }, ""passenger_count"" : { ""count"" : 19998, ""cardinality"" : 7, ""min_value"" : 0, ""max_value"" : 6, ""mean_value"" : 1.6201620162016201, ""median_value"" : 1, ""top_hits"" : [ { ""value"" : 1, ""count"" : 14219 }, { ""value"" : 2, ""count"" : 2886 }, { ""value"" : 5, ""count"" : 1047 }, { ""value"" : 3, ""count"" : 804 }, { ""value"" : 6, ""count"" : 523 }, { ""value"" : 4, ""count"" : 406 }, { ""value"" : 0, ""count"" : 113 } ] }, ""payment_type"" : { ""count"" : 19998, ""cardinality"" : 4, ""min_value"" : 1, ""max_value"" : 4, ""mean_value"" : 1.315631563156316, ""median_value"" : 1, ""top_hits"" : [ { ""value"" : 1, ""count"" : 13936 }, { ""value"" : 2, ""count"" : 5857 }, { ""value"" : 3, ""count"" : 160 }, { ""value"" : 4, ""count"" : 45 } ] }, ""store_and_fwd_flag"" : { ""count"" : 19998, ""cardinality"" : 2, ""top_hits"" : [ { ""value"" : ""N"", ""count"" : 19910 }, { ""value"" : ""Y"", ""count"" : 88 } ] }, ""tip_amount"" : { ""count"" : 19998, ""cardinality"" : 717, ""min_value"" : 0, ""max_value"" : 128, ""mean_value"" : 2.010959095909593, ""median_value"" : 1.45, ""top_hits"" : [ { ""value"" : 0, ""count"" : 6917 }, { ""value"" : 1, ""count"" : 1178 }, { ""value"" : 2, ""count"" : 624 }, { ""value"" : 3, ""count"" : 248 }, { ""value"" : 1.56, ""count"" : 206 }, { ""value"" : 1.46, ""count"" : 205 }, { ""value"" : 1.76, ""count"" : 196 }, { ""value"" : 1.45, ""count"" : 195 }, { ""value"" : 1.36, ""count"" : 191 }, { ""value"" : 1.5, ""count"" : 187 } ] }, ""tolls_amount"" : { ""count"" : 19998, ""cardinality"" : 26, ""min_value"" : 0, ""max_value"" : 35, ""mean_value"" : 0.2729697969796978, ""median_value"" : 0, ""top_hits"" : [ { ""value"" : 0, ""count"" : 19107 }, { ""value"" : 5.76, ""count"" : 791 }, { ""value"" : 10.5, ""count"" : 36 }, { ""value"" : 2.64, ""count"" : 21 }, { ""value"" : 11.52, ""count"" : 8 }, { ""value"" : 5.54, ""count"" : 4 }, { ""value"" : 8.5, ""count"" : 4 }, { ""value"" : 17.28, ""count"" : 4 }, { ""value"" : 2, ""count"" : 2 }, { ""value"" : 2.16, ""count"" : 2 } ] }, ""total_amount"" : { ""count"" : 19998, ""cardinality"" : 1267, ""min_value"" : -100.3, ""max_value"" : 389.12, ""mean_value"" : 17.499898989898995, ""median_value"" : 12.35, ""top_hits"" : [ { ""value"" : 7.3, ""count"" : 478 }, { ""value"" : 8.3, ""count"" : 443 }, { ""value"" : 8.8, ""count"" : 420 }, { ""value"" : 6.8, ""count"" : 406 }, { ""value"" : 7.8, ""count"" : 405 }, { ""value"" : 6.3, ""count"" : 371 }, { ""value"" : 9.8, ""count"" : 368 }, { ""value"" : 5.8, ""count"" : 362 }, { ""value"" : 9.3, ""count"" : 332 }, { ""value"" : 10.3, ""count"" : 332 } ] }, ""tpep_dropoff_datetime"" : { ""count"" : 19998, ""cardinality"" : 9066, ""earliest"" : ""2018-05-31 06:18:15"", ""latest"" : ""2018-06-02 02:25:44"", ""top_hits"" : [ { ""value"" : ""2018-06-01 01:12:12"", ""count"" : 10 }, { ""value"" : ""2018-06-01 00:32:15"", ""count"" : 9 }, { ""value"" : ""2018-06-01 00:44:27"", ""count"" : 9 }, { ""value"" : ""2018-06-01 00:46:42"", ""count"" : 9 }, { ""value"" : ""2018-06-01 01:03:22"", ""count"" : 9 }, { ""value"" : ""2018-06-01 01:05:13"", ""count"" : 9 }, { ""value"" : ""2018-06-01 00:11:20"", ""count"" : 8 }, { ""value"" : ""2018-06-01 00:16:03"", ""count"" : 8 }, { ""value"" : ""2018-06-01 00:19:47"", ""count"" : 8 }, { ""value"" : ""2018-06-01 00:25:17"", ""count"" : 8 } ] }, ""tpep_pickup_datetime"" : { ""count"" : 19998, ""cardinality"" : 8760, ""earliest"" : ""2018-05-31 06:08:31"", ""latest"" : ""2018-06-02 01:21:21"", ""top_hits"" : [ { ""value"" : ""2018-06-01 00:01:23"", ""count"" : 12 }, { ""value"" : ""2018-06-01 00:04:31"", ""count"" : 10 }, { ""value"" : ""2018-06-01 00:05:38"", ""count"" : 10 }, { ""value"" : ""2018-06-01 00:09:50"", ""count"" : 10 }, { ""value"" : ""2018-06-01 00:12:01"", ""count"" : 10 }, { ""value"" : ""2018-06-01 00:14:17"", ""count"" : 10 }, { ""value"" : ""2018-06-01 00:00:34"", ""count"" : 9 }, { ""value"" : ""2018-06-01 00:00:40"", ""count"" : 9 }, { ""value"" : ""2018-06-01 00:02:53"", ""count"" : 9 }, { ""value"" : ""2018-06-01 00:05:40"", ""count"" : 9 } ] }, ""trip_distance"" : { ""count"" : 19998, ""cardinality"" : 1687, ""min_value"" : 0, ""max_value"" : 64.63, ""mean_value"" : 3.6521062106210715, ""median_value"" : 2.16, ""top_hits"" : [ { ""value"" : 0.9, ""count"" : 335 }, { ""value"" : 0.8, ""count"" : 320 }, { ""value"" : 1.1, ""count"" : 316 }, { ""value"" : 0.7, ""count"" : 304 }, { ""value"" : 1.2, ""count"" : 303 }, { ""value"" : 1, ""count"" : 296 }, { ""value"" : 1.3, ""count"" : 280 }, { ""value"" : 1.5, ""count"" : 268 }, { ""value"" : 1.6, ""count"" : 268 }, { ""value"" : 0.6, ""count"" : 256 } ] } } } ---- // NOTCONSOLE <1> `num_messages_analyzed` is 2 lower than `num_lines_analyzed` because only data records count as messages. The first line contains the column names and in this sample the second line is blank. <2> Unlike the first example, in this case the `format` has been identified as `delimited`. <3> Because the `format` is `delimited`, the `column_names` field in the output lists the column names in the order they appear in the sample. <4> `has_header_row` indicates that for this sample the column names were in the first row of the sample. (If they hadn't been then it would have been a good idea to specify them in the `column_names` query parameter.) <5> The `delimiter` for this sample is a comma, as it's a CSV file. <6> The `quote` character is the default double quote. (The structure finder does not attempt to deduce any other quote character, so if you have a delimited file that's quoted with some other character you must specify it using the `quote` query parameter.) <7> The `timestamp_field` has been chosen to be `tpep_pickup_datetime`. `tpep_dropoff_datetime` would work just as well, but `tpep_pickup_datetime` was chosen because it comes first in the column order. If you prefer `tpep_dropoff_datetime` then force it to be chosen using the `timestamp_field` query parameter. <8> `joda_timestamp_formats` are used to tell Logstash how to parse timestamps. <9> `java_timestamp_formats` are the Java time formats recognized in the time fields. Elasticsearch mappings and Ingest pipeline use this format. <10> The timestamp format in this sample doesn't specify a timezone, so to accurately convert them to UTC timestamps to store in Elasticsearch it's necessary to supply the timezone they relate to. `need_client_timezone` will be `false` for timestamp formats that include the timezone. If you try to analyze a lot of data then the analysis will take a long time. If you want to limit the amount of processing your {es} cluster performs for a request, use the `timeout` query parameter. The analysis will be aborted and an error returned when the timeout expires. For example, you can replace 20000 lines in the previous example with 200000 and set a 1 second timeout on the analysis: [source,js] ---- curl -s ""s3.amazonaws.com/nyc-tlc/trip+data/yellow_tripdata_2018-06.csv"" | head -200000 | curl -s -H ""Content-Type: application/json"" -XPOST ""localhost:9200/_ml/find_file_structure?pretty&lines_to_sample=200000&timeout=1s"" -T - ---- // NOTCONSOLE // Not converting to console because this shows how curl can be used Unless you are using an incredibly fast computer you'll receive a timeout error: [source,js] ---- { ""error"" : { ""root_cause"" : [ { ""type"" : ""timeout_exception"", ""reason"" : ""Aborting structure analysis during [delimited record parsing] as it has taken longer than the timeout of [1s]"" } ], ""type"" : ""timeout_exception"", ""reason"" : ""Aborting structure analysis during [delimited record parsing] as it has taken longer than the timeout of [1s]"" }, ""status"" : 500 } ---- // NOTCONSOLE -- NOTE: If you try the example above yourself you will note that the overall running time of the `curl` commands is considerably longer than 1 second. This is because it takes a while to download 200000 lines of CSV from the internet, and the timeout is measured from the time this endpoint starts to process the data. -- This is an example of analyzing {es}'s own log file: [source,js] ---- curl -s -H ""Content-Type: application/json"" -XPOST ""localhost:9200/_ml/find_file_structure?pretty"" -T ""$ES_HOME/logs/elasticsearch.log"" ---- // NOTCONSOLE // Not converting to console because this shows how curl can be used If the request does not encounter errors, the result will look something like this: [source,js] ---- { ""num_lines_analyzed"" : 53, ""num_messages_analyzed"" : 53, ""sample_start"" : ""[2018-09-27T14:39:28,518][INFO ][o.e.e.NodeEnvironment ] [node-0] using [1] data paths, mounts [[/ (/dev/disk1)]], net usable_space [165.4gb], net total_space [464.7gb], types [hfs]\\n[2018-09-27T14:39:28,521][INFO ][o.e.e.NodeEnvironment ] [node-0] heap size [494.9mb], compressed ordinary object pointers [true]\\n"", ""charset"" : ""UTF-8"", ""has_byte_order_marker"" : false, ""format"" : ""semi_structured_text"", <1> ""multiline_start_pattern"" : ""^\\\\[\\\\b\\\\d{4}-\\\\d{2}-\\\\d{2}[T ]\\\\d{2}:\\\\d{2}"", <2> ""grok_pattern"" : ""\\\\[%{TIMESTAMP_ISO8601:timestamp}\\\\]\\\\[%{LOGLEVEL:loglevel}.*"", <3> ""timestamp_field"" : ""timestamp"", ""joda_timestamp_formats"" : [ ""ISO8601"" ], ""java_timestamp_formats"" : [ ""ISO8601"" ], ""need_client_timezone"" : true, ""mappings"" : { ""@timestamp"" : { ""type"" : ""date"" }, ""loglevel"" : { ""type"" : ""keyword"" }, ""message"" : { ""type"" : ""text"" } }, ""ingest_pipeline"" : { ""description"" : ""Ingest pipeline created by file structure finder"", ""processors"" : [ { ""grok"" : { ""field"" : ""message"", ""patterns"" : [ ""\\\\[%{TIMESTAMP_ISO8601:timestamp}\\\\]\\\\[%{LOGLEVEL:loglevel}.*"" ] } }, { ""date"" : { ""field"" : ""timestamp"", ""timezone"" : ""{{ beat.timezone }}"", ""formats"" : [ ""ISO8601"" ] } }, { ""remove"" : { ""field"" : ""timestamp"" } } ] }, ""field_stats"" : { ""loglevel"" : { ""count"" : 53, ""cardinality"" : 3, ""top_hits"" : [ { ""value"" : ""INFO"", ""count"" : 51 }, { ""value"" : ""DEBUG"", ""count"" : 1 }, { ""value"" : ""WARN"", ""count"" : 1 } ] }, ""timestamp"" : { ""count"" : 53, ""cardinality"" : 28, ""earliest"" : ""2018-09-27T14:39:28,518"", ""latest"" : ""2018-09-27T14:39:37,012"", ""top_hits"" : [ { ""value"" : ""2018-09-27T14:39:29,859"", ""count"" : 10 }, { ""value"" : ""2018-09-27T14:39:29,860"", ""count"" : 9 }, { ""value"" : ""2018-09-27T14:39:29,858"", ""count"" : 6 }, { ""value"" : ""2018-09-27T14:39:28,523"", ""count"" : 3 }, { ""value"" : ""2018-09-27T14:39:34,234"", ""count"" : 2 }, { ""value"" : ""2018-09-27T14:39:28,518"", ""count"" : 1 }, { ""value"" : ""2018-09-27T14:39:28,521"", ""count"" : 1 }, { ""value"" : ""2018-09-27T14:39:28,522"", ""count"" : 1 }, { ""value"" : ""2018-09-27T14:39:29,861"", ""count"" : 1 }, { ""value"" : ""2018-09-27T14:39:32,786"", ""count"" : 1 } ] } } } ---- // NOTCONSOLE <1> This time the `format` has been identified as `semi_structured_text`. <2> The `multiline_start_pattern` is set on the basis that the timestamp appears in the first line of each multi-line log message. <3> A very simple `grok_pattern` has been created, which extracts the timestamp and recognizable fields that appear in every analyzed message. In this case the only field that was recognized beyond the timestamp was the log level. If you recognize more fields than the simple `grok_pattern` produced by the structure finder unaided then you can resubmit the request specifying a more advanced `grok_pattern` as a query parameter and the structure finder will calculate `field_stats` for your additional fields. In the case of the {es} log a more complete Grok pattern is `\\[%{TIMESTAMP_ISO8601:timestamp}\\]\\[%{LOGLEVEL:loglevel} *\\]\\[%{JAVACLASS:class} *\\] \\[%{HOSTNAME:node}\\] %{JAVALOGMESSAGE:message}`. You can analyze the same log file again, submitting this `grok_pattern` as a query parameter (appropriately URL escaped): [source,js] ---- curl -s -H ""Content-Type: application/json"" -XPOST ""localhost:9200/_ml/find_file_structure?pretty&format=semi_structured_text&grok_pattern=%5C%5B%25%7BTIMESTAMP_ISO8601:timestamp%7D%5C%5D%5C%5B%25%7BLOGLEVEL:loglevel%7D%20*%5C%5D%5C%5B%25%7BJAVACLASS:class%7D%20*%5C%5D%20%5C%5B%25%7BHOSTNAME:node%7D%5C%5D%20%25%7BJAVALOGMESSAGE:message%7D"" -T ""$ES_HOME/logs/elasticsearch.log"" ---- // NOTCONSOLE // Not converting to console because this shows how curl can be used If the request does not encounter errors, the result will look something like this: [source,js] ---- { ""num_lines_analyzed"" : 53, ""num_messages_analyzed"" : 53, ""sample_start"" : ""[2018-09-27T14:39:28,518][INFO ][o.e.e.NodeEnvironment ] [node-0] using [1] data paths, mounts [[/ (/dev/disk1)]], net usable_space [165.4gb], net total_space [464.7gb], types [hfs]\\n[2018-09-27T14:39:28,521][INFO ][o.e.e.NodeEnvironment ] [node-0] heap size [494.9mb], compressed ordinary object pointers [true]\\n"", ""charset"" : ""UTF-8"", ""has_byte_order_marker"" : false, ""format"" : ""semi_structured_text"", ""multiline_start_pattern"" : ""^\\\\[\\\\b\\\\d{4}-\\\\d{2}-\\\\d{2}[T ]\\\\d{2}:\\\\d{2}"", ""grok_pattern"" : ""\\\\[%{TIMESTAMP_ISO8601:timestamp}\\\\]\\\\[%{LOGLEVEL:loglevel} *\\\\]\\\\[%{JAVACLASS:class} *\\\\] \\\\[%{HOSTNAME:node}\\\\] %{JAVALOGMESSAGE:message}"", <1> ""timestamp_field"" : ""timestamp"", ""joda_timestamp_formats"" : [ ""ISO8601"" ], ""java_timestamp_formats"" : [ ""ISO8601"" ], ""need_client_timezone"" : true, ""mappings"" : { ""@timestamp"" : { ""type"" : ""date"" }, ""class"" : { ""type"" : ""keyword"" }, ""loglevel"" : { ""type"" : ""keyword"" }, ""message"" : { ""type"" : ""text"" }, ""node"" : { ""type"" : ""keyword"" } }, ""ingest_pipeline"" : { ""description"" : ""Ingest pipeline created by file structure finder"", ""processors"" : [ { ""grok"" : { ""field"" : ""message"", ""patterns"" : [ ""\\\\[%{TIMESTAMP_ISO8601:timestamp}\\\\]\\\\[%{LOGLEVEL:loglevel} *\\\\]\\\\[%{JAVACLASS:class} *\\\\] \\\\[%{HOSTNAME:node}\\\\] %{JAVALOGMESSAGE:message}"" ] } }, { ""date"" : { ""field"" : ""timestamp"", ""timezone"" : ""{{ beat.timezone }}"", ""formats"" : [ ""ISO8601"" ] } }, { ""remove"" : { ""field"" : ""timestamp"" } } ] }, ""field_stats"" : { <2> ""class"" : { ""count"" : 53, ""cardinality"" : 14, ""top_hits"" : [ { ""value"" : ""o.e.p.PluginsService"", ""count"" : 26 }, { ""value"" : ""o.e.c.m.MetaDataIndexTemplateService"", ""count"" : 8 }, { ""value"" : ""o.e.n.Node"", ""count"" : 7 }, { ""value"" : ""o.e.e.NodeEnvironment"", ""count"" : 2 }, { ""value"" : ""o.e.a.ActionModule"", ""count"" : 1 }, { ""value"" : ""o.e.c.s.ClusterApplierService"", ""count"" : 1 }, { ""value"" : ""o.e.c.s.MasterService"", ""count"" : 1 }, { ""value"" : ""o.e.d.DiscoveryModule"", ""count"" : 1 }, { ""value"" : ""o.e.g.GatewayService"", ""count"" : 1 }, { ""value"" : ""o.e.l.LicenseService"", ""count"" : 1 } ] }, ""loglevel"" : { ""count"" : 53, ""cardinality"" : 3, ""top_hits"" : [ { ""value"" : ""INFO"", ""count"" : 51 }, { ""value"" : ""DEBUG"", ""count"" : 1 }, { ""value"" : ""WARN"", ""count"" : 1 } ] }, ""message"" : { ""count"" : 53, ""cardinality"" : 53, ""top_hits"" : [ { ""value"" : ""Using REST wrapper from plugin org.elasticsearch.xpack.security.Security"", ""count"" : 1 }, { ""value"" : ""adding template [.monitoring-alerts] for index patterns [.monitoring-alerts-6]"", ""count"" : 1 }, { ""value"" : ""adding template [.monitoring-beats] for index patterns [.monitoring-beats-6-*]"", ""count"" : 1 }, { ""value"" : ""adding template [.monitoring-es] for index patterns [.monitoring-es-6-*]"", ""count"" : 1 }, { ""value"" : ""adding template [.monitoring-kibana] for index patterns [.monitoring-kibana-6-*]"", ""count"" : 1 }, { ""value"" : ""adding template [.monitoring-logstash] for index patterns [.monitoring-logstash-6-*]"", ""count"" : 1 }, { ""value"" : ""adding template [.triggered_watches] for index patterns [.triggered_watches*]"", ""count"" : 1 }, { ""value"" : ""adding template [.watch-history-9] for index patterns [.watcher-history-9*]"", ""count"" : 1 }, { ""value"" : ""adding template [.watches] for index patterns [.watches*]"", ""count"" : 1 }, { ""value"" : ""starting ..."", ""count"" : 1 } ] }, ""node"" : { ""count"" : 53, ""cardinality"" : 1, ""top_hits"" : [ { ""value"" : ""node-0"", ""count"" : 53 } ] }, ""timestamp"" : { ""count"" : 53, ""cardinality"" : 28, ""earliest"" : ""2018-09-27T14:39:28,518"", ""latest"" : ""2018-09-27T14:39:37,012"", ""top_hits"" : [ { ""value"" : ""2018-09-27T14:39:29,859"", ""count"" : 10 }, { ""value"" : ""2018-09-27T14:39:29,860"", ""count"" : 9 }, { ""value"" : ""2018-09-27T14:39:29,858"", ""count"" : 6 }, { ""value"" : ""2018-09-27T14:39:28,523"", ""count"" : 3 }, { ""value"" : ""2018-09-27T14:39:34,234"", ""count"" : 2 }, { ""value"" : ""2018-09-27T14:39:28,518"", ""count"" : 1 }, { ""value"" : ""2018-09-27T14:39:28,521"", ""count"" : 1 }, { ""value"" : ""2018-09-27T14:39:28,522"", ""count"" : 1 }, { ""value"" : ""2018-09-27T14:39:29,861"", ""count"" : 1 }, { ""value"" : ""2018-09-27T14:39:32,786"", ""count"" : 1 } ] } } } ---- // NOTCONSOLE <1> The `grok_pattern` in the output is now the overridden one supplied in the query parameter. <2> The returned `field_stats` include entries for the fields from the overridden `grok_pattern`. The URL escaping is hard, so if you are working interactively it is best to use the {ml} UI! ",16157,True,3221.7079248442224,median "/* VERSION: 10.11 DATE: 2/25/2009 ACTIONSCRIPT VERSION: 3.0 (AS2 version is also available) UPDATES & MORE DETAILED DOCUMENTATION AT: http://www.TweenMax.com DESCRIPTION: TweenMax extends the extremely lightweight, FAST TweenLite engine, adding many useful features like pause/resume, timeScale, event listeners, reverse(), restart(), setDestination(), yoyo, loop, rounding, and the ability to jump to any point in the tween using the ""progress"" property. It also activates many extra plugins by default, making it extremely full-featured. Since TweenMax extends TweenLite, it can do ANYTHING TweenLite can do plus much more. Same syntax. There are plenty of other tweening engines out there to choose from, so here's why you might want to consider TweenMax: - SPEED - I'm not aware of any popular tweening engine with a similar feature set that's as fast as TweenMax. See some speed comparisons yourself at http://blog.greensock.com/tweening-speed-test/ - Feature set - In addition to tweening ANY numeric property of ANY object, TweenMax can tween filters, hex colors, volume, tint, frames, saturation, contrast, hue, colorization, brightness, and even do bezier tweening, orientToBezier, pause/resume, reverse(), restart(), round values, jump to any point in the tween with the ""progress"" property, automatically rotate in the shortest direction, plus LOTS more. Overwrite management is an important consideration for a tweening engine as well which is another area where the GreenSock tweening platform shines. You have options for AUTO overwriting or you can manually define how each tween will handle overlapping tweens of the same object. - Expandability - With its new plugin architecture, you can activate as many (or as few) features as your project requires. Or write your own plugin if you need a feature that's unavailable. Minimize bloat and maximize performance. - Management features - TweenGroup makes it surprisingly simple to create complex sequences and groups of TweenLite/Max tweens that you can pause(), resume(), restart(), or reverse(). You can even tween a TweenGroup's progress property to fastforward or rewind the entire group/sequence. - Ease of use - Designers and Developers alike rave about how intuitive the GreenSock tweening platform is. - Updates - Frequent updates and feature additions make the GreenSock tweening platform reliable and robust. - AS2 and AS3 - Most other engines are only developed for AS2 or AS3 but not both. PARAMETERS: 1) $target : Object - Target object whose properties we're tweening 2) $duration : Number - Duration (in seconds) of the tween 3) $vars : Object - An object containing the end values of all the properties you'd like tweened (or if you're using TweenMax.from(), these variables would define the BEGINNING values). For example, to tween myClip's alpha to 0.5 over the course of 1 second, you'd do: TweenMax.to(myClip, 1, {alpha:0.5}). SPECIAL PROPERTIES (no plugins required): Any of the following special properties can optionally be passed in through the $vars object (the third parameter): delay : Number - Amount of delay before the tween should begin (in seconds). ease : Function - Use any standard easing equation to control the rate of change. For example, gs.easing.Elastic.easeOut. The Default is Regular.easeOut. easeParams : Array - An Array of extra parameters to feed the easing equation. This can be useful when using an ease like Elastic and want to control extra parameters like the amplitude and period. Most easing equations, however, don't require extra parameters so you won't need to pass in any easeParams. onStart : Function - If you'd like to call a function as soon as the tween begins, reference it here. onStartParams : Array - An Array of parameters to pass the onStart function. onUpdate : Function - If you'd like to call a function every time the property values are updated (on every frame during the course of the tween), reference it here. onUpdateParams : Array - An Array of parameters to pass the onUpdate function onComplete : Function - If you'd like to call a function when the tween has finished, reference it here. onCompleteParams : Array - An Array of parameters to pass the onComplete function persist : Boolean - if true, the TweenMax instance will NOT automatically be removed by the garbage collector when it is complete. However, it is still eligible to be overwritten by new tweens even if persist is true. By default, it is false. renderOnStart : Boolean - If you're using TweenMax.from() with a delay and want to prevent the tween from rendering until it actually begins, set this to true. By default, it's false which causes TweenMax.from() to render its values immediately, even before the delay has expired. overwrite : int - Controls how other tweens of the same object are handled when this tween is created. Here are the options: - 0 (NONE): No tweens are overwritten. This is the fastest mode, but you need to be careful not to create any tweens with overlapping properties, otherwise they'll conflict with each other. - 1 (ALL): (this is the default unless OverwriteManager.init() has been called) All tweens of the same object are completely overwritten immediately when the tween is created. TweenMax.to(mc, 1, {x:100, y:200}); TweenMax.to(mc, 1, {x:300, delay:2, overwrite:1}); //immediately overwrites the previous tween - 2 (AUTO): (used by default if OverwriteManager.init() has been called) Searches for and overwrites only individual overlapping properties in tweens that are active when the tween begins. TweenMax.to(mc, 1, {x:100, y:200}); TweenMax.to(mc, 1, {x:300, overwrite:2}); //only overwrites the ""x"" property in the previous tween - 3 (CONCURRENT): Overwrites all tweens of the same object that are active when the tween begins. TweenMax.to(mc, 1, {x:100, y:200}); TweenMax.to(mc, 1, {x:300, delay:2, overwrite:3}); //does NOT overwrite the previous tween because the first tween will have finished by the time this one begins. onStartListener : Function - A function to which the TweenMax instance should dispatch a TweenEvent when it begins. This is the same as doing myTweenMaxInstance.addEventListener(TweenEvent.START, myFunction); onUpdateListener : Function - A function to which the TweenMax instance should dispatch a TweenEvent every time it updates values. This is the same as doing myTweenMaxInstance.addEventListener(TweenEvent.UPDATE, myFunction); onCompleteListener : Function - A function to which the TweenMax instance should dispatch a TweenEvent when it completes. This is the same as doing myTweenMaxInstance.addEventListener(TweenEvent.COMPLETE, myFunction); yoyo : Number - To make the tween reverse when it completes (like a yoyo) any number of times, set this to the number of cycles you'd like the tween to yoyo. A value of zero causes the tween to yoyo endlessly. loop : Number - To make the tween repeat when it completes any number of times, set this to the number of cycles you'd like the tween to loop. A value of zero causes the tween to loop endlessly. timeScale : Number - Multiplier that controls the speed of the tween (perceived duration) where 1 = normal speed, 0.5 = half speed, 2 = double speed, etc. NOTE: There is also a static TweenMax.globalTimeScale property that affects ALL TweenMax and TweenFilterLite tweens (not TweenLite though) startAt : Object - Allows you to define the starting values for each property. Typically, TweenMax uses the current value (whatever it happens to be at the time the tween begins) as the start value, but startAt allows you to override that behavior. Simply pass an object in with whatever properties you'd like to set just before the tween begins. For example, if mc.x is currently 100, and you'd like to tween it from 0 to 500, do TweenMax.to(mc, 2, {x:500, startAt:{x:0}}); PLUGINS: There are many plugins that add capabilities through other special properties. Adding the capabilities is as simple as activating the plugin with a single line of code, like SetSizePlugin.activate(); Get information about all the plugins at http://blog.greensock.com/plugins/ The following plugins are activated by default in TweenMax (you can easily prevent them from activating, thus saving file size, by commenting out the associated activation lines of code in the constructor): autoAlpha : Number - Use it instead of the alpha property to gain the additional feature of toggling the visible property to false when alpha reaches 0. It will also toggle visible to true before the tween starts if the value of autoAlpha is greater than zero. visible : Boolean - To set a DisplayObject's ""visible"" property at the end of the tween, use this special property. volume : Number - Tweens the volume of an object with a soundTransform property (MovieClip/SoundChannel/NetStream, etc.) tint : Number - To change a DisplayObject's tint/color, set this to the hex value of the tint you'd like to end up at(or begin at if you're using TweenMax.from()). An example hex value would be 0xFF0000. removeTint : Boolean - If you'd like to remove the tint that's applied to a DisplayObject, pass true for this special property. frame : Number - Use this to tween a MovieClip to a particular frame. bezier : Array - Bezier tweening allows you to tween in a non-linear way. For example, you may want to tween a MovieClip's position from the origin (0,0) 500 pixels to the right (500,0) but curve downwards through the middle of the tween. Simply pass as many objects in the bezier array as you'd like, one for each ""control point"" (see documentation on Flash's curveTo() drawing method for more about how control points work). In this example, let's say the control point would be at x/y coordinates 250,50. Just make sure your my_mc is at coordinates 0,0 and then do: TweenMax.to(my_mc, 3, {_x:500, _y:0, bezier:[{_x:250, _y:50}]}); bezierThrough : Array - Identical to bezier except that instead of passing bezier control point values, you pass points through which the bezier values should move. This can be more intuitive than using control points. orientToBezier : Array (or Boolean) - A common effect that designers/developers want is for a MovieClip/Sprite to orient itself in the direction of a Bezier path (alter its rotation). orientToBezier makes it easy. In order to alter a rotation property accurately, TweenMax needs 4 pieces of information: 1) Position property 1 (typically ""x"") 2) Position property 2 (typically ""y"") 3) Rotational property (typically ""rotation"") 4) Number of degrees to add (optional - makes it easy to orient your MovieClip properly) The orientToBezier property should be an Array containing one Array for each set of these values. For maximum flexibility, you can pass in any number of arrays inside the container array, one for each rotational property. This can be convenient when working in 3D because you can rotate on multiple axis. If you're doing a standard 2D x/y tween on a bezier, you can simply pass in a boolean value of true and TweenMax will use a typical setup, [[""x"", ""y"", ""rotation"", 0]]. Hint: Don't forget the container Array (notice the double outer brackets) hexColors : Object - Although hex colors are technically numbers, if you try to tween them conventionally, you'll notice that they don't tween smoothly. To tween them properly, the red, green, and blue components must be extracted and tweened independently. TweenMax makes it easy. To tween a property of your object that's a hex color to another hex color, use this special hexColors property of TweenMax. It must be an OBJECT with properties named the same as your object's hex color properties. For example, if your my_obj object has a ""myHexColor"" property that you'd like to tween to red (0xFF0000) over the course of 2 seconds, do: TweenMax.to(my_obj, 2, {hexColors:{myHexColor:0xFF0000}}); You can pass in any number of hexColor properties. shortRotation : Number - To tween the rotation property of the target object in the shortest direction, use ""shortRotation"" instead of ""rotation"" as the property. For example, if myObject.rotation is currently 170 degrees and you want to tween it to -170 degrees, a normal rotation tween would travel a total of 340 degrees in the counter-clockwise direction, but if you use shortRotation, it would travel 20 degrees in the clockwise direction instead. roundProps : Array - If you'd like the inbetween values in a tween to always get rounded to the nearest integer, use the roundProps special property. Just pass in an Array containing the property names that you'd like rounded. For example, if you're tweening the x, y, and alpha properties of mc and you want to round the x and y values (not alpha) every time the tween is rendered, you'd do: TweenMax.to(mc, 2, {x:300, y:200, alpha:0.5, roundProps:[""x"",""y""]}); blurFilter : Object - To apply a BlurFilter, pass an object with one or more of the following properties: blurX, blurY, quality glowFilter : Object - To apply a GlowFilter, pass an object with one or more of the following properties: alpha, blurX, blurY, color, strength, quality, inner, knockout colorMatrixFilter : Object - To apply a ColorMatrixFilter, pass an object with one or more of the following properties: colorize, amount, contrast, brightness, saturation, hue, threshold, relative, matrix dropShadowFilter : Object - To apply a DropShadowFilter, pass an object with one or more of the following properties: alpha, angle, blurX, blurY, color, distance, strength, quality bevelFilter : Object - To apply a BevelFilter, pass an object with one or more of the following properties: angle, blurX, blurY, distance, highlightAlpha, highlightColor, shadowAlpha, shadowColor, strength, quality KEY PROPERTIES: - progress : Number (0 - 1 where 0 = tween hasn't progressed, 0.5 = tween is halfway done, and 1 = tween is finished) - timeScale : Number (Multiplier that controls the speed of the tween where 1 = normal speed, 0.5 = half speed, 2 = double speed, etc. ) - paused : Boolean - reversed : Boolean KEY METHODS: - TweenMax.to(target:Object, duration:Number, vars:Object):TweenMax - TweenMax.from(target:Object, duration:Number, vars:Object):TweenMax - TweenMax.getTweensOf(target:Object):Array - TweenMax.isTweening(target:Object):Boolean - TweenMax.getAllTweens():Array - TweenMax.killAllTweens(complete:Boolean):void - TweenMax.killAllDelayedCalls(complete:Boolean):void - TweenMax.pauseAll(tweens:Boolean, delayedCalls:Boolean):void - TweenMax.resumeAll(tweens:Boolean, delayedCalls:Boolean):void - TweenMax.delayedCall(delay:Number, function:Function, params:Array, persist:Boolean):TweenMax - TweenMax.setGlobalTimeScale(scale:Number):void - addEventListener(type:String, listener:Function, useCapture:Boolean, priority:int, useWeakReference:Boolean):void - removeEventListener(type:String, listener:Function):void - pause():void - resume():void - restart(includeDelay:Boolean):void - reverse(adjustStart:Boolean, forcePlay:Boolean):void - setDestination(property:String, value:*, adjustStartValues:Boolean):void - invalidate(adjustStartValues:Boolean):void - killProperties(names:Array):void EXAMPLES: To tween the clip_mc MovieClip over 5 seconds, changing the alpha to 0.5, the x to 120 using the Back.easeOut easing function, delay starting the whole tween by 2 seconds, and then call a function named ""onFinishTween"" when it has completed and pass in a few parameters to that function (a value of 5 and a reference to the clip_mc), you'd do so like: import gs.*; import gs.easing.*; TweenMax.to(clip_mc, 5, {alpha:0.5, x:120, ease:Back.easeOut, delay:2, onComplete:onFinishTween, onCompleteParams:[5, clip_mc]}); function onFinishTween(argument1:Number, argument2:MovieClip):void { trace(""The tween has finished! argument1 = "" + argument1 + "", and argument2 = "" + argument2); } If you have a MovieClip on the stage that is already in it's end position and you just want to animate it into place over 5 seconds (drop it into place by changing its y property to 100 pixels higher on the screen and dropping it from there), you could: import gs.*; import gs.easing.*; TweenMax.from(clip_mc, 5, {y:""-100"", ease:Elastic.easeOut}); To set up an onUpdate listener (not callback) that traces the ""progress"" property of a tween, and another listener that gets called when the tween completes, you could do: import gs.*; import gs.events.TweenEvent; TweenMax.to(clip_mc, 2, {x:200, onUpdateListener:reportProgress, onCompleteListener:tweenFinished}); function reportProgress($e:TweenEvent):void { trace(""tween progress: "" + $e.target.progress); } function tweenFinished($e:TweenEvent):void { trace(""tween finished!""); } NOTES / HINTS: - Passing values as Strings will make the tween relative to the current value. For example, if you do TweenMax.to(mc, 2, {x:""-20""}); it'll move the mc.x to the left 20 pixels which is the same as doing TweenMax.to(mc, 2, {x:mc.x - 20}); You could also cast it like: TweenMax.to(mc, 2, {x:String(myVariable)}); - If you prefer, instead of using the onCompleteListener, onStartListener, and onUpdateListener special properties, you can set up listeners the typical way, like: var myTween:TweenMax = new TweenMax(my_mc, 2, {x:200}); myTween.addEventListener(TweenEvent.COMPLETE, myFunction); - To tween an Array, just pass in an Array as a property named endArray like: var myArray:Array = [1,2,3,4]; TweenMax.to(myArray, 1.5, {endArray:[10,20,30,40]}); - You can kill all tweens of a particular object anytime with the TweenMax.killTweensOf(myObject); function. If you want to have the tweens forced to completion, pass true as the second parameter, like TweenMax.killTweensOf(myObject, true); - You can kill all delayedCalls to a particular function using TweenMax.killDelayedCallsTo(myFunction); This can be helpful if you want to preempt a call. - Use the TweenMax.from() method to animate things into place. For example, if you have things set up on the stage in the spot where they should end up, and you just want to animate them into place, you can pass in the beginning x and/or y and/or alpha (or whatever properties you want). - If you find this class useful, please consider joining Club GreenSock which not only contributes to ongoing development, but also gets you bonus classes (and other benefits) that are ONLY available to members. Learn more at http://blog.greensock.com/club/ CHANGE LOG: 10.11: - Fixed bug in setDestination() when adjustStartValues was false - Fixed bug in startAt that caused it to wait one frame when the delay was zero. 10.1: - Fixed bug that caused error when ""omit trace actions"" was selected in publish settings. 10.09: - Fixed bug with timeScale 10.08: - Fixed bug in setDestination() - Fixed bug in SetSizePlugin - Fixed bug in isTweening() which didn't report true immediately after a tween was created. 10.07: - Fixed reporting of ""paused"" property being reversed 10.06: - Added ""startAt"" special property for defining starting values. - Speed improvements - Integrated a new gs.utils.tween.TweenInfo class - Minor internal changes 10.0: - Major update, shifting to a ""plugin"" architecture for handling special properties. - Eliminated TweenFilterLite and extended TweenLite instead - Added ""remove"" property to all filter tweens to accommodate removing the filter at the end of the tween - Added ""setSize"" and ""frameLabel"" plugins - Speed enhancements - Fixed minor overwrite bugs - Updated the version to sync better with TweenLite (jumped from 3.6 to 10.0) 3.6: - Added compatibility with TweenProxy and TweenProxy3D - Fixed bug with adding event listeners via TweenMaxVars 3.52: - Adjusted how the timeScale special property is handled internally. It should be more flexible and slightly faster now. - Changed the way parseBeziers() stores values to make bezier tweening faster (Arrays instead of Objects with named properties) 3.51: - Fixed problem that caused killAllTweens() to not fully kill paused tweens 3.5: - Changed yoyo and loop behavior so that instead of being Boolean values that loop or yoyo endlessly, they're numbers so that you can define a specific number of cycles you'd like the tween to loop or yoyo. Zero causes the loop or yoyo to repeat endlessly. 3.41: - Fixed conflict between TweenMaxVars and the new shortRotation property in Flash Player 10 3.4: - Added ""shortRotation"" special property - Minor speed enhancement 3.391: - Minor change to make the timing of looping and yoyo-ing tweens more accurate (a few milliseconds could have been lost previously when the loop or yoyo was triggered) 3.39: - Speed improvement and slight file size decrease 3.37: - Fixed resumeAll() 3.36: - Fixed bug with autoAlpha tweens working with TweenGroups when they're reversed. 3.35: - Deprecated allTo() and allFrom() in favor of the much more powerful and flexible TweenGroup class (see http://blog.greensock.com/tweengroup/ for details) 3.2: - Added ""roundProps"" special property for rounding values - Fixed but with TweenLiteVars, TweenFilterVars, and TweenMaxVars that caused ""visible"" to always get set at the end of a tween 3.1: - In AUTO or CONCURRENT mode, OverwriteManager doesn't handle overwriting until the tween actually begins which allows for immediate pause()-ing or re-ordering in TweenGroup, etc. - Re-architected some inner-workings to further optimize for speed and reduce file size 3.04: - Fixed bug with killTweensOf() - Fixed bug with reverse() - Fixed bug with from() 3.0: - Deprecated sequence() and multiSequence() in favor of the much more powerful and flexible TweenGroup class (see http://blog.greensock.com/tweengroup/ for details) - Added clear() method - Added a ""clear"" parameter to the removeTween() method - Exposed TweenLite.currentTime as well as several other TweenLite variables for compatibility with TweenGroup 2.35: - Fixed potential problem if multiple tweens used the same vars object and reverse() was called on more than one. 2.34: - Fixed problem with COMPLETE event listeners not firing when killTweensOf() was called with the forceComplete parameter set to true 2.32: - Fixed bug with invalidating() a tween with event listeners and adding an UPDATE listener after a tween is instantiated. 2.31: - invalidate() reparses onCompleteListener, onUpdateListener, and onStartListener special properties now. - If a tween completed without persist:true and the globalTimeScale was updated between that time and the time restart(), reverse(), or resume() was called, it could have an incorrect timeScale. That's fixed now. 2.3: - Added setGlobalTimeScale() function to control the speed of all TweenFilterLite and TweenMax instances - Added static ""globalTimeScale"" property to TweenMax and TweenFilterLite classes. You can even tween it like TweenLite.to(TweenMax, 1, {globalTimeScale:0.5}); - Changed timeScale so that it also affects the delay (if any) AUTHOR: Jack Doyle, jack@greensock.com Copyright 2009, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. */ package gs { import flash.events.*; import flash.utils.*; import gs.events.TweenEvent; import gs.plugins.*; import gs.utils.tween.*; public class TweenMax extends TweenLite implements IEventDispatcher { public static const version:Number = 10.1; private static var _activatedPlugins:Boolean = TweenPlugin.activate([ //ACTIVATE (OR DEACTIVATE) PLUGINS HERE... TintPlugin, //tweens tints RemoveTintPlugin, //allows you to remove a tint FramePlugin, //tweens MovieClip frames AutoAlphaPlugin, //tweens alpha and then toggles ""visible"" to false if/when alpha is zero VisiblePlugin, //tweens a target's ""visible"" property VolumePlugin, //tweens the volume of a MovieClip or SoundChannel or anything with a ""soundTransform"" property EndArrayPlugin, //tweens numbers in an Array HexColorsPlugin, //tweens hex colors BlurFilterPlugin, //tweens BlurFilters ColorMatrixFilterPlugin, //tweens ColorMatrixFilters (including hue, saturation, colorize, contrast, brightness, and threshold) BevelFilterPlugin, //tweens BevelFilters DropShadowFilterPlugin, //tweens DropShadowFilters GlowFilterPlugin, //tweens GlowFilters RoundPropsPlugin, //enables the roundProps special property for rounding values. BezierPlugin, //enables bezier tweening BezierThroughPlugin, //enables bezierThrough tweening ShortRotationPlugin //tweens rotation values in the shortest direction ]); //activated in static var instead of constructor because otherwise if there's a from() tween, TweenLite's constructor would get called first and initTweenVals() would run before the plugins were activated. private static var _overwriteMode:int = (OverwriteManager.enabled) ? OverwriteManager.mode : OverwriteManager.init(); //OverwriteManager is optional for TweenLite and TweenFilterLite, but it is used by default in TweenMax. public static var killTweensOf:Function = TweenLite.killTweensOf; public static var killDelayedCallsTo:Function = TweenLite.killTweensOf; public static var removeTween:Function = TweenLite.removeTween; protected static var _pausedTweens:Dictionary = new Dictionary(false); //protects from garbage collection issues protected static var _globalTimeScale:Number = 1; protected var _dispatcher:EventDispatcher; protected var _callbacks:Object; //stores the original onComplete, onStart, and onUpdate Functions from the this.vars Object (we replace them if/when dispatching events) protected var _repeatCount:Number; //number of times the tween has yoyo'd or loop'd. protected var _timeScale:Number; //Allows you to speed up or slow down a tween. Default is 1 (normal speed) 0.5 would be half-speed public var pauseTime:Number; public function TweenMax($target:Object, $duration:Number, $vars:Object) { super($target, $duration, $vars); if (TweenLite.version < 10.09) { trace(""TweenMax error! Please update your TweenLite class or try deleting your ASO files. TweenMax requires a more recent version. Download updates at http://www.TweenMax.com.""); } if (this.combinedTimeScale != 1 && this.target is TweenMax) { //in case the user is trying to tween the timeScale of another TweenFilterLite/TweenMax instance _timeScale = 1; this.combinedTimeScale = _globalTimeScale; } else { _timeScale = this.combinedTimeScale; this.combinedTimeScale *= _globalTimeScale; //combining them speeds processing in important functions like render(). } if (this.combinedTimeScale != 1 && this.delay != 0) { this.startTime = this.initTime + (this.delay * (1000 / this.combinedTimeScale)); } if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null) { initDispatcher(); if ($duration == 0 && this.delay == 0) { onUpdateDispatcher(); onCompleteDispatcher(); } } _repeatCount = 0; if (!isNaN(this.vars.yoyo) || !isNaN(this.vars.loop)) { this.vars.persist = true; } if (this.delay == 0 && this.exposedVars.startAt != null) { this.exposedVars.startAt.overwrite = 0; new TweenMax(this.target, 0, this.exposedVars.startAt); } } override public function initTweenVals():void { if (this.exposedVars.startAt != null && this.delay != 0) { this.exposedVars.startAt.overwrite = 0; new TweenMax(this.target, 0, this.exposedVars.startAt); } super.initTweenVals(); //accommodate rounding if necessary... if (this.exposedVars.roundProps is Array && TweenLite.plugins.roundProps != null) { var i:int, j:int, prop:String, multiProps:String, rp:Array = this.exposedVars.roundProps, plugin:Object, ti:TweenInfo; for (i = rp.length - 1; i > -1; i--) { prop = rp[i]; for (j = this.tweens.length - 1; j > -1; j--) { ti = this.tweens[j]; if (ti.name == prop) { if (ti.isPlugin) { ti.target.round = true; } else { if (plugin == null) { plugin = new TweenLite.plugins.roundProps(); plugin.add(ti.target, prop, ti.start, ti.change); _hasPlugins = true; this.tweens[j] = new TweenInfo(plugin, ""changeFactor"", 0, 1, prop, true); } else { plugin.add(ti.target, prop, ti.start, ti.change); //using a single plugin for rounding speeds processing this.tweens.splice(j, 1); } } } else if (ti.isPlugin && ti.name == ""_MULTIPLE_"" && !ti.target.round) { multiProps = "" "" + ti.target.overwriteProps.join("" "") + "" ""; if (multiProps.indexOf("" "" + prop + "" "") != -1) { ti.target.round = true; } } } } } } public function pause():void { if (isNaN(this.pauseTime)) { this.pauseTime = currentTime; this.startTime = 999999999999999; //required for OverwriteManager this.enabled = false; _pausedTweens[this] = this; } } public function resume():void { this.enabled = true; if (!isNaN(this.pauseTime)) { this.initTime += currentTime - this.pauseTime; this.startTime = this.initTime + (this.delay * (1000 / this.combinedTimeScale)); this.pauseTime = NaN; if (!this.started && currentTime >= this.startTime) { activate(); //triggers onStart if necessary and initTweenVals() } else { this.active = this.started; } _pausedTweens[this] = null; delete _pausedTweens[this]; } } public function restart($includeDelay:Boolean=false):void { if ($includeDelay) { this.initTime = currentTime; this.startTime = currentTime + (this.delay * (1000 / this.combinedTimeScale)); } else { this.startTime = currentTime; this.initTime = currentTime - (this.delay * (1000 / this.combinedTimeScale)); } _repeatCount = 0; if (this.target != this.vars.onComplete) { //protects delayedCall()s from being rendered. render(this.startTime); } this.pauseTime = NaN; _pausedTweens[this] = null; delete _pausedTweens[this]; this.enabled = true; } public function reverse($adjustDuration:Boolean=true, $forcePlay:Boolean=true):void { this.ease = (this.vars.ease == this.ease) ? reverseEase : this.vars.ease; var p:Number = this.progress; if ($adjustDuration && p > 0) { this.startTime = currentTime - ((1 - p) * this.duration * 1000 / this.combinedTimeScale); this.initTime = this.startTime - (this.delay * (1000 / this.combinedTimeScale)); } if ($forcePlay != false) { if (p < 1) { resume(); } else { restart(); } } } public function reverseEase($t:Number, $b:Number, $c:Number, $d:Number):Number { return this.vars.ease($d - $t, $b, $c, $d); } public function invalidate($adjustStartValues:Boolean=true):void { //forces the vars to be re-parsed and immediately re-rendered if (this.initted) { var p:Number = this.progress; if (!$adjustStartValues && p != 0) { this.progress = 0; } this.tweens = []; _hasPlugins = false; this.exposedVars = (this.vars.isTV == true) ? this.vars.exposedProps : this.vars; //for TweenLiteVars and TweenMaxVars initTweenVals(); _timeScale = this.vars.timeScale || 1; this.combinedTimeScale = _timeScale * _globalTimeScale; this.delay = this.vars.delay || 0; if (isNaN(this.pauseTime)) { this.startTime = this.initTime + (this.delay * 1000 / this.combinedTimeScale); } if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null) { if (_dispatcher != null) { this.vars.onStart = _callbacks.onStart; this.vars.onUpdate = _callbacks.onUpdate; this.vars.onComplete = _callbacks.onComplete; _dispatcher = null; } initDispatcher(); } if (p != 0) { if ($adjustStartValues) { adjustStartValues(); } else { this.progress = p; } } } } public function setDestination($property:String, $value:*, $adjustStartValues:Boolean=true):void { var p:Number = this.progress, i:int, ti:TweenInfo; if (this.initted) { if (!$adjustStartValues) { for (i = this.tweens.length - 1; i > -1; i--) { ti = this.tweens[i]; if (ti.name == $property) { ti.target[ti.property] = ti.start; //return it to its start value (tween index values: [object, property, start, change, name]) } } } var varsOld:Object = this.vars; var exposedVarsOld:Object = this.exposedVars; var tweensOld:Array = this.tweens; var hadPlugins:Boolean = _hasPlugins; this.tweens = []; this.vars = this.exposedVars = {}; this.vars[$property] = $value; initTweenVals(); if (this.ease != reverseEase && varsOld.ease is Function) { this.ease = varsOld.ease; } if ($adjustStartValues && p != 0) { adjustStartValues(); } var addedTweens:Array = this.tweens; this.vars = varsOld; this.exposedVars = exposedVarsOld; this.tweens = tweensOld; var killVars:Object = {}; killVars[$property] = true; for (i = this.tweens.length - 1; i > -1; i--) { ti = this.tweens[i]; if (ti.name == $property) { this.tweens.splice(i, 1); } else if (ti.isPlugin && ti.name == ""_MULTIPLE_"") { //is a plugin with multiple overwritable properties ti.target.killProps(killVars); if (ti.target.overwriteProps.length == 0) { this.tweens.splice(i, 1); } } } this.tweens = this.tweens.concat(addedTweens); _hasPlugins = Boolean(hadPlugins || _hasPlugins); } this.vars[$property] = this.exposedVars[$property] = $value; } protected function adjustStartValues():void { //adjusts the start values in the tweens so that the current progress and end values are maintained which prevents ""skipping"" when changing destination values mid-way through the tween. var p:Number = this.progress; if (p != 0) { var factor:Number = this.ease(p, 0, 1, 1); var inv:Number = 1 / (1 - factor); var endValue:Number, ti:TweenInfo, i:int; for (i = this.tweens.length - 1; i > -1; i--) { ti = this.tweens[i]; endValue = ti.start + ti.change; //[object, property, start, change, name, isPlugin] if (ti.isPlugin) { //can't read the ""progress"" value of a plugin, but we know what it is based on the factor (above) ti.change = (endValue - factor) * inv; } else { ti.change = (endValue - ti.target[ti.property]) * inv; } ti.start = endValue - ti.change; } } } public function killProperties($names:Array):void { var v:Object = {}, i:int; for (i = $names.length - 1; i > -1; i--) { v[$names[i]] = true; } killVars(v); } override public function render($t:uint):void { var time:Number = ($t - this.startTime) * 0.001 * this.combinedTimeScale, factor:Number, ti:TweenInfo, i:int; if (time >= this.duration) { time = this.duration; factor = (this.ease == this.vars.ease || this.duration == 0.001) ? 1 : 0; //to accommodate TweenMax.reverse(). Without this, the last frame would render incorrectly } else { factor = this.ease(time, 0, 1, this.duration); } for (i = this.tweens.length - 1; i > -1; i--) { ti = this.tweens[i]; ti.target[ti.property] = ti.start + (factor * ti.change); //tween index values: [object, property, start, change, name, isPlugin] } if (_hasUpdate) { this.vars.onUpdate.apply(null, this.vars.onUpdateParams); } if (time == this.duration) { //Check to see if we're done complete(true); } } override public function complete($skipRender:Boolean = false):void { if ((!isNaN(this.vars.yoyo) && (_repeatCount < this.vars.yoyo || this.vars.yoyo == 0)) || (!isNaN(this.vars.loop) && (_repeatCount < this.vars.loop || this.vars.loop == 0))) { _repeatCount++; if (!isNaN(this.vars.yoyo)) { this.ease = (this.vars.ease == this.ease) ? reverseEase : this.vars.ease; } this.startTime = ($skipRender) ? this.startTime + (this.duration * (1000 / this.combinedTimeScale)) : currentTime; //for more accurate results, add the duration to the startTime, otherwise a few milliseconds might be skipped. You can occassionally see this if you have two simultaneous looping tweens with different end times that move objects that are butted up against each other. this.initTime = this.startTime - (this.delay * (1000 / this.combinedTimeScale)); } else if (this.vars.persist == true) { //super.complete($skipRender); pause(); //return; } super.complete($skipRender); } //---- EVENT DISPATCHING ---------------------------------------------------------------------------------------------------------- protected function initDispatcher():void { if (_dispatcher == null) { _dispatcher = new EventDispatcher(this); _callbacks = {onStart:this.vars.onStart, onUpdate:this.vars.onUpdate, onComplete:this.vars.onComplete}; //store the originals if (this.vars.isTV == true) { //For TweenLiteVars, TweenFilterLiteVars, and TweenMaxVars compatibility this.vars = this.vars.clone(); } else { var v:Object = {}, p:String; for (p in this.vars) { v[p] = this.vars[p]; //Just in case the same vars Object is reused for multiple tweens, we need to copy all the properties and create a duplicate so that we don't interfere with other tweens. } this.vars = v; } this.vars.onStart = onStartDispatcher; this.vars.onComplete = onCompleteDispatcher; if (this.vars.onStartListener is Function) { _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true); } if (this.vars.onUpdateListener is Function) { _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true); this.vars.onUpdate = onUpdateDispatcher; //To improve performance, we only want to add UPDATE dispatching if absolutely necessary. _hasUpdate = true; } if (this.vars.onCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true); } } } protected function onStartDispatcher(... $args):void { if (_callbacks.onStart != null) { _callbacks.onStart.apply(null, this.vars.onStartParams); } _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START)); } protected function onUpdateDispatcher(... $args):void { if (_callbacks.onUpdate != null) { _callbacks.onUpdate.apply(null, this.vars.onUpdateParams); } _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE)); } protected function onCompleteDispatcher(... $args):void { if (_callbacks.onComplete != null) { _callbacks.onComplete.apply(null, this.vars.onCompleteParams); } _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE)); } public function addEventListener($type:String, $listener:Function, $useCapture:Boolean = false, $priority:int = 0, $useWeakReference:Boolean = false):void { if (_dispatcher == null) { initDispatcher(); } if ($type == TweenEvent.UPDATE && this.vars.onUpdate != onUpdateDispatcher) { //To improve performance, we only want to add UPDATE dispatching if absolutely necessary. this.vars.onUpdate = onUpdateDispatcher; _hasUpdate = true; } _dispatcher.addEventListener($type, $listener, $useCapture, $priority, $useWeakReference); } public function removeEventListener($type:String, $listener:Function, $useCapture:Boolean = false):void { if (_dispatcher != null) { _dispatcher.removeEventListener($type, $listener, $useCapture); } } public function hasEventListener($type:String):Boolean { if (_dispatcher == null) { return false; } else { return _dispatcher.hasEventListener($type); } } public function willTrigger($type:String):Boolean { if (_dispatcher == null) { return false; } else { return _dispatcher.willTrigger($type); } } public function dispatchEvent($e:Event):Boolean { if (_dispatcher == null) { return false; } else { return _dispatcher.dispatchEvent($e); } } //---- STATIC FUNCTIONS ----------------------------------------------------------------------------------------------------------- public static function to($target:Object, $duration:Number, $vars:Object):TweenMax { return new TweenMax($target, $duration, $vars); } public static function from($target:Object, $duration:Number, $vars:Object):TweenMax { $vars.runBackwards = true; return new TweenMax($target, $duration, $vars); } public static function delayedCall($delay:Number, $onComplete:Function, $onCompleteParams:Array=null, $persist:Boolean=false):TweenMax { return new TweenMax($onComplete, 0, {delay:$delay, onComplete:$onComplete, onCompleteParams:$onCompleteParams, persist:$persist, overwrite:0}); } public static function setGlobalTimeScale($scale:Number):void { if ($scale < 0.00001) { $scale = 0.00001; } var ml:Dictionary = masterList, i:int, a:Array; _globalTimeScale = $scale; for each (a in ml) { for (i = a.length - 1; i > -1; i--) { if (a[i] is TweenMax) { a[i].timeScale *= 1; //just forces combining of the _timeScale and _globalTimeScale. } } } } public static function getTweensOf($target:Object):Array { var a:Array = masterList[$target]; var toReturn:Array = []; if(a != null) { for (var i:int = a.length - 1; i > -1; i--) { if (!a[i].gc) { toReturn[toReturn.length] = a[i]; } } } for each (var tween:TweenLite in _pausedTweens) { if (tween.target == $target) { toReturn[toReturn.length] = tween; } } return toReturn; } public static function isTweening($target:Object):Boolean { var a:Array = getTweensOf($target); for (var i:int = a.length - 1; i > -1; i--) { if ((a[i].active || a[i].startTime == currentTime) && !a[i].gc) { return true; } } return false; } public static function getAllTweens():Array { var ml:Dictionary = masterList; //speeds things up slightly var toReturn:Array = [], a:Array, i:int, tween:TweenLite; for each (a in ml) { for (i = a.length - 1; i > -1; i--) { if (!a[i].gc) { toReturn[toReturn.length] = a[i]; } } } for each (tween in _pausedTweens) { toReturn[toReturn.length] = tween; } return toReturn; } public static function killAllTweens($complete:Boolean = false):void { killAll($complete, true, false); } public static function killAllDelayedCalls($complete:Boolean = false):void { killAll($complete, false, true); } public static function killAll($complete:Boolean = false, $tweens:Boolean = true, $delayedCalls:Boolean = true):void { var a:Array = getAllTweens(); var isDC:Boolean, i:int; //is delayedCall for (i = a.length - 1; i > -1; i--) { isDC = (a[i].target == a[i].vars.onComplete); if (isDC == $delayedCalls || isDC != $tweens) { if ($complete) { a[i].complete(false); a[i].clear(); } else { TweenLite.removeTween(a[i], true); } } } } public static function pauseAll($tweens:Boolean = true, $delayedCalls:Boolean = false):void { changePause(true, $tweens, $delayedCalls); } public static function resumeAll($tweens:Boolean = true, $delayedCalls:Boolean = false):void { changePause(false, $tweens, $delayedCalls); } public static function changePause($pause:Boolean, $tweens:Boolean = true, $delayedCalls:Boolean = false):void { var a:Array = getAllTweens(); var isDC:Boolean; //is delayedCall for (var i:int = a.length - 1; i > -1; i--) { isDC = (a[i].target == a[i].vars.onComplete); if (a[i] is TweenMax && (isDC == $delayedCalls || isDC != $tweens)) { a[i].paused = $pause; } } } //---- GETTERS / SETTERS ---------------------------------------------------------------------------------------------------------- public function get paused():Boolean { return !isNaN(this.pauseTime); } public function set paused($b:Boolean):void { if ($b) { pause(); } else { resume(); } } public function get reversed():Boolean { return (this.ease == reverseEase); } public function set reversed($b:Boolean):void { if (this.reversed != $b) { reverse(); } } public function get timeScale():Number { return _timeScale; } public function set timeScale($n:Number):void { if ($n < 0.00001) { $n = _timeScale = 0.00001; } else { _timeScale = $n; $n *= _globalTimeScale; //instead of doing _timeScale * _globalTimeScale in the render() and elsewhere, we improve performance by combining them here. } this.initTime = currentTime - ((currentTime - this.initTime - (this.delay * (1000 / this.combinedTimeScale))) * this.combinedTimeScale * (1 / $n)) - (this.delay * (1000 / $n)); if (this.startTime != 999999999999999) { //required for OverwriteManager (indicates a TweenMax instance that has been paused) this.startTime = this.initTime + (this.delay * (1000 / $n)); } this.combinedTimeScale = $n; } override public function set enabled($b:Boolean):void { if (!$b) { _pausedTweens[this] = null; delete _pausedTweens[this]; } super.enabled = $b; if ($b) { this.combinedTimeScale = _timeScale * _globalTimeScale; } } public static function set globalTimeScale($n:Number):void { setGlobalTimeScale($n); } public static function get globalTimeScale():Number { return _globalTimeScale; } public function get progress():Number { var t:Number = (!isNaN(this.pauseTime)) ? this.pauseTime : currentTime; var p:Number = (((t - this.initTime) * 0.001) - this.delay / this.combinedTimeScale) / this.duration * this.combinedTimeScale; if (p > 1) { return 1; } else if (p < 0) { return 0; } else { return p; } } public function set progress($n:Number):void { this.startTime = currentTime - ((this.duration * $n) * 1000); this.initTime = this.startTime - (this.delay * (1000 / this.combinedTimeScale)); if (!this.started) { activate();//Just to trigger all the onStart stuff and make sure initTweenVals() has been called. } render(currentTime); if (!isNaN(this.pauseTime)) { this.pauseTime = currentTime; this.startTime = 999999999999999; //required for OverwriteManager this.active = false; } } } }",12521,False,1803.8109848525683,median "// Urho3D material editor Window@ particleEffectWindow; ParticleEffect@ editParticleEffect; XMLFile@ oldParticleEffectState; bool inParticleEffectRefresh = false; View3D@ particleEffectPreview; Scene@ particlePreviewScene; Node@ particleEffectPreviewNode; Node@ particlePreviewCameraNode; Node@ particlePreviewLightNode; Light@ particlePreviewLight; ParticleEmitter@ particleEffectEmitter; float particleResetTimer; void CreateParticleEffectEditor() { if (particleEffectWindow !is null) return; particleEffectWindow = LoadEditorUI(""UI/EditorParticleEffectWindow.xml""); ui.root.AddChild(particleEffectWindow); particleEffectWindow.opacity = uiMaxOpacity; InitParticleEffectPreview(); InitParticleEffectBasicAttributes(); RefreshParticleEffectEditor(); int height = Min(ui.root.height - 60, 500); particleEffectWindow.SetSize(300, height); CenterDialog(particleEffectWindow); HideParticleEffectEditor(); SubscribeToEvent(particleEffectWindow.GetChild(""NewButton"", true), ""Released"", ""NewParticleEffect""); SubscribeToEvent(particleEffectWindow.GetChild(""RevertButton"", true), ""Released"", ""RevertParticleEffect""); SubscribeToEvent(particleEffectWindow.GetChild(""SaveButton"", true), ""Released"", ""SaveParticleEffect""); SubscribeToEvent(particleEffectWindow.GetChild(""SaveAsButton"", true), ""Released"", ""SaveParticleEffectAs""); SubscribeToEvent(particleEffectWindow.GetChild(""CloseButton"", true), ""Released"", ""HideParticleEffectEditor""); SubscribeToEvent(particleEffectWindow.GetChild(""NewColorFrame"", true), ""Released"", ""EditParticleEffectColorFrameNew""); SubscribeToEvent(particleEffectWindow.GetChild(""RemoveColorFrame"", true), ""Released"", ""EditParticleEffectColorFrameRemove""); SubscribeToEvent(particleEffectWindow.GetChild(""ColorFrameSort"", true), ""Released"", ""EditParticleEffectColorFrameSort""); SubscribeToEvent(particleEffectWindow.GetChild(""NewTextureFrame"", true), ""Released"", ""EditParticleEffectTextureFrameNew""); SubscribeToEvent(particleEffectWindow.GetChild(""RemoveTextureFrame"", true), ""Released"", ""EditParticleEffectTextureFrameRemove""); SubscribeToEvent(particleEffectWindow.GetChild(""TextureFrameSort"", true), ""Released"", ""EditParticleEffectTextureFrameSort""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceX"", true), ""TextChanged"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceY"", true), ""TextChanged"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceZ"", true), ""TextChanged"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinX"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinY"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinZ"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxX"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxY"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxZ"", true), ""TextChanged"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DampingForce"", true), ""TextChanged"", ""EditParticleEffectDampingForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ActiveTime"", true), ""TextChanged"", ""EditParticleEffectActiveTime""); SubscribeToEvent(particleEffectWindow.GetChild(""InactiveTime"", true), ""TextChanged"", ""EditParticleEffectInactiveTime""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinX"", true), ""TextChanged"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinY"", true), ""TextChanged"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true), ""TextChanged"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true), ""TextChanged"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMin"", true), ""TextChanged"", ""EditParticleEffectTimeToLive""); SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMax"", true), ""TextChanged"", ""EditParticleEffectTimeToLive""); SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMin"", true), ""TextChanged"", ""EditParticleEffectVelocity""); SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMax"", true), ""TextChanged"", ""EditParticleEffectVelocity""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationMin"", true), ""TextChanged"", ""EditParticleEffectRotation""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationMax"", true), ""TextChanged"", ""EditParticleEffectRotation""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMin"", true), ""TextChanged"", ""EditParticleEffectRotationSpeed""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMax"", true), ""TextChanged"", ""EditParticleEffectRotationSpeed""); SubscribeToEvent(particleEffectWindow.GetChild(""SizeAdd"", true), ""TextChanged"", ""EditParticleEffectSizeAdd""); SubscribeToEvent(particleEffectWindow.GetChild(""SizeMultiply"", true), ""TextChanged"", ""EditParticleEffectSizeMultiply""); SubscribeToEvent(particleEffectWindow.GetChild(""AnimationLodBias"", true), ""TextChanged"", ""EditParticleEffectAnimationLodBias""); SubscribeToEvent(particleEffectWindow.GetChild(""NumParticles"", true), ""TextChanged"", ""EditParticleEffectNumParticles""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeX"", true), ""TextChanged"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeY"", true), ""TextChanged"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeZ"", true), ""TextChanged"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMin"", true), ""TextChanged"", ""EditParticleEffectEmissionRate""); SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMax"", true), ""TextChanged"", ""EditParticleEffectEmissionRate""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceX"", true), ""TextFinished"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceY"", true), ""TextFinished"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ConstantForceZ"", true), ""TextFinished"", ""EditParticleEffectConstantForce""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinX"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinY"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMinZ"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxX"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxY"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DirectionMaxZ"", true), ""TextFinished"", ""EditParticleEffectDirection""); SubscribeToEvent(particleEffectWindow.GetChild(""DampingForce"", true), ""TextFinished"", ""EditParticleEffectDampingForce""); SubscribeToEvent(particleEffectWindow.GetChild(""ActiveTime"", true), ""TextFinished"", ""EditParticleEffectActiveTime""); SubscribeToEvent(particleEffectWindow.GetChild(""InactiveTime"", true), ""TextFinished"", ""EditParticleEffectInactiveTime""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinX"", true), ""TextFinished"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMinY"", true), ""TextFinished"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true), ""TextFinished"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true), ""TextFinished"", ""EditParticleEffectParticleSize""); SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMin"", true), ""TextFinished"", ""EditParticleEffectTimeToLive""); SubscribeToEvent(particleEffectWindow.GetChild(""TimeToLiveMax"", true), ""TextFinished"", ""EditParticleEffectTimeToLive""); SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMin"", true), ""TextFinished"", ""EditParticleEffectVelocity""); SubscribeToEvent(particleEffectWindow.GetChild(""VelocityMax"", true), ""TextFinished"", ""EditParticleEffectVelocity""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationMin"", true), ""TextFinished"", ""EditParticleEffectRotation""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationMax"", true), ""TextFinished"", ""EditParticleEffectRotation""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMin"", true), ""TextFinished"", ""EditParticleEffectRotationSpeed""); SubscribeToEvent(particleEffectWindow.GetChild(""RotationSpeedMax"", true), ""TextFinished"", ""EditParticleEffectRotationSpeed""); SubscribeToEvent(particleEffectWindow.GetChild(""SizeAdd"", true), ""TextFinished"", ""EditParticleEffectSizeAdd""); SubscribeToEvent(particleEffectWindow.GetChild(""SizeMultiply"", true), ""TextFinished"", ""EditParticleEffectSizeMultiply""); SubscribeToEvent(particleEffectWindow.GetChild(""AnimationLodBias"", true), ""TextFinished"", ""EditParticleEffectAnimationLodBias""); SubscribeToEvent(particleEffectWindow.GetChild(""NumParticles"", true), ""TextFinished"", ""EditParticleEffectNumParticles""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeX"", true), ""TextFinished"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeY"", true), ""TextFinished"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterSizeZ"", true), ""TextFinished"", ""EditParticleEffectEmitterSize""); SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMin"", true), ""TextFinished"", ""EditParticleEffectEmissionRate""); SubscribeToEvent(particleEffectWindow.GetChild(""EmissionRateMax"", true), ""TextFinished"", ""EditParticleEffectEmissionRate""); SubscribeToEvent(particleEffectWindow.GetChild(""EmitterShape"", true), ""ItemSelected"", ""EditParticleEffectEmitterShape""); SubscribeToEvent(particleEffectWindow.GetChild(""Scaled"", true), ""Toggled"", ""EditParticleEffectScaled""); SubscribeToEvent(particleEffectWindow.GetChild(""Sorted"", true), ""Toggled"", ""EditParticleEffectSorted""); SubscribeToEvent(particleEffectWindow.GetChild(""Relative"", true), ""Toggled"", ""EditParticleEffectRelative""); } void EditParticleEffectColorFrameNew(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); uint num = editParticleEffect.numColorFrames; editParticleEffect.numColorFrames = num + 1; RefreshParticleEffectColorFrames(); EndParticleEffectEdit(); } void EditParticleEffectTextureFrameNew(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); uint num = editParticleEffect.numTextureFrames; editParticleEffect.numTextureFrames = num + 1; RefreshParticleEffectTextureFrames(); EndParticleEffectEdit(); } void EditParticleEffectColorFrameRemove(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; ListView@ lv = particleEffectWindow.GetChild(""ColorFrameListView"", true); if (lv !is null && lv.selection != M_MAX_UNSIGNED ) { BeginParticleEffectEdit(); editParticleEffect.RemoveColorFrame(lv.selection); RefreshParticleEffectColorFrames(); EndParticleEffectEdit(); } } void EditParticleEffectTextureFrameRemove(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; ListView@ lv = particleEffectWindow.GetChild(""TextureFrameListView"", true); if (lv !is null && lv.selection != M_MAX_UNSIGNED ) { BeginParticleEffectEdit(); editParticleEffect.RemoveTextureFrame(lv.selection); RefreshParticleEffectTextureFrames(); EndParticleEffectEdit(); } } void EditParticleEffectColorFrameSort(StringHash eventType, VariantMap& eventData) { RefreshParticleEffectColorFrames(); } void EditParticleEffectTextureFrameSort(StringHash eventType, VariantMap& eventData) { RefreshParticleEffectTextureFrames(); } void InitParticleEffectBasicAttributes() { CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ConstantForceZ"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMinZ"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DirectionMaxZ"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""DampingForce"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ActiveTime"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""InactiveTime"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMinX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMinY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""TimeToLiveMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""TimeToLiveMax"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""VelocityMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""VelocityMax"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationMax"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationSpeedMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""RotationSpeedMax"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""SizeAdd"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""SizeMultiply"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""AnimationLodBias"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""NumParticles"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeX"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeY"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmitterSizeZ"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmissionRateMin"", true))); CreateDragSlider(cast(particleEffectWindow.GetChild(""EmissionRateMax"", true))); } void EditParticleEffectConstantForce(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); Vector3 v = editParticleEffect.constantForce; if (element.name == ""ConstantForceX"") editParticleEffect.constantForce = Vector3(element.text.ToFloat(), v.y, v.z); if (element.name == ""ConstantForceY"") editParticleEffect.constantForce = Vector3(v.x, element.text.ToFloat(), v.z); if (element.name == ""ConstantForceZ"") editParticleEffect.constantForce = Vector3(v.x, v.y, element.text.ToFloat()); EndParticleEffectEdit(); } void EditParticleEffectDirection(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); Vector3 vMin = editParticleEffect.minDirection; Vector3 vMax = editParticleEffect.maxDirection; if (element.name == ""DirectionMinX"") editParticleEffect.minDirection = Vector3(element.text.ToFloat(), vMin.y, vMin.z); if (element.name == ""DirectionMinY"") editParticleEffect.minDirection = Vector3(vMin.x, element.text.ToFloat(), vMin.z); if (element.name == ""DirectionMinZ"") editParticleEffect.minDirection = Vector3(vMin.x, vMin.y, element.text.ToFloat()); if (element.name == ""DirectionMaxX"") editParticleEffect.maxDirection = Vector3(element.text.ToFloat(), vMax.y, vMax.z); if (element.name == ""DirectionMaxY"") editParticleEffect.maxDirection = Vector3(vMax.x, element.text.ToFloat(), vMax.z); if (element.name == ""DirectionMaxZ"") editParticleEffect.maxDirection = Vector3(vMax.x, vMax.y, element.text.ToFloat()); EndParticleEffectEdit(); } void EditParticleEffectDampingForce(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.dampingForce = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectActiveTime(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.activeTime = element.text.ToFloat(); particleEffectEmitter.Reset(); EndParticleEffectEdit(); } void EditParticleEffectInactiveTime(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.inactiveTime = element.text.ToFloat(); particleEffectEmitter.Reset(); EndParticleEffectEdit(); } void EditParticleEffectParticleSize(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); Vector2 vMin = editParticleEffect.minParticleSize; Vector2 vMax = editParticleEffect.maxParticleSize; if (element.name == ""ParticleSizeMinX"") editParticleEffect.minParticleSize = Vector2(element.text.ToFloat(), vMin.y); if (element.name == ""ParticleSizeMinY"") editParticleEffect.minParticleSize = Vector2(vMin.x, element.text.ToFloat()); if (element.name == ""ParticleSizeMaxX"") editParticleEffect.maxParticleSize = Vector2(element.text.ToFloat(), vMax.y); if (element.name == ""ParticleSizeMaxY"") editParticleEffect.maxParticleSize = Vector2(vMax.x, element.text.ToFloat()); EndParticleEffectEdit(); } void EditParticleEffectTimeToLive(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); float vMin = editParticleEffect.minTimeToLive; float vMax = editParticleEffect.maxTimeToLive; if (element.name == ""TimeToLiveMin"") editParticleEffect.minTimeToLive = element.text.ToFloat(); if (element.name == ""TimeToLiveMax"") editParticleEffect.maxTimeToLive = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectVelocity(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); float vMin = editParticleEffect.minVelocity; float vMax = editParticleEffect.maxVelocity; if (element.name == ""VelocityMin"") editParticleEffect.minVelocity = element.text.ToFloat(); if (element.name == ""VelocityMax"") editParticleEffect.maxVelocity = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectRotation(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); float vMin = editParticleEffect.minRotation; float vMax = editParticleEffect.maxRotation; if (element.name == ""RotationMin"") editParticleEffect.minRotation = element.text.ToFloat(); if (element.name == ""RotationMax"") editParticleEffect.maxRotation = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectRotationSpeed(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); float vMin = editParticleEffect.minRotationSpeed; float vMax = editParticleEffect.maxRotationSpeed; if (element.name == ""RotationSpeedMin"") editParticleEffect.minRotationSpeed = element.text.ToFloat(); if (element.name == ""RotationSpeedMax"") editParticleEffect.maxRotationSpeed = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectSizeAdd(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.sizeAdd = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectSizeMultiply(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.sizeMul = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectAnimationLodBias(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.animationLodBias = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectNumParticles(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); editParticleEffect.numParticles = element.text.ToInt(); particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } void EditParticleEffectEmitterSize(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); Vector3 v = editParticleEffect.emitterSize; if (element.name == ""EmitterSizeX"") editParticleEffect.emitterSize = Vector3(element.text.ToFloat(), v.y, v.z); if (element.name == ""EmitterSizeY"") editParticleEffect.emitterSize = Vector3(v.x, element.text.ToFloat(), v.z); if (element.name == ""EmitterSizeZ"") editParticleEffect.emitterSize = Vector3(v.x, v.y, element.text.ToFloat()); EndParticleEffectEdit(); } void EditParticleEffectEmissionRate(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); if (element.name == ""EmissionRateMin"") editParticleEffect.minEmissionRate = element.text.ToFloat(); if (element.name == ""EmissionRateMax"") editParticleEffect.maxEmissionRate = element.text.ToFloat(); EndParticleEffectEdit(); } void EditParticleEffectEmitterShape(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; BeginParticleEffectEdit(); DropDownList@ element = eventData[""Element""].GetPtr(); switch (element.selection) { case 0: editParticleEffect.emitterType = EMITTER_BOX; break; case 1: editParticleEffect.emitterType = EMITTER_SPHERE; break; } EndParticleEffectEdit(); } void EditParticleEffectMaterial(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; LineEdit@ element = eventData[""Element""].GetPtr(); Material@ res = cache.GetResource(""Material"", element.text); if (res !is null) { BeginParticleEffectEdit(); editParticleEffect.material = res; particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } } void PickEditParticleEffectMaterial(StringHash eventType, VariantMap& eventData) { @resourcePicker = GetResourcePicker(StringHash(""Material"")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector(""Pick "" + resourcePicker.typeName, ""OK"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, ""FileSelected"", ""PickEditParticleEffectMaterialDone""); } void PickEditParticleEffectMaterialDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData[""OK""].GetBool()) { @resourcePicker = null; return; } String resourceName = eventData[""FileName""].GetString(); Resource@ res = GetPickedResource(resourceName); if (res !is null && editParticleEffect !is null && particleEffectEmitter !is null) { editParticleEffect.material = res; particleEffectEmitter.ApplyEffect(); RefreshParticleEffectMaterial(); } @resourcePicker = null; } void EditParticleEffectScaled(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); CheckBox@ element = eventData[""Element""].GetPtr(); editParticleEffect.scaled = element.checked; particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } void EditParticleEffectSorted(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); CheckBox@ element = eventData[""Element""].GetPtr(); editParticleEffect.sorted = element.checked; particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } void EditParticleEffectRelative(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); CheckBox@ element = eventData[""Element""].GetPtr(); editParticleEffect.relative = element.checked; particleEffectEmitter.ApplyEffect(); EndParticleEffectEdit(); } bool ShowParticleEffectEditor() { RefreshParticleEffectEditor(); particleEffectWindow.visible = true; particleEffectWindow.BringToFront(); return true; } void HideParticleEffectEditor() { if (particleEffectWindow !is null) particleEffectWindow.visible = false; } void InitParticleEffectPreview() { particlePreviewScene = Scene(""particlePreviewScene""); particlePreviewScene.CreateComponent(""Octree""); Node@ zoneNode = particlePreviewScene.CreateChild(""Zone""); Zone@ zone = zoneNode.CreateComponent(""Zone""); zone.boundingBox = BoundingBox(-1000, 1000); zone.ambientColor = Color(0.15, 0.15, 0.15); zone.fogColor = Color(0, 0, 0); zone.fogStart = 10.0; zone.fogEnd = 100.0; particlePreviewCameraNode = particlePreviewScene.CreateChild(""PreviewCamera""); particlePreviewCameraNode.position = Vector3(0, 0, -2.5); Camera@ camera = particlePreviewCameraNode.CreateComponent(""Camera""); camera.nearClip = 0.1f; camera.farClip = 100.0f; particlePreviewLightNode = particlePreviewScene.CreateChild(""particlePreviewLight""); particlePreviewLightNode.direction = Vector3(0.5, -0.5, 0.5); particlePreviewLight = particlePreviewLightNode.CreateComponent(""Light""); particlePreviewLight.lightType = LIGHT_DIRECTIONAL; particlePreviewLight.specularIntensity = 0.5; particleEffectPreviewNode = particlePreviewScene.CreateChild(""PreviewEmitter""); particleEffectPreviewNode.rotation = Quaternion(0, 0, 0); StaticModel@ gizmo = particleEffectPreviewNode.CreateComponent(""StaticModel""); gizmo.model = cache.GetResource(""Model"", ""Models/Editor/Axes.mdl""); gizmo.materials[0] = cache.GetResource(""Material"", ""Materials/Editor/RedUnlit.xml""); gizmo.materials[1] = cache.GetResource(""Material"", ""Materials/Editor/GreenUnlit.xml""); gizmo.materials[2] = cache.GetResource(""Material"", ""Materials/Editor/BlueUnlit.xml""); gizmo.occludee = false; particleEffectEmitter = particleEffectPreviewNode.CreateComponent(""ParticleEmitter""); editParticleEffect = CreateNewParticleEffect(); particleEffectEmitter.effect = editParticleEffect; particleEffectPreview = particleEffectWindow.GetChild(""ParticleEffectPreview"", true); particleEffectPreview.SetFixedHeight(100); particleEffectPreview.SetView(particlePreviewScene, camera); SubscribeToEvent(particleEffectPreview, ""DragMove"", ""RotateParticleEffectPreview""); } ParticleEffect@ CreateNewParticleEffect() { ParticleEffect@ effect = ParticleEffect(); Material@ res = cache.GetResource(""Material"", ""Materials/Particle.xml""); if (res is null) log.Error(""Could not load default material for new particle effect.""); effect.material = res; effect.AddColorTime(Color(1,1,1,1), 0.0f); return effect; } void EditParticleEffect(ParticleEffect@ effect) { if (effect is null) return; if (editParticleEffect !is null) UnsubscribeFromEvent(editParticleEffect, ""ReloadFinished""); if (!effect.name.empty) cache.ReloadResource(effect); editParticleEffect = effect; particleEffectEmitter.effect = editParticleEffect; if (editParticleEffect !is null) SubscribeToEvent(editParticleEffect, ""ReloadFinished"", ""RefreshParticleEffectEditor""); ShowParticleEffectEditor(); } void RefreshParticleEffectEditor() { inParticleEffectRefresh = true; RefreshParticleEffectPreview(); RefreshParticleEffectName(); RefreshParticleEffectBasicAttributes(); RefreshParticleEffectMaterial(); RefreshParticleEffectColorFrames(); RefreshParticleEffectTextureFrames(); inParticleEffectRefresh = false; } void RefreshParticleEffectColorFrames() { if (editParticleEffect is null) return; editParticleEffect.SortColorFrames(); ListView@ lv = particleEffectWindow.GetChild(""ColorFrameListView"", true); if (lv is null) return; lv.RemoveAllItems(); for (uint i = 0; i < editParticleEffect.numColorFrames; i++) { ColorFrame@ colorFrame = editParticleEffect.GetColorFrame(i); Button@ container = Button(); lv.AddItem(container); container.style = ""Button""; container.imageRect = IntRect(18, 2, 30, 14); container.minSize = IntVector2(0, 20); container.maxSize = IntVector2(2147483647, 20); container.layoutMode = LM_HORIZONTAL; container.layoutBorder = IntRect(3,1,3,1); container.layoutSpacing = 4; UIElement@ labelContainer = UIElement(); container.AddChild(labelContainer); labelContainer.style = ""HorizontalPanel""; labelContainer.minSize = IntVector2(0, 16); labelContainer.maxSize = IntVector2(2147483647, 16); labelContainer.verticalAlignment = VA_CENTER; { LineEdit@ le = LineEdit(); labelContainer.AddChild(le); le.name = ""ColorTime""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.minSize = IntVector2(0, 16); le.maxSize = IntVector2(40, 16); le.text = colorFrame.time; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } UIElement@ textContainer = UIElement(); labelContainer.AddChild(textContainer); textContainer.minSize = IntVector2(0, 16); textContainer.maxSize = IntVector2(2147483647, 16); textContainer.verticalAlignment = VA_CENTER; Text@ t = Text(); textContainer.AddChild(t); t.style = ""Text""; t.text = ""Color""; UIElement@ editContainer = UIElement(); container.AddChild(editContainer); editContainer.style = ""HorizontalPanel""; editContainer.minSize = IntVector2(0, 16); editContainer.maxSize = IntVector2(2147483647, 16); editContainer.verticalAlignment = VA_CENTER; { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""ColorR""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.text = colorFrame.color.r; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""ColorG""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.text = colorFrame.color.g; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""ColorB""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.text = colorFrame.color.b; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""ColorA""; le.vars[""ColorFrame""] = i; le.style = ""LineEdit""; le.text = colorFrame.color.a; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectColorFrame""); } } } void RefreshParticleEffectTextureFrames() { if (editParticleEffect is null) return; editParticleEffect.SortTextureFrames(); ListView@ lv = particleEffectWindow.GetChild(""TextureFrameListView"", true); if (lv is null) return; lv.RemoveAllItems(); for (uint i = 0; i < editParticleEffect.numTextureFrames; i++) { TextureFrame@ textureFrame = editParticleEffect.GetTextureFrame(i); if (textureFrame is null) continue; Button@ container = Button(); lv.AddItem(container); container.style = ""Button""; container.imageRect = IntRect(18, 2, 30, 14); container.minSize = IntVector2(0, 20); container.maxSize = IntVector2(2147483647, 20); container.layoutMode = LM_HORIZONTAL; container.layoutBorder = IntRect(1,1,1,1); container.layoutSpacing = 4; UIElement@ labelContainer = UIElement(); container.AddChild(labelContainer); labelContainer.style = ""HorizontalPanel""; labelContainer.minSize = IntVector2(0, 16); labelContainer.maxSize = IntVector2(2147483647, 16); labelContainer.verticalAlignment = VA_CENTER; { LineEdit@ le = LineEdit(); labelContainer.AddChild(le); le.name = ""TextureTime""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.minSize = IntVector2(0, 16); le.maxSize = IntVector2(40, 16); le.text = textureFrame.time; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } UIElement@ textContainer = UIElement(); labelContainer.AddChild(textContainer); textContainer.minSize = IntVector2(0, 16); textContainer.maxSize = IntVector2(2147483647, 16); textContainer.verticalAlignment = VA_CENTER; Text@ t = Text(); textContainer.AddChild(t); t.style = ""Text""; t.text = ""Texture""; UIElement@ editContainer = UIElement(); container.AddChild(editContainer); editContainer.style = ""HorizontalPanel""; editContainer.minSize = IntVector2(0, 16); editContainer.maxSize = IntVector2(2147483647, 16); editContainer.verticalAlignment = VA_CENTER; { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""TextureMinX""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.text = textureFrame.uv.min.x; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""TextureMinY""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.text = textureFrame.uv.min.y; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""TextureMaxX""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.text = textureFrame.uv.max.x; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } { LineEdit@ le = LineEdit(); editContainer.AddChild(le); le.name = ""TextureMaxY""; le.vars[""TextureFrame""] = i; le.style = ""LineEdit""; le.text = textureFrame.uv.max.y; le.cursorPosition = 0; CreateDragSlider(le); SubscribeToEvent(le, ""TextChanged"", ""EditParticleEffectTextureFrame""); } } } void EditParticleEffectColorFrame(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); uint i = element.vars[""ColorFrame""].GetInt(); ColorFrame@ cf = editParticleEffect.GetColorFrame(i); if (element.name == ""ColorTime"") cf.time = element.text.ToFloat(); if (element.name == ""ColorR"") cf.color = Color(element.text.ToFloat(), cf.color.g, cf.color.b, cf.color.a); if (element.name == ""ColorG"") cf.color = Color(cf.color.r, element.text.ToFloat(), cf.color.b, cf.color.a); if (element.name == ""ColorB"") cf.color = Color(cf.color.r, cf.color.g, element.text.ToFloat(), cf.color.a); if (element.name == ""ColorA"") cf.color = Color(cf.color.r, cf.color.g, cf.color.b, element.text.ToFloat()); editParticleEffect.SetColorFrame(i, cf); particleEffectEmitter.Reset(); EndParticleEffectEdit(); } void EditParticleEffectTextureFrame(StringHash eventType, VariantMap& eventData) { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (particleEffectEmitter is null) return; BeginParticleEffectEdit(); LineEdit@ element = eventData[""Element""].GetPtr(); uint i = element.vars[""TextureFrame""].GetInt(); TextureFrame@ tf = editParticleEffect.GetTextureFrame(i); if (element.name == ""TextureTime"") tf.time = element.text.ToFloat(); if (element.name == ""TextureMinX"") tf.uv = Rect(element.text.ToFloat(), tf.uv.min.y, tf.uv.max.x, tf.uv.max.y); if (element.name == ""TextureMinY"") tf.uv = Rect(tf.uv.min.x, element.text.ToFloat(), tf.uv.max.x, tf.uv.max.y); if (element.name == ""TextureMaxX"") tf.uv = Rect(tf.uv.min.x, tf.uv.min.y, element.text.ToFloat(), tf.uv.max.y); if (element.name == ""TextureMaxY"") tf.uv = Rect(tf.uv.min.x, tf.uv.min.y, tf.uv.max.x, element.text.ToFloat()); editParticleEffect.SetTextureFrame(i, tf); particleEffectEmitter.Reset(); EndParticleEffectEdit(); } void RefreshParticleEffectPreview() { if (particleEffectEmitter is null || editParticleEffect is null) return; particleEffectEmitter.effect = editParticleEffect; particleEffectEmitter.Reset(); particleEffectPreview.QueueUpdate(); } void RefreshParticleEffectName() { UIElement@ container = particleEffectWindow.GetChild(""NameContainer"", true); if (container is null) return; container.RemoveAllChildren(); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, 0, 0); if (editParticleEffect !is null) nameEdit.text = editParticleEffect.name; SubscribeToEvent(nameEdit, ""TextFinished"", ""EditParticleEffectName""); Button@ pickButton = CreateResourcePickerButton(container, null, 0, 0, ""Pick""); SubscribeToEvent(pickButton, ""Released"", ""PickEditParticleEffect""); } void RefreshParticleEffectBasicAttributes() { if (editParticleEffect is null) return; cast(particleEffectWindow.GetChild(""ConstantForceX"", true)).text = editParticleEffect.constantForce.x; cast(particleEffectWindow.GetChild(""ConstantForceY"", true)).text = editParticleEffect.constantForce.y; cast(particleEffectWindow.GetChild(""ConstantForceZ"", true)).text = editParticleEffect.constantForce.z; cast(particleEffectWindow.GetChild(""DirectionMinX"", true)).text = editParticleEffect.minDirection.x; cast(particleEffectWindow.GetChild(""DirectionMinY"", true)).text = editParticleEffect.minDirection.y; cast(particleEffectWindow.GetChild(""DirectionMinZ"", true)).text = editParticleEffect.minDirection.z; cast(particleEffectWindow.GetChild(""DirectionMaxX"", true)).text = editParticleEffect.maxDirection.x; cast(particleEffectWindow.GetChild(""DirectionMaxY"", true)).text = editParticleEffect.maxDirection.y; cast(particleEffectWindow.GetChild(""DirectionMaxZ"", true)).text = editParticleEffect.maxDirection.z; cast(particleEffectWindow.GetChild(""DampingForce"", true)).text = editParticleEffect.dampingForce; cast(particleEffectWindow.GetChild(""ActiveTime"", true)).text = editParticleEffect.activeTime; cast(particleEffectWindow.GetChild(""InactiveTime"", true)).text = editParticleEffect.inactiveTime; cast(particleEffectWindow.GetChild(""ParticleSizeMinX"", true)).text = editParticleEffect.minParticleSize.x; cast(particleEffectWindow.GetChild(""ParticleSizeMinY"", true)).text = editParticleEffect.minParticleSize.y; cast(particleEffectWindow.GetChild(""ParticleSizeMaxX"", true)).text = editParticleEffect.maxParticleSize.x; cast(particleEffectWindow.GetChild(""ParticleSizeMaxY"", true)).text = editParticleEffect.maxParticleSize.y; cast(particleEffectWindow.GetChild(""TimeToLiveMin"", true)).text = editParticleEffect.minTimeToLive; cast(particleEffectWindow.GetChild(""TimeToLiveMax"", true)).text = editParticleEffect.maxTimeToLive; cast(particleEffectWindow.GetChild(""VelocityMin"", true)).text = editParticleEffect.minVelocity; cast(particleEffectWindow.GetChild(""VelocityMax"", true)).text = editParticleEffect.maxVelocity; cast(particleEffectWindow.GetChild(""RotationMin"", true)).text = editParticleEffect.minRotation; cast(particleEffectWindow.GetChild(""RotationMax"", true)).text = editParticleEffect.maxRotation; cast(particleEffectWindow.GetChild(""RotationSpeedMin"", true)).text = editParticleEffect.minRotationSpeed; cast(particleEffectWindow.GetChild(""RotationSpeedMax"", true)).text = editParticleEffect.maxRotationSpeed; cast(particleEffectWindow.GetChild(""SizeAdd"", true)).text = editParticleEffect.sizeAdd; cast(particleEffectWindow.GetChild(""SizeMultiply"", true)).text = editParticleEffect.sizeMul; cast(particleEffectWindow.GetChild(""AnimationLodBias"", true)).text = editParticleEffect.animationLodBias; cast(particleEffectWindow.GetChild(""NumParticles"", true)).text = editParticleEffect.numParticles; cast(particleEffectWindow.GetChild(""EmitterSizeX"", true)).text = editParticleEffect.emitterSize.x; cast(particleEffectWindow.GetChild(""EmitterSizeY"", true)).text = editParticleEffect.emitterSize.y; cast(particleEffectWindow.GetChild(""EmitterSizeZ"", true)).text = editParticleEffect.emitterSize.z; cast(particleEffectWindow.GetChild(""EmissionRateMin"", true)).text = editParticleEffect.minEmissionRate; cast(particleEffectWindow.GetChild(""EmissionRateMax"", true)).text = editParticleEffect.maxEmissionRate; switch (editParticleEffect.emitterType) { case EMITTER_BOX: cast(particleEffectWindow.GetChild(""EmitterShape"", true)).selection = 0; break; case EMITTER_SPHERE: cast(particleEffectWindow.GetChild(""EmitterShape"", true)).selection = 1; break; } cast(particleEffectWindow.GetChild(""Scaled"", true)).checked = editParticleEffect.scaled; cast(particleEffectWindow.GetChild(""Sorted"", true)).checked = editParticleEffect.sorted; cast(particleEffectWindow.GetChild(""Relative"", true)).checked = editParticleEffect.relative; } void RefreshParticleEffectMaterial() { UIElement@ container = particleEffectWindow.GetChild(""ParticleMaterialContainer"", true); if (container is null) return; container.RemoveAllChildren(); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, 0, 0); if (editParticleEffect !is null) { if (editParticleEffect.material !is null) nameEdit.text = editParticleEffect.material.name; else { nameEdit.text = ""Materials/Particle.xml""; Material@ res = cache.GetResource(""Material"", ""Materials/Particle.xml""); if (res !is null) editParticleEffect.material = res; } } SubscribeToEvent(nameEdit, ""TextFinished"", ""EditParticleEffectMaterial""); Button@ pickButton = CreateResourcePickerButton(container, null, 0, 0, ""Pick""); SubscribeToEvent(pickButton, ""Released"", ""PickEditParticleEffectMaterial""); } void RotateParticleEffectPreview(StringHash eventType, VariantMap& eventData) { int elemX = eventData[""ElementX""].GetInt(); int elemY = eventData[""ElementY""].GetInt(); if (particleEffectPreview.height > 0 && particleEffectPreview.width > 0) { float yaw = ((particleEffectPreview.height / 2) - elemY) * (90.0 / particleEffectPreview.height); float pitch = ((particleEffectPreview.width / 2) - elemX) * (90.0 / particleEffectPreview.width); particleEffectPreviewNode.rotation = particleEffectPreviewNode.rotation.Slerp(Quaternion(yaw, pitch, 0), 0.1); particleEffectPreview.QueueUpdate(); } } void EditParticleEffectName(StringHash eventType, VariantMap& eventData) { LineEdit@ nameEdit = eventData[""Element""].GetPtr(); String newParticleEffectName = nameEdit.text.Trimmed(); if (!newParticleEffectName.empty && !(editParticleEffect !is null && newParticleEffectName == editParticleEffect.name)) { ParticleEffect@ newParticleEffect = cache.GetResource(""ParticleEffect"", newParticleEffectName); if (newParticleEffect !is null) EditParticleEffect(newParticleEffect); } } void PickEditParticleEffect() { @resourcePicker = GetResourcePicker(StringHash(""ParticleEffect"")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector(""Pick "" + resourcePicker.typeName, ""OK"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, ""FileSelected"", ""PickEditParticleEffectDone""); } void PickEditParticleEffectDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData[""OK""].GetBool()) { @resourcePicker = null; return; } String resourceName = eventData[""FileName""].GetString(); Resource@ res = GetPickedResource(resourceName); if (res !is null) EditParticleEffect(cast(res)); @resourcePicker = null; } void NewParticleEffect() { BeginParticleEffectEdit(); EditParticleEffect(CreateNewParticleEffect()); EndParticleEffectEdit(); } void RevertParticleEffect() { if (inParticleEffectRefresh) return; if (editParticleEffect is null) return; if (editParticleEffect.name.empty) { NewParticleEffect(); return; } BeginParticleEffectEdit(); cache.ReloadResource(editParticleEffect); EndParticleEffectEdit(); RefreshParticleEffectEditor(); } void SaveParticleEffect() { if (editParticleEffect is null || editParticleEffect.name.empty) return; String fullName = cache.GetResourceFileName(editParticleEffect.name); if (fullName.empty) return; File saveFile(fullName, FILE_WRITE); editParticleEffect.Save(saveFile); } void SaveParticleEffectAs() { if (editParticleEffect is null) return; @resourcePicker = GetResourcePicker(StringHash(""ParticleEffect"")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector(""Save material as"", ""Save"", ""Cancel"", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, ""FileSelected"", ""SaveParticleEffectAsDone""); } void SaveParticleEffectAsDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); @resourcePicker = null; if (editParticleEffect is null) return; if (!eventData[""OK""].GetBool()) { @resourcePicker = null; return; } String fullName = eventData[""FileName""].GetString(); // Add default extension for saving if not specified String filter = eventData[""Filter""].GetString(); if (GetExtension(fullName).empty && filter != ""*.*"") fullName = fullName + filter.Substring(1); File saveFile(fullName, FILE_WRITE); if (editParticleEffect.Save(saveFile)) { saveFile.Close(); // Load the new resource to update the name in the editor ParticleEffect@ newEffect = cache.GetResource(""ParticleEffect"", GetResourceNameFromFullName(fullName)); if (newEffect !is null) EditParticleEffect(newEffect); } } void BeginParticleEffectEdit() { if (editParticleEffect is null) return; inParticleEffectRefresh = true; oldParticleEffectState = XMLFile(); XMLElement particleElem = oldParticleEffectState.CreateRoot(""particleeffect""); editParticleEffect.Save(particleElem); } void EndParticleEffectEdit() { if (editParticleEffect is null) return; if (!dragEditAttribute) { EditParticleEffectAction@ action = EditParticleEffectAction(); action.Define(particleEffectEmitter, editParticleEffect, oldParticleEffectState); SaveEditAction(action); } inParticleEffectRefresh = false; particleEffectPreview.QueueUpdate(); } ",12061,False,2339.537508633485,median "UIElement@ browserWindow; Window@ browserFilterWindow; ListView@ browserDirList; ListView@ browserFileList; LineEdit@ browserSearch; BrowserFile@ browserDragFile; Node@ browserDragNode; Component@ browserDragComponent; View3D@ resourceBrowserPreview; Scene@ resourcePreviewScene; Node@ resourcePreviewNode; Node@ resourcePreviewCameraNode; Node@ resourcePreviewLightNode; Light@ resourcePreviewLight; int browserSearchSortMode = 0; BrowserDir@ rootDir; Array browserFiles; Dictionary browserDirs; Array activeResourceTypeFilters; Array activeResourceDirFilters; Array browserFilesToScan; const uint BROWSER_WORKER_ITEMS_PER_TICK = 10; const uint BROWSER_SEARCH_LIMIT = 50; const int BROWSER_SORT_MODE_ALPHA = 1; const int BROWSER_SORT_MODE_SEARCH = 2; const int RESOURCE_TYPE_UNUSABLE = -2; const int RESOURCE_TYPE_UNKNOWN = -1; const int RESOURCE_TYPE_NOTSET = 0; const int RESOURCE_TYPE_SCENE = 1; const int RESOURCE_TYPE_SCRIPTFILE = 2; const int RESOURCE_TYPE_MODEL = 3; const int RESOURCE_TYPE_MATERIAL = 4; const int RESOURCE_TYPE_ANIMATION = 5; const int RESOURCE_TYPE_IMAGE = 6; const int RESOURCE_TYPE_SOUND = 7; const int RESOURCE_TYPE_TEXTURE = 8; const int RESOURCE_TYPE_FONT = 9; const int RESOURCE_TYPE_PREFAB = 10; const int RESOURCE_TYPE_TECHNIQUE = 11; const int RESOURCE_TYPE_PARTICLEEFFECT = 12; const int RESOURCE_TYPE_UIELEMENT = 13; const int RESOURCE_TYPE_UIELEMENTS = 14; const int RESOURCE_TYPE_ANIMATION_SETTINGS = 15; const int RESOURCE_TYPE_RENDERPATH = 16; const int RESOURCE_TYPE_TEXTURE_ATLAS = 17; const int RESOURCE_TYPE_2D_PARTICLE_EFFECT = 18; const int RESOURCE_TYPE_TEXTURE_3D = 19; const int RESOURCE_TYPE_CUBEMAP = 20; const int RESOURCE_TYPE_PARTICLEEMITTER = 21; const int RESOURCE_TYPE_2D_ANIMATION_SET = 22; // any resource type > 0 is valid const int NUMBER_OF_VALID_RESOURCE_TYPES = 22; const StringHash XML_TYPE_SCENE(""scene""); const StringHash XML_TYPE_NODE(""node""); const StringHash XML_TYPE_MATERIAL(""material""); const StringHash XML_TYPE_TECHNIQUE(""technique""); const StringHash XML_TYPE_PARTICLEEFFECT(""particleeffect""); const StringHash XML_TYPE_PARTICLEEMITTER(""particleemitter""); const StringHash XML_TYPE_TEXTURE(""texture""); const StringHash XML_TYPE_ELEMENT(""element""); const StringHash XML_TYPE_ELEMENTS(""elements""); const StringHash XML_TYPE_ANIMATION_SETTINGS(""animation""); const StringHash XML_TYPE_RENDERPATH(""renderpath""); const StringHash XML_TYPE_TEXTURE_ATLAS(""TextureAtlas""); const StringHash XML_TYPE_2D_PARTICLE_EFFECT(""particleEmitterConfig""); const StringHash XML_TYPE_TEXTURE_3D(""texture3d""); const StringHash XML_TYPE_CUBEMAP(""cubemap""); const StringHash XML_TYPE_SPRITER_DATA(""spriter_data""); const StringHash JSON_TYPE_SCENE(""scene""); const StringHash JSON_TYPE_NODE(""node""); const StringHash JSON_TYPE_MATERIAL(""material""); const StringHash JSON_TYPE_TECHNIQUE(""technique""); const StringHash JSON_TYPE_PARTICLEEFFECT(""particleeffect""); const StringHash JSON_TYPE_PARTICLEEMITTER(""particleemitter""); const StringHash JSON_TYPE_TEXTURE(""texture""); const StringHash JSON_TYPE_ELEMENT(""element""); const StringHash JSON_TYPE_ELEMENTS(""elements""); const StringHash JSON_TYPE_ANIMATION_SETTINGS(""animation""); const StringHash JSON_TYPE_RENDERPATH(""renderpath""); const StringHash JSON_TYPE_TEXTURE_ATLAS(""TextureAtlas""); const StringHash JSON_TYPE_2D_PARTICLE_EFFECT(""particleEmitterConfig""); const StringHash JSON_TYPE_TEXTURE_3D(""texture3d""); const StringHash JSON_TYPE_CUBEMAP(""cubemap""); const StringHash JSON_TYPE_SPRITER_DATA(""spriter_data""); const StringHash BINARY_TYPE_SCENE(""USCN""); const StringHash BINARY_TYPE_PACKAGE(""UPAK""); const StringHash BINARY_TYPE_COMPRESSED_PACKAGE(""ULZ4""); const StringHash BINARY_TYPE_ANGLESCRIPT(""ASBC""); const StringHash BINARY_TYPE_MODEL(""UMDL""); const StringHash BINARY_TYPE_SHADER(""USHD""); const StringHash BINARY_TYPE_ANIMATION(""UANI""); const StringHash EXTENSION_TYPE_TTF("".ttf""); const StringHash EXTENSION_TYPE_OTF("".otf""); const StringHash EXTENSION_TYPE_OGG("".ogg""); const StringHash EXTENSION_TYPE_WAV("".wav""); const StringHash EXTENSION_TYPE_DDS("".dds""); const StringHash EXTENSION_TYPE_PNG("".png""); const StringHash EXTENSION_TYPE_JPG("".jpg""); const StringHash EXTENSION_TYPE_JPEG("".jpeg""); const StringHash EXTENSION_TYPE_BMP("".bmp""); const StringHash EXTENSION_TYPE_TGA("".tga""); const StringHash EXTENSION_TYPE_KTX("".ktx""); const StringHash EXTENSION_TYPE_PVR("".pvr""); const StringHash EXTENSION_TYPE_OBJ("".obj""); const StringHash EXTENSION_TYPE_FBX("".fbx""); const StringHash EXTENSION_TYPE_COLLADA("".dae""); const StringHash EXTENSION_TYPE_BLEND("".blend""); const StringHash EXTENSION_TYPE_ANGELSCRIPT("".as""); const StringHash EXTENSION_TYPE_LUASCRIPT("".lua""); const StringHash EXTENSION_TYPE_HLSL("".hlsl""); const StringHash EXTENSION_TYPE_GLSL("".glsl""); const StringHash EXTENSION_TYPE_FRAGMENTSHADER("".frag""); const StringHash EXTENSION_TYPE_VERTEXSHADER("".vert""); const StringHash EXTENSION_TYPE_HTML("".html""); const StringHash TEXT_VAR_FILE_ID(""browser_file_id""); const StringHash TEXT_VAR_DIR_ID(""browser_dir_id""); const StringHash TEXT_VAR_RESOURCE_TYPE(""resource_type""); const StringHash TEXT_VAR_RESOURCE_DIR_ID(""resource_dir_id""); const int BROWSER_FILE_SOURCE_RESOURCE_DIR = 1; uint browserDirIndex = 1; uint browserFileIndex = 1; BrowserDir@ selectedBrowserDirectory; BrowserFile@ selectedBrowserFile; Text@ browserStatusMessage; Text@ browserResultsMessage; bool ignoreRefreshBrowserResults = false; String resourceDirsCache; void CreateResourceBrowser() { if (browserWindow !is null) return; CreateResourceBrowserUI(); InitResourceBrowserPreview(); RebuildResourceDatabase(); } void RebuildResourceDatabase() { if (browserWindow is null) return; String newResourceDirsCache = Join(cache.resourceDirs, ';'); ScanResourceDirectories(); if (newResourceDirsCache != resourceDirsCache) { resourceDirsCache = newResourceDirsCache; PopulateResourceDirFilters(); } PopulateBrowserDirectories(); PopulateResourceBrowserFilesByDirectory(rootDir); } void ScanResourceDirectories() { browserDirs.Clear(); browserFiles.Clear(); browserFilesToScan.Clear(); rootDir = BrowserDir(""""); browserDirs.Set("""", @rootDir); // collect all of the items and sort them afterwards for(uint i=0; i < cache.resourceDirs.length; ++i) { if (activeResourceDirFilters.Find(i) > -1) continue; ScanResourceDir(i); } } // used to stop ui from blocking while determining file types void DoResourceBrowserWork() { if (browserFilesToScan.length == 0) return; int counter = 0; bool updateBrowserUI = false; BrowserFile@ scanItem = browserFilesToScan[0]; while(counter < BROWSER_WORKER_ITEMS_PER_TICK) { scanItem.DetermainResourceType(); // next browserFilesToScan.Erase(0); if (browserFilesToScan.length > 0) @scanItem = browserFilesToScan[0]; else break; counter++; } if (browserFilesToScan.length > 0) browserStatusMessage.text = localization.Get(""Files left to scan: "" )+ browserFilesToScan.length; else browserStatusMessage.text = localization.Get(""Scan complete""); } void CreateResourceBrowserUI() { browserWindow = LoadEditorUI(""UI/EditorResourceBrowser.xml""); browserDirList = browserWindow.GetChild(""DirectoryList"", true); browserFileList = browserWindow.GetChild(""FileList"", true); browserSearch = browserWindow.GetChild(""Search"", true); browserStatusMessage = browserWindow.GetChild(""StatusMessage"", true); browserResultsMessage = browserWindow.GetChild(""ResultsMessage"", true); // browserWindow.visible = false; browserWindow.opacity = uiMaxOpacity; browserFilterWindow = LoadEditorUI(""UI/EditorResourceFilterWindow.xml""); CreateResourceFilterUI(); HideResourceFilterWindow(); int height = Min(ui.root.height / 4, 300); browserWindow.SetSize(900, height); browserWindow.SetPosition(35, ui.root.height - height - 25); CloseContextMenu(); ui.root.AddChild(browserWindow); ui.root.AddChild(browserFilterWindow); SubscribeToEvent(browserWindow.GetChild(""CloseButton"", true), ""Released"", ""HideResourceBrowserWindow""); SubscribeToEvent(browserWindow.GetChild(""RescanButton"", true), ""Released"", ""HandleRescanResourceBrowserClick""); SubscribeToEvent(browserWindow.GetChild(""FilterButton"", true), ""Released"", ""ToggleResourceFilterWindow""); SubscribeToEvent(browserDirList, ""SelectionChanged"", ""HandleResourceBrowserDirListSelectionChange""); SubscribeToEvent(browserSearch, ""TextChanged"", ""HandleResourceBrowserSearchTextChange""); SubscribeToEvent(browserFileList, ""ItemClicked"", ""HandleBrowserFileClick""); SubscribeToEvent(browserFileList, ""SelectionChanged"", ""HandleResourceBrowserFileListSelectionChange""); SubscribeToEvent(cache, ""FileChanged"", ""HandleFileChanged""); } void CreateResourceFilterUI() { UIElement@ options = browserFilterWindow.GetChild(""TypeOptions"", true); CheckBox@ toggleAllTypes = browserFilterWindow.GetChild(""ToggleAllTypes"", true); CheckBox@ toggleAllResourceDirs = browserFilterWindow.GetChild(""ToggleAllResourceDirs"", true); SubscribeToEvent(toggleAllTypes, ""Toggled"", ""HandleResourceTypeFilterToggleAllTypesToggled""); SubscribeToEvent(toggleAllResourceDirs, ""Toggled"", ""HandleResourceDirFilterToggleAllTypesToggled""); SubscribeToEvent(browserFilterWindow.GetChild(""CloseButton"", true), ""Released"", ""HideResourceFilterWindow""); int columns = 2; UIElement@ col1 = browserFilterWindow.GetChild(""TypeFilterColumn1"", true); UIElement@ col2 = browserFilterWindow.GetChild(""TypeFilterColumn2"", true); // use array to get sort of items Array sorted; for (int i=1; i <= NUMBER_OF_VALID_RESOURCE_TYPES; ++i) sorted.Push(ResourceType(i, ResourceTypeName(i))); // 2 unknown types are reserved for the top, the rest are alphabetized sorted.Sort(); sorted.Insert(0, ResourceType(RESOURCE_TYPE_UNKNOWN, ResourceTypeName(RESOURCE_TYPE_UNKNOWN)) ); sorted.Insert(0, ResourceType(RESOURCE_TYPE_UNUSABLE, ResourceTypeName(RESOURCE_TYPE_UNUSABLE)) ); int halfColumns = Ceil( float(sorted.length) / float(columns) ); for (uint i = 0; i < sorted.length; ++i) { ResourceType@ type = sorted[i]; UIElement@ resourceTypeHolder = UIElement(); if (i < halfColumns) col1.AddChild(resourceTypeHolder); else col2.AddChild(resourceTypeHolder); resourceTypeHolder.layoutMode = LM_HORIZONTAL; resourceTypeHolder.layoutSpacing = 4; Text@ label = Text(); label.style = ""EditorAttributeText""; label.text = type.name; CheckBox@ checkbox = CheckBox(); checkbox.name = type.id; checkbox.SetStyleAuto(); checkbox.vars[TEXT_VAR_RESOURCE_TYPE] = i; checkbox.checked = true; SubscribeToEvent(checkbox, ""Toggled"", ""HandleResourceTypeFilterToggled""); resourceTypeHolder.AddChild(checkbox); resourceTypeHolder.AddChild(label); } } void CreateDirList(BrowserDir@ dir, UIElement@ parentUI = null) { Text@ dirText = Text(); browserDirList.InsertItem(browserDirList.numItems, dirText, parentUI); dirText.style = ""FileSelectorListText""; dirText.text = dir.resourceKey.empty ? localization.Get(""Root"") : dir.name; dirText.name = dir.resourceKey; dirText.vars[TEXT_VAR_DIR_ID] = dir.resourceKey; // Sort directories alphetically browserSearchSortMode = BROWSER_SORT_MODE_ALPHA; dir.children.Sort(); for(uint i=0; i 0) fileText.dragDropMode = DD_SOURCE; { Text@ text = Text(); fileText.AddChild(text); text.style = ""FileSelectorListText""; text.text = file.fullname; text.name = file.resourceKey; } { Text@ text = Text(); fileText.AddChild(text); text.style = ""FileSelectorListText""; text.text = file.ResourceTypeName(); } if (file.resourceType == RESOURCE_TYPE_MATERIAL || file.resourceType == RESOURCE_TYPE_MODEL || file.resourceType == RESOURCE_TYPE_PARTICLEEFFECT || file.resourceType == RESOURCE_TYPE_PREFAB ) { SubscribeToEvent(fileText, ""DragBegin"", ""HandleBrowserFileDragBegin""); SubscribeToEvent(fileText, ""DragEnd"", ""HandleBrowserFileDragEnd""); } } void InitResourceBrowserPreview() { resourcePreviewScene = Scene(""PreviewScene""); resourcePreviewScene.CreateComponent(""Octree""); PhysicsWorld@ physicsWorld = resourcePreviewScene.CreateComponent(""PhysicsWorld""); physicsWorld.enabled = false; physicsWorld.gravity = Vector3(0.0, 0.0, 0.0); Node@ zoneNode = resourcePreviewScene.CreateChild(""Zone""); Zone@ zone = zoneNode.CreateComponent(""Zone""); zone.boundingBox = BoundingBox(-1000, 1000); zone.ambientColor = Color(0.15, 0.15, 0.15); zone.fogColor = Color(0, 0, 0); zone.fogStart = 10.0; zone.fogEnd = 100.0; resourcePreviewCameraNode = resourcePreviewScene.CreateChild(""PreviewCamera""); resourcePreviewCameraNode.position = Vector3(0, 0, -1.5); Camera@ camera = resourcePreviewCameraNode.CreateComponent(""Camera""); camera.nearClip = 0.1f; camera.farClip = 100.0f; resourcePreviewLightNode = resourcePreviewScene.CreateChild(""PreviewLight""); resourcePreviewLightNode.direction = Vector3(0.5, -0.5, 0.5); resourcePreviewLight = resourcePreviewLightNode.CreateComponent(""Light""); resourcePreviewLight.lightType = LIGHT_DIRECTIONAL; resourcePreviewLight.specularIntensity = 0.5; resourceBrowserPreview = browserWindow.GetChild(""ResourceBrowserPreview"", true); resourceBrowserPreview.SetFixedHeight(200); resourceBrowserPreview.SetFixedWidth(266); resourceBrowserPreview.SetView(resourcePreviewScene, camera); resourceBrowserPreview.autoUpdate = false; resourcePreviewNode = resourcePreviewScene.CreateChild(""PreviewNodeContainer""); SubscribeToEvent(resourceBrowserPreview, ""DragMove"", ""RotateResourceBrowserPreview""); RefreshBrowserPreview(); } // Opens a contextual menu based on what resource item was actioned void HandleBrowserFileClick(StringHash eventType, VariantMap& eventData) { if (eventData[""Button""].GetInt() != MOUSEB_RIGHT) return; UIElement@ uiElement = eventData[""Item""].GetPtr(); BrowserFile@ file = GetBrowserFileFromUIElement(uiElement); if (file is null) return; Array actions; if (file.resourceType == RESOURCE_TYPE_MATERIAL) { actions.Push(CreateBrowserFileActionMenu(""Edit"", ""HandleBrowserEditResource"", file)); } else if (file.resourceType == RESOURCE_TYPE_MODEL) { actions.Push(CreateBrowserFileActionMenu(""Instance Animated Model"", ""HandleBrowserInstantiateAnimatedModel"", file)); actions.Push(CreateBrowserFileActionMenu(""Instance Static Model"", ""HandleBrowserInstantiateStaticModel"", file)); } else if (file.resourceType == RESOURCE_TYPE_PREFAB) { actions.Push(CreateBrowserFileActionMenu(""Instance Prefab"", ""HandleBrowserInstantiatePrefab"", file)); actions.Push(CreateBrowserFileActionMenu(""Instance in Spawner"", ""HandleBrowserInstantiateInSpawnEditor"", file)); } else if (file.fileType == EXTENSION_TYPE_OBJ || file.fileType == EXTENSION_TYPE_COLLADA || file.fileType == EXTENSION_TYPE_FBX || file.fileType == EXTENSION_TYPE_BLEND) { actions.Push(CreateBrowserFileActionMenu(""Import Model"", ""HandleBrowserImportModel"", file)); actions.Push(CreateBrowserFileActionMenu(""Import Scene"", ""HandleBrowserImportScene"", file)); } else if (file.resourceType == RESOURCE_TYPE_UIELEMENT) { actions.Push(CreateBrowserFileActionMenu(""Open UI Layout"", ""HandleBrowserOpenUILayout"", file)); } else if (file.resourceType == RESOURCE_TYPE_SCENE) { actions.Push(CreateBrowserFileActionMenu(""Load Scene"", ""HandleBrowserLoadScene"", file)); } else if (file.resourceType == RESOURCE_TYPE_SCRIPTFILE) { actions.Push(CreateBrowserFileActionMenu(""Execute Script"", ""HandleBrowserRunScript"", file)); } else if (file.resourceType == RESOURCE_TYPE_PARTICLEEFFECT) { actions.Push(CreateBrowserFileActionMenu(""Edit"", ""HandleBrowserEditResource"", file)); } actions.Push(CreateBrowserFileActionMenu(""Open"", ""HandleBrowserOpenResource"", file)); ActivateContextMenu(actions); } BrowserDir@ GetBrowserDir(String path) { BrowserDir@ browserDir; browserDirs.Get(path, @browserDir); return browserDir; } // Makes sure the entire directory tree exists and new dir is linked to parent BrowserDir@ InitBrowserDir(String path) { BrowserDir@ browserDir; if (browserDirs.Get(path, @browserDir)) return browserDir; Array parts = path.Split('/'); Array finishedParts; if (parts.length > 0) { BrowserDir@ parent = rootDir; for( uint i = 0; i < parts.length; ++i ) { finishedParts.Push(parts[i]); String currentPath = Join(finishedParts, ""/""); if (!browserDirs.Get(currentPath, @browserDir)) { browserDir = BrowserDir(currentPath); browserDirs.Set(currentPath, @browserDir); parent.children.Push(browserDir); } @parent = browserDir; } return browserDir; } return null; } void ScanResourceDir(uint resourceDirIndex) { String resourceDir = cache.resourceDirs[resourceDirIndex]; ScanResourceDirFiles("""", resourceDirIndex); Array dirs = fileSystem.ScanDir(resourceDir, ""*"", SCAN_DIRS, true); for (uint i=0; i < dirs.length; ++i) { String path = dirs[i]; if (path.EndsWith(""."")) continue; InitBrowserDir(path); ScanResourceDirFiles(path, resourceDirIndex); } } void ScanResourceDirFiles(String path, uint resourceDirIndex) { String fullPath = cache.resourceDirs[resourceDirIndex] + path; if (!fileSystem.DirExists(fullPath)) return; BrowserDir@ dir = GetBrowserDir(path); if (dir is null) return; // get files in directory Array dirFiles = fileSystem.ScanDir(fullPath, ""*.*"", SCAN_FILES, false); // add new files for (uint x=0; x < dirFiles.length; x++) { String filename = dirFiles[x]; BrowserFile@ browserFile = dir.AddFile(filename, resourceDirIndex, BROWSER_FILE_SOURCE_RESOURCE_DIR); browserFiles.Push(browserFile); browserFilesToScan.Push(browserFile); } } bool ToggleResourceBrowserWindow() { if (browserWindow.visible == false) ShowResourceBrowserWindow(); else HideResourceBrowserWindow(); return true; } void ShowResourceBrowserWindow() { browserWindow.visible = true; browserWindow.BringToFront(); ui.focusElement = browserSearch; } void HideResourceBrowserWindow() { browserWindow.visible = false; } void ToggleResourceFilterWindow() { if (browserFilterWindow.visible) HideResourceFilterWindow(); else ShowResourceFilterWindow(); } void HideResourceFilterWindow() { browserFilterWindow.visible = false; } void ShowResourceFilterWindow() { int x = browserWindow.position.x + browserWindow.width - browserFilterWindow.width; int y = browserWindow.position.y - browserFilterWindow.height - 1; browserFilterWindow.position = IntVector2(x,y); browserFilterWindow.visible = true; browserFilterWindow.BringToFront(); } void PopulateResourceDirFilters() { UIElement@ resourceDirs = browserFilterWindow.GetChild(""DirFilters"", true); resourceDirs.RemoveAllChildren(); activeResourceDirFilters.Clear(); for (uint i=0; i < cache.resourceDirs.length; ++i) { UIElement@ resourceDirHolder = UIElement(); resourceDirs.AddChild(resourceDirHolder); resourceDirHolder.layoutMode = LM_HORIZONTAL; resourceDirHolder.layoutSpacing = 4; resourceDirHolder.SetFixedHeight(16); Text@ label = Text(); label.style = ""EditorAttributeText""; label.text = cache.resourceDirs[i].Replaced(fileSystem.programDir, """"); CheckBox@ checkbox = CheckBox(); checkbox.name = i; checkbox.SetStyleAuto(); checkbox.vars[TEXT_VAR_RESOURCE_DIR_ID] = i; checkbox.checked = true; SubscribeToEvent(checkbox, ""Toggled"", ""HandleResourceDirFilterToggled""); resourceDirHolder.AddChild(checkbox); resourceDirHolder.AddChild(label); } } void PopulateBrowserDirectories() { browserDirList.RemoveAllItems(); CreateDirList(rootDir); browserDirList.selection = 0; } void PopulateResourceBrowserFilesByDirectory(BrowserDir@ dir) { @selectedBrowserDirectory = dir; browserFileList.RemoveAllItems(); if (dir is null) return; Array files; for(uint x=0; x < dir.files.length; x++) { BrowserFile@ file = dir.files[x]; if (activeResourceTypeFilters.Find(file.resourceType) == -1) files.Push(file); } // Sort alphetically browserSearchSortMode = BROWSER_SORT_MODE_ALPHA; files.Sort(); PopulateResourceBrowserResults(files); browserResultsMessage.text = localization.Get(""Showing files: "") + files.length; } void PopulateResourceBrowserBySearch() { String query = browserSearch.text; Array scores; Array scored; Array filtered; { BrowserFile@ file; for(uint x=0; x < browserFiles.length; x++) { @file = browserFiles[x]; file.sortScore = -1; if (activeResourceTypeFilters.Find(file.resourceType) > -1) continue; if (activeResourceDirFilters.Find(file.resourceSourceIndex) > -1) continue; int find = file.fullname.Find(query, 0, false); if (find > -1) { int fudge = query.length - file.fullname.length; int score = find * int(Abs(fudge*2)) + int(Abs(fudge)); file.sortScore = score; scored.Push(file); scores.Push(score); } } } // cut this down for a faster sort if (scored.length > BROWSER_SEARCH_LIMIT) { scores.Sort(); int scoreThreshold = scores[BROWSER_SEARCH_LIMIT]; BrowserFile@ file; for(uint x=0;x@ files) { browserFileList.RemoveAllItems(); for(uint i=0; i < files.length; ++i) CreateFileList(files[i]); } void RefreshBrowserResults() { if (browserSearch.text.empty) { browserDirList.visible = true; PopulateResourceBrowserFilesByDirectory(selectedBrowserDirectory); } else { browserDirList.visible = false; PopulateResourceBrowserBySearch(); } } void HandleResourceTypeFilterToggleAllTypesToggled(StringHash eventType, VariantMap& eventData) { CheckBox@ checkbox = eventData[""Element""].GetPtr(); UIElement@ filterHolder = browserFilterWindow.GetChild(""TypeFilters"", true); Array children = filterHolder.GetChildren(true); ignoreRefreshBrowserResults = true; for(uint i=0; i < children.length; ++i) { CheckBox@ filter = children[i]; if (filter !is null) filter.checked = checkbox.checked; } ignoreRefreshBrowserResults = false; RefreshBrowserResults(); } void HandleResourceTypeFilterToggled(StringHash eventType, VariantMap& eventData) { CheckBox@ checkbox = eventData[""Element""].GetPtr(); if (!checkbox.vars.Contains(TEXT_VAR_RESOURCE_TYPE)) return; int resourceType = checkbox.GetVar(TEXT_VAR_RESOURCE_TYPE).GetInt(); int find = activeResourceTypeFilters.Find(resourceType); if (checkbox.checked && find != -1) activeResourceTypeFilters.Erase(find); else if (!checkbox.checked && find == -1) activeResourceTypeFilters.Push(resourceType); if (ignoreRefreshBrowserResults == false) RefreshBrowserResults(); } void HandleResourceDirFilterToggleAllTypesToggled(StringHash eventType, VariantMap& eventData) { CheckBox@ checkbox = eventData[""Element""].GetPtr(); UIElement@ filterHolder = browserFilterWindow.GetChild(""DirFilters"", true); Array children = filterHolder.GetChildren(true); ignoreRefreshBrowserResults = true; for(uint i=0; i < children.length; ++i) { CheckBox@ filter = children[i]; if (filter !is null) filter.checked = checkbox.checked; } ignoreRefreshBrowserResults = false; RebuildResourceDatabase(); } void HandleResourceDirFilterToggled(StringHash eventType, VariantMap& eventData) { CheckBox@ checkbox = eventData[""Element""].GetPtr(); if (!checkbox.vars.Contains(TEXT_VAR_RESOURCE_DIR_ID)) return; int resourceDir = checkbox.GetVar(TEXT_VAR_RESOURCE_DIR_ID).GetInt(); int find = activeResourceDirFilters.Find(resourceDir); if (checkbox.checked && find != -1) activeResourceDirFilters.Erase(find); else if (!checkbox.checked && find == -1) activeResourceDirFilters.Push(resourceDir); if (ignoreRefreshBrowserResults == false) RebuildResourceDatabase(); } void HandleRescanResourceBrowserClick(StringHash eventType, VariantMap& eventData) { RebuildResourceDatabase(); } void HandleResourceBrowserDirListSelectionChange(StringHash eventType, VariantMap& eventData) { if (browserDirList.selection == M_MAX_UNSIGNED) return; UIElement@ uiElement = browserDirList.GetItems()[browserDirList.selection]; BrowserDir@ dir = GetBrowserDir(uiElement.vars[TEXT_VAR_DIR_ID].GetString()); if (dir is null) return; PopulateResourceBrowserFilesByDirectory(dir); } void HandleResourceBrowserFileListSelectionChange(StringHash eventType, VariantMap& eventData) { if (browserFileList.selection == M_MAX_UNSIGNED) return; UIElement@ uiElement = browserFileList.GetItems()[browserFileList.selection]; BrowserFile@ file = GetBrowserFileFromUIElement(uiElement); if (file is null) return; if (resourcePreviewNode !is null) resourcePreviewNode.Remove(); resourcePreviewNode = resourcePreviewScene.CreateChild(""PreviewNodeContainer""); CreateResourcePreview(file.GetFullPath(), resourcePreviewNode); if (resourcePreviewNode !is null) { Array boxes; Array staticModels = resourcePreviewNode.GetComponents(""StaticModel"", true); Array animatedModels = resourcePreviewNode.GetComponents(""AnimatedModel"", true); for (uint i = 0; i < staticModels.length; ++i) boxes.Push(cast(staticModels[i]).worldBoundingBox); for (uint i = 0; i < animatedModels.length; ++i) boxes.Push(cast(animatedModels[i]).worldBoundingBox); if (boxes.length > 0) { Vector3 camPosition = Vector3(0.0, 0.0, -1.2); BoundingBox biggestBox = boxes[0]; for (uint i = 1; i < boxes.length; ++i) { if (boxes[i].size.length > biggestBox.size.length) biggestBox = boxes[i]; } resourcePreviewCameraNode.position = biggestBox.center + camPosition * biggestBox.size.length; } resourcePreviewScene.AddChild(resourcePreviewNode); RefreshBrowserPreview(); } } void HandleResourceBrowserSearchTextChange(StringHash eventType, VariantMap& eventData) { RefreshBrowserResults(); } BrowserFile@ GetBrowserFileFromId(uint id) { if (id == 0) return null; BrowserFile@ file; for(uint i=0; i(GetDrawableAtMousePostion()); if (model !is null) { AssignMaterial(model, browserDragFile.resourceKey); } } browserDragFile = null; browserDragComponent = null; browserDragNode = null; } void HandleFileChanged(StringHash eventType, VariantMap& eventData) { String filename = eventData[""FileName""].GetString(); BrowserFile@ file = GetBrowserFileFromPath(filename); if (file is null) { // TODO: new file logic when watchers are supported return; } else { file.FileChanged(); } } Menu@ CreateBrowserFileActionMenu(String text, String handler, BrowserFile@ browserFile = null) { Menu@ menu = CreateContextMenuItem(text, handler); if (browserFile !is null) menu.vars[TEXT_VAR_FILE_ID] = browserFile.id; return menu; } int GetResourceType(String path) { StringHash fileType; return GetResourceType(path, fileType); } int GetResourceType(String path, StringHash &out fileType, bool useCache = false) { if (GetExtensionType(path, fileType) || GetBinaryType(path, fileType, useCache) || GetXmlType(path, fileType, useCache)) return GetResourceType(fileType); return RESOURCE_TYPE_UNKNOWN; } int GetResourceType(StringHash fileType) { // binary fileTypes if (fileType == BINARY_TYPE_SCENE) return RESOURCE_TYPE_SCENE; else if (fileType == BINARY_TYPE_PACKAGE) return RESOURCE_TYPE_UNUSABLE; else if (fileType == BINARY_TYPE_COMPRESSED_PACKAGE) return RESOURCE_TYPE_UNUSABLE; else if (fileType == BINARY_TYPE_ANGLESCRIPT) return RESOURCE_TYPE_SCRIPTFILE; else if (fileType == BINARY_TYPE_MODEL) return RESOURCE_TYPE_MODEL; else if (fileType == BINARY_TYPE_SHADER) return RESOURCE_TYPE_UNUSABLE; else if (fileType == BINARY_TYPE_ANIMATION) return RESOURCE_TYPE_ANIMATION; // xml fileTypes else if (fileType == XML_TYPE_SCENE) return RESOURCE_TYPE_SCENE; else if (fileType == XML_TYPE_NODE) return RESOURCE_TYPE_PREFAB; else if(fileType == XML_TYPE_MATERIAL) return RESOURCE_TYPE_MATERIAL; else if(fileType == XML_TYPE_TECHNIQUE) return RESOURCE_TYPE_TECHNIQUE; else if(fileType == XML_TYPE_PARTICLEEFFECT) return RESOURCE_TYPE_PARTICLEEFFECT; else if(fileType == XML_TYPE_PARTICLEEMITTER) return RESOURCE_TYPE_PARTICLEEMITTER; else if(fileType == XML_TYPE_TEXTURE) return RESOURCE_TYPE_TEXTURE; else if(fileType == XML_TYPE_ELEMENT) return RESOURCE_TYPE_UIELEMENT; else if(fileType == XML_TYPE_ELEMENTS) return RESOURCE_TYPE_UIELEMENTS; else if (fileType == XML_TYPE_ANIMATION_SETTINGS) return RESOURCE_TYPE_ANIMATION_SETTINGS; else if (fileType == XML_TYPE_RENDERPATH) return RESOURCE_TYPE_RENDERPATH; else if (fileType == XML_TYPE_TEXTURE_ATLAS) return RESOURCE_TYPE_TEXTURE_ATLAS; else if (fileType == XML_TYPE_2D_PARTICLE_EFFECT) return RESOURCE_TYPE_2D_PARTICLE_EFFECT; else if (fileType == XML_TYPE_TEXTURE_3D) return RESOURCE_TYPE_TEXTURE_3D; else if (fileType == XML_TYPE_CUBEMAP) return RESOURCE_TYPE_CUBEMAP; else if (fileType == XML_TYPE_SPRITER_DATA) return RESOURCE_TYPE_2D_ANIMATION_SET; // JSON fileTypes else if (fileType == JSON_TYPE_SCENE) return RESOURCE_TYPE_SCENE; else if (fileType == JSON_TYPE_NODE) return RESOURCE_TYPE_PREFAB; else if(fileType == JSON_TYPE_MATERIAL) return RESOURCE_TYPE_MATERIAL; else if(fileType == JSON_TYPE_TECHNIQUE) return RESOURCE_TYPE_TECHNIQUE; else if(fileType == JSON_TYPE_PARTICLEEFFECT) return RESOURCE_TYPE_PARTICLEEFFECT; else if(fileType == JSON_TYPE_PARTICLEEMITTER) return RESOURCE_TYPE_PARTICLEEMITTER; else if(fileType == JSON_TYPE_TEXTURE) return RESOURCE_TYPE_TEXTURE; else if(fileType == JSON_TYPE_ELEMENT) return RESOURCE_TYPE_UIELEMENT; else if(fileType == JSON_TYPE_ELEMENTS) return RESOURCE_TYPE_UIELEMENTS; else if (fileType == JSON_TYPE_ANIMATION_SETTINGS) return RESOURCE_TYPE_ANIMATION_SETTINGS; else if (fileType == JSON_TYPE_RENDERPATH) return RESOURCE_TYPE_RENDERPATH; else if (fileType == JSON_TYPE_TEXTURE_ATLAS) return RESOURCE_TYPE_TEXTURE_ATLAS; else if (fileType == JSON_TYPE_2D_PARTICLE_EFFECT) return RESOURCE_TYPE_2D_PARTICLE_EFFECT; else if (fileType == JSON_TYPE_TEXTURE_3D) return RESOURCE_TYPE_TEXTURE_3D; else if (fileType == JSON_TYPE_CUBEMAP) return RESOURCE_TYPE_CUBEMAP; else if (fileType == JSON_TYPE_SPRITER_DATA) return RESOURCE_TYPE_2D_ANIMATION_SET; // extension fileTypes else if (fileType == EXTENSION_TYPE_TTF) return RESOURCE_TYPE_FONT; else if (fileType == EXTENSION_TYPE_OTF) return RESOURCE_TYPE_FONT; else if (fileType == EXTENSION_TYPE_OGG) return RESOURCE_TYPE_SOUND; else if(fileType == EXTENSION_TYPE_WAV) return RESOURCE_TYPE_SOUND; else if(fileType == EXTENSION_TYPE_DDS) return RESOURCE_TYPE_IMAGE; else if(fileType == EXTENSION_TYPE_PNG) return RESOURCE_TYPE_IMAGE; else if(fileType == EXTENSION_TYPE_JPG) return RESOURCE_TYPE_IMAGE; else if(fileType == EXTENSION_TYPE_JPEG) return RESOURCE_TYPE_IMAGE; else if(fileType == EXTENSION_TYPE_BMP) return RESOURCE_TYPE_IMAGE; else if(fileType == EXTENSION_TYPE_TGA) return RESOURCE_TYPE_IMAGE; else if(fileType == EXTENSION_TYPE_KTX) return RESOURCE_TYPE_IMAGE; else if(fileType == EXTENSION_TYPE_PVR) return RESOURCE_TYPE_IMAGE; else if(fileType == EXTENSION_TYPE_OBJ) return RESOURCE_TYPE_UNUSABLE; else if(fileType == EXTENSION_TYPE_FBX) return RESOURCE_TYPE_UNUSABLE; else if(fileType == EXTENSION_TYPE_COLLADA) return RESOURCE_TYPE_UNUSABLE; else if(fileType == EXTENSION_TYPE_BLEND) return RESOURCE_TYPE_UNUSABLE; else if(fileType == EXTENSION_TYPE_ANGELSCRIPT) return RESOURCE_TYPE_SCRIPTFILE; else if(fileType == EXTENSION_TYPE_LUASCRIPT) return RESOURCE_TYPE_SCRIPTFILE; else if(fileType == EXTENSION_TYPE_HLSL) return RESOURCE_TYPE_UNUSABLE; else if(fileType == EXTENSION_TYPE_GLSL) return RESOURCE_TYPE_UNUSABLE; else if(fileType == EXTENSION_TYPE_FRAGMENTSHADER) return RESOURCE_TYPE_UNUSABLE; else if(fileType == EXTENSION_TYPE_VERTEXSHADER) return RESOURCE_TYPE_UNUSABLE; else if(fileType == EXTENSION_TYPE_HTML) return RESOURCE_TYPE_UNUSABLE; return RESOURCE_TYPE_UNKNOWN; } bool GetExtensionType(String path, StringHash &out fileType) { StringHash type = StringHash(GetExtension(path)); if (type == EXTENSION_TYPE_TTF) fileType = EXTENSION_TYPE_TTF; else if (type == EXTENSION_TYPE_OTF) fileType = EXTENSION_TYPE_OTF; else if (type == EXTENSION_TYPE_OGG) fileType = EXTENSION_TYPE_OGG; else if(type == EXTENSION_TYPE_WAV) fileType = EXTENSION_TYPE_WAV; else if(type == EXTENSION_TYPE_DDS) fileType = EXTENSION_TYPE_DDS; else if(type == EXTENSION_TYPE_PNG) fileType = EXTENSION_TYPE_PNG; else if(type == EXTENSION_TYPE_JPG) fileType = EXTENSION_TYPE_JPG; else if(type == EXTENSION_TYPE_JPEG) fileType = EXTENSION_TYPE_JPEG; else if(type == EXTENSION_TYPE_BMP) fileType = EXTENSION_TYPE_BMP; else if(type == EXTENSION_TYPE_TGA) fileType = EXTENSION_TYPE_TGA; else if(type == EXTENSION_TYPE_KTX) fileType = EXTENSION_TYPE_KTX; else if(type == EXTENSION_TYPE_PVR) fileType = EXTENSION_TYPE_PVR; else if(type == EXTENSION_TYPE_OBJ) fileType = EXTENSION_TYPE_OBJ; else if(type == EXTENSION_TYPE_FBX) fileType = EXTENSION_TYPE_FBX; else if(type == EXTENSION_TYPE_COLLADA) fileType = EXTENSION_TYPE_COLLADA; else if(type == EXTENSION_TYPE_BLEND) fileType = EXTENSION_TYPE_BLEND; else if(type == EXTENSION_TYPE_ANGELSCRIPT) fileType = EXTENSION_TYPE_ANGELSCRIPT; else if(type == EXTENSION_TYPE_LUASCRIPT) fileType = EXTENSION_TYPE_LUASCRIPT; else if(type == EXTENSION_TYPE_HLSL) fileType = EXTENSION_TYPE_HLSL; else if(type == EXTENSION_TYPE_GLSL) fileType = EXTENSION_TYPE_GLSL; else if(type == EXTENSION_TYPE_FRAGMENTSHADER) fileType = EXTENSION_TYPE_FRAGMENTSHADER; else if(type == EXTENSION_TYPE_VERTEXSHADER) fileType = EXTENSION_TYPE_VERTEXSHADER; else if(type == EXTENSION_TYPE_HTML) fileType = EXTENSION_TYPE_HTML; else return false; return true; } bool GetBinaryType(String path, StringHash &out fileType, bool useCache = false) { StringHash type; if (useCache) { File@ file = cache.GetFile(path); if (file is null) return false; if (file.size == 0) return false; type = StringHash(file.ReadFileID()); } else { File@ file = File(); if (!file.Open(path)) return false; if (file.size == 0) return false; type = StringHash(file.ReadFileID()); } if (type == BINARY_TYPE_SCENE) fileType = BINARY_TYPE_SCENE; else if (type == BINARY_TYPE_PACKAGE) fileType = BINARY_TYPE_PACKAGE; else if (type == BINARY_TYPE_COMPRESSED_PACKAGE) fileType = BINARY_TYPE_COMPRESSED_PACKAGE; else if (type == BINARY_TYPE_ANGLESCRIPT) fileType = BINARY_TYPE_ANGLESCRIPT; else if (type == BINARY_TYPE_MODEL) fileType = BINARY_TYPE_MODEL; else if (type == BINARY_TYPE_SHADER) fileType = BINARY_TYPE_SHADER; else if (type == BINARY_TYPE_ANIMATION) fileType = BINARY_TYPE_ANIMATION; else return false; return true; } bool GetXmlType(String path, StringHash &out fileType, bool useCache = false) { String extension = GetExtension(path); if (extension == "".txt"" || extension == "".json"" || extension == "".icns"" || extension == "".atlas"") return false; String name; if (useCache) { XMLFile@ xml = cache.GetResource(""XMLFile"", path); if (xml is null) return false; name = xml.root.name; } else { File@ file = File(); if (!file.Open(path)) return false; if (file.size == 0) return false; XMLFile@ xml = XMLFile(); if (xml.Load(file)) name = xml.root.name; else return false; } bool found = false; if (!name.empty) { found = true; StringHash type = StringHash(name); if (type == XML_TYPE_SCENE) fileType = XML_TYPE_SCENE; else if (type == XML_TYPE_NODE) fileType = XML_TYPE_NODE; else if(type == XML_TYPE_MATERIAL) fileType = XML_TYPE_MATERIAL; else if(type == XML_TYPE_TECHNIQUE) fileType = XML_TYPE_TECHNIQUE; else if(type == XML_TYPE_PARTICLEEFFECT) fileType = XML_TYPE_PARTICLEEFFECT; else if(type == XML_TYPE_PARTICLEEMITTER) fileType = XML_TYPE_PARTICLEEMITTER; else if(type == XML_TYPE_TEXTURE) fileType = XML_TYPE_TEXTURE; else if(type == XML_TYPE_ELEMENT) fileType = XML_TYPE_ELEMENT; else if(type == XML_TYPE_ELEMENTS) fileType = XML_TYPE_ELEMENTS; else if (type == XML_TYPE_ANIMATION_SETTINGS) fileType = XML_TYPE_ANIMATION_SETTINGS; else if (type == XML_TYPE_RENDERPATH) fileType = XML_TYPE_RENDERPATH; else if (type == XML_TYPE_TEXTURE_ATLAS) fileType = XML_TYPE_TEXTURE_ATLAS; else if (type == XML_TYPE_2D_PARTICLE_EFFECT) fileType = XML_TYPE_2D_PARTICLE_EFFECT; else if (type == XML_TYPE_TEXTURE_3D) fileType = XML_TYPE_TEXTURE_3D; else if (type == XML_TYPE_CUBEMAP) fileType = XML_TYPE_CUBEMAP; else if (type == XML_TYPE_SPRITER_DATA) fileType = XML_TYPE_SPRITER_DATA; else found = false; } return found; } String ResourceTypeName(int resourceType) { if (resourceType == RESOURCE_TYPE_UNUSABLE) return ""Unusable""; else if (resourceType == RESOURCE_TYPE_UNKNOWN) return ""Unknown""; else if (resourceType == RESOURCE_TYPE_NOTSET) return ""Uninitialized""; else if (resourceType == RESOURCE_TYPE_SCENE) return ""Scene""; else if (resourceType == RESOURCE_TYPE_SCRIPTFILE) return ""Script File""; else if (resourceType == RESOURCE_TYPE_MODEL) return ""Model""; else if (resourceType == RESOURCE_TYPE_MATERIAL) return ""Material""; else if (resourceType == RESOURCE_TYPE_ANIMATION) return ""Animation""; else if (resourceType == RESOURCE_TYPE_IMAGE) return ""Image""; else if (resourceType == RESOURCE_TYPE_SOUND) return ""Sound""; else if (resourceType == RESOURCE_TYPE_TEXTURE) return ""Texture""; else if (resourceType == RESOURCE_TYPE_FONT) return ""Font""; else if (resourceType == RESOURCE_TYPE_PREFAB) return ""Prefab""; else if (resourceType == RESOURCE_TYPE_TECHNIQUE) return ""Render Technique""; else if (resourceType == RESOURCE_TYPE_PARTICLEEFFECT) return ""Particle Effect""; else if (resourceType == RESOURCE_TYPE_PARTICLEEMITTER) return ""Particle Emitter""; else if (resourceType == RESOURCE_TYPE_UIELEMENT) return ""UI Element""; else if (resourceType == RESOURCE_TYPE_UIELEMENTS) return ""UI Elements""; else if (resourceType == RESOURCE_TYPE_ANIMATION_SETTINGS) return ""Animation Settings""; else if (resourceType == RESOURCE_TYPE_RENDERPATH) return ""Render Path""; else if (resourceType == RESOURCE_TYPE_TEXTURE_ATLAS) return ""Texture Atlas""; else if (resourceType == RESOURCE_TYPE_2D_PARTICLE_EFFECT) return ""2D Particle Effect""; else if (resourceType == RESOURCE_TYPE_TEXTURE_3D) return ""Texture 3D""; else if (resourceType == RESOURCE_TYPE_CUBEMAP) return ""Cubemap""; else if (resourceType == RESOURCE_TYPE_2D_ANIMATION_SET) return ""2D Animation Set""; else return """"; } class BrowserDir { uint id; String resourceKey; String name; Array children; Array files; BrowserDir(String path_) { resourceKey = path_; String parent = GetParentPath(path_); name = path_; name.Replace(parent, """"); id = browserDirIndex++; } int opCmp(BrowserDir@ b) { return name.opCmp(b.name); } BrowserFile@ AddFile(String name, uint resourceSourceIndex, uint sourceType) { String path = resourceKey + ""/"" + name; BrowserFile@ file = BrowserFile(path, resourceSourceIndex, sourceType); files.Push(file); return file; } } class BrowserFile { uint id; uint resourceSourceIndex; String resourceKey; String name; String fullname; String extension; StringHash fileType; int resourceType = 0; int sourceType = 0; int sortScore = 0; WeakHandle browserFileListRow; BrowserFile(String path_, uint resourceSourceIndex_, int sourceType_) { sourceType = sourceType_; resourceSourceIndex = resourceSourceIndex_; resourceKey = path_; name = GetFileName(path_); extension = GetExtension(path_); fullname = GetFileNameAndExtension(path_); id = browserFileIndex++; } int opCmp(BrowserFile@ b) { if (browserSearchSortMode == 1) return fullname.opCmp(b.fullname); else return sortScore - b.sortScore; } String GetResourceSource() { if (sourceType == BROWSER_FILE_SOURCE_RESOURCE_DIR) return cache.resourceDirs[resourceSourceIndex]; else return ""Unknown""; } String GetFullPath() { return String(cache.resourceDirs[resourceSourceIndex] + resourceKey); } String GetPath() { return resourceKey; } void DetermainResourceType() { resourceType = GetResourceType(GetFullPath(), fileType, false); Text@ browserFileListRow_ = browserFileListRow.Get(); if (browserFileListRow_ !is null) { InitializeBrowserFileListRow(browserFileListRow_, this); } } String ResourceTypeName() { return ::ResourceTypeName(resourceType); } void FileChanged() { if (!fileSystem.FileExists(GetFullPath())) { } else { } } } void CreateResourcePreview(String path, Node@ previewNode) { resourceBrowserPreview.autoUpdate = false; int resourceType = GetResourceType(path); if (resourceType > 0) { File file; file.Open(path); if (resourceType == RESOURCE_TYPE_MODEL) { Model@ model = Model(); if (model.Load(file)) { StaticModel@ staticModel = previewNode.CreateComponent(""StaticModel""); staticModel.model = model; return; } } else if (resourceType == RESOURCE_TYPE_MATERIAL) { Material@ material = Material(); if (material.Load(file)) { StaticModel@ staticModel = previewNode.CreateComponent(""StaticModel""); staticModel.model = cache.GetResource(""Model"", ""Models/Sphere.mdl""); staticModel.material = material; return; } } else if (resourceType == RESOURCE_TYPE_IMAGE) { Image@ image = Image(); if (image.Load(file)) { StaticModel@ staticModel = previewNode.CreateComponent(""StaticModel""); staticModel.model = cache.GetResource(""Model"", ""Models/Editor/ImagePlane.mdl""); Material@ material = cache.GetResource(""Material"", ""Materials/Editor/TexturedUnlit.xml""); Texture2D@ texture = Texture2D(); texture.SetData(@image, true); material.textures[0] = texture; staticModel.material = material; return; } } else if (resourceType == RESOURCE_TYPE_PREFAB) { if (GetExtension(path) == "".xml"") { XMLFile xmlFile; if(xmlFile.Load(file)) if(previewNode.LoadXML(xmlFile.root, true) && (previewNode.GetComponents(""StaticModel"", true).length > 0 || previewNode.GetComponents(""AnimatedModel"", true).length > 0)) { return; } } else if(previewNode.Load(file, true) && (previewNode.GetComponents(""StaticModel"", true).length > 0 || previewNode.GetComponents(""AnimatedModel"", true).length > 0)) return; previewNode.RemoveAllChildren(); previewNode.RemoveAllComponents(); } else if (resourceType == RESOURCE_TYPE_PARTICLEEFFECT) { ParticleEffect@ particleEffect = ParticleEffect(); if (particleEffect.Load(file)) { ParticleEmitter@ particleEmitter = previewNode.CreateComponent(""ParticleEmitter""); particleEmitter.effect = particleEffect; particleEffect.activeTime = 0.0; particleEmitter.Reset(); resourceBrowserPreview.autoUpdate = true; return; } } } StaticModel@ staticModel = previewNode.CreateComponent(""StaticModel""); staticModel.model = cache.GetResource(""Model"", ""Models/Editor/ImagePlane.mdl""); Material@ material = cache.GetResource(""Material"", ""Materials/Editor/TexturedUnlit.xml""); Texture2D@ texture = Texture2D(); Image@ noPreviewImage = cache.GetResource(""Image"", ""Textures/Editor/NoPreviewAvailable.png""); texture.SetData(noPreviewImage, false); material.textures[0] = texture; staticModel.material = material; return; } void RotateResourceBrowserPreview(StringHash eventType, VariantMap& eventData) { int elemX = eventData[""ElementX""].GetInt(); int elemY = eventData[""ElementY""].GetInt(); if (resourceBrowserPreview.height > 0 && resourceBrowserPreview.width > 0) { float yaw = ((resourceBrowserPreview.height / 2) - elemY) * (90.0 / resourceBrowserPreview.height); float pitch = ((resourceBrowserPreview.width / 2) - elemX) * (90.0 / resourceBrowserPreview.width); resourcePreviewNode.rotation = resourcePreviewNode.rotation.Slerp(Quaternion(yaw, pitch, 0), 0.1); RefreshBrowserPreview(); } } void RefreshBrowserPreview() { resourceBrowserPreview.QueueUpdate(); } class ResourceType { int id; String name; ResourceType(int id_, String name_) { id = id_; name = name_; } int opCmp(ResourceType@ b) { return name.opCmp(b.name); } } ",12481,False,2446.249961562693,median "= v1.ImageStream {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] ImageStream stores a mapping of tags to images, metadata overrides that are applied when images are tagged in a stream, and an optional reference to a Docker image repository on a registry. == Object Schema Expand or mouse-over a field for more information about it. ++++
    apiVersion:
    kind:
    metadata:
    annotations:
    [string]:
    clusterName:
    creationTimestamp:
    deletionGracePeriodSeconds:
    deletionTimestamp:
    finalizers:
    - [string]:
    generateName:
    generation:
    :
    pending:
    - name:
    result:
    apiVersion:
    code:
    details:
    causes:
    - field:
    message:
    reason:
    group:
    kind:
    name:
    retryAfterSeconds:
    uid:
    kind:
    message:
    metadata:
    continue:
    resourceVersion:
    selfLink:
    reason:
    status:
    labels:
    [string]:
    name:
    namespace:
    ownerReferences:
    - apiVersion:
    blockOwnerDeletion:
    controller:
    kind:
    name:
    uid:
    resourceVersion:
    selfLink:
    uid:
    spec:
    dockerImageRepository:
    lookupPolicy:
    local:
    tags:
    - annotations:
    - [string]:
    from:
    apiVersion:
    fieldPath:
    kind:
    name:
    namespace:
    resourceVersion:
    uid:
    generation:
    importPolicy:
    insecure:
    scheduled:
    name:
    reference:
    referencePolicy:
    type:
    status:
    dockerImageRepository:
    publicDockerImageRepository:
    tags:
    - conditions:
    - - generation:
    lastTransitionTime:
    message:
    reason:
    status:
    type:
    items:
    - created:
    dockerImageReference:
    generation:
    image:
    tag:
    ++++ == Operations [[Post-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Create a ImageStream in a namespace Create an ImageStream ==== HTTP request ---- POST /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |202 Accepted|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Get a ImageStream in a namespace Read the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-imagestreams]] === Get all ImageStreams List or watch objects of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/imagestreams ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStreamList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Get all ImageStreams in a namespace List or watch objects of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStreamList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-namespaces-namespace-imagestreams-name]] === Watch a ImageStream in a namespace Watch changes to an object of kind ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-imagestreams]] === Watch all ImageStreams Watch individual changes to a list of ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/imagestreams ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-image.openshift.io-v1-watch-namespaces-namespace-imagestreams]] === Watch all ImageStreams in a namespace Watch individual changes to a list of ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/watch/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Update a ImageStream in a namespace Replace the specified ImageStream ==== HTTP request ---- PUT /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Patch a ImageStream in a namespace Partially update the specified ImageStream ==== HTTP request ---- PATCH /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name]] === Delete a ImageStream in a namespace Delete an ImageStream ==== HTTP request ---- DELETE /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-image.openshift.io-v1-namespaces-namespace-imagestreams]] === Delete all ImageStreams in a namespace Delete collection of ImageStream ==== HTTP request ---- DELETE /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-layers]] === Get layers of a ImageStream in a namespace Read layers of the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/layers HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/layers ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStreamLayers |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStreamLayers |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-secrets]] === Get secrets of a ImageStream in a namespace Read secrets of the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/secrets HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/secrets ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the SecretList |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.SecretList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Get status of a ImageStream in a namespace Read status of the specified ImageStream ==== HTTP request ---- GET /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Put-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Update status of a ImageStream in a namespace Replace status of the specified ImageStream ==== HTTP request ---- PUT /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status <<'EOF' { ""kind"": ""ImageStream"", ""apiVersion"": ""image.openshift.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.ImageStream |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |201 Created|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-image.openshift.io-v1-namespaces-namespace-imagestreams-name-status]] === Patch status of a ImageStream in a namespace Partially update status of the specified ImageStream ==== HTTP request ---- PATCH /apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/image.openshift.io/v1/namespaces/$NAMESPACE/imagestreams/$NAME/status <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ImageStream |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.ImageStream |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",16252,True,3042.6257965008767,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.containers { /* import flash.display.DisplayObject; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import mx.containers.dividedBoxClasses.BoxDivider; import mx.core.EdgeMetrics; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.IInvalidating; */ import mx.core.IUIComponent; import mx.core.UIComponent; /* import mx.core.mx_internal; import mx.events.ChildExistenceChangedEvent; import mx.events.DividerEvent; import mx.managers.CursorManager; import mx.managers.CursorManagerPriority; import mx.styles.IStyleManager2; import mx.styles.StyleManager; use namespace mx_internal; */ //-------------------------------------- // Events //-------------------------------------- /** * Dispatched multiple times as the user drags any divider. * * The dividerDrag event is dispatched * after the dividerPress event * and before the dividerRelease event. * * @eventType mx.events.DividerEvent.DIVIDER_DRAG * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Event(name=""dividerDrag"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user presses any divider in this container. * * The dividerPress event is dispatched * before any dividerDrag events are dispatched. * * @eventType mx.events.DividerEvent.DIVIDER_PRESS * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Event(name=""dividerPress"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user releases a divider. * * The dividerRelease event is dispatched * after the dividerDrag events, * but before the container's children are resized. * The divider's x and y properties are not updated until * after this event is triggered. As a result, a call to * hDividerBox.getDividerAt(0).x will return * the value of the original x position of the first divider. If you want the * position of the divider after the move, you can access it when the * DividerBox's updateComplete event has been triggered. * * @eventType mx.events.DividerEvent.DIVIDER_RELEASE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Event(name=""dividerRelease"", type=""mx.events.DividerEvent"")] /** * A DividedBox container measures and lays out its children * horizontally or vertically in exactly the same way as a * Box container, but it inserts * draggable dividers in the gaps between the children. * Users can drag any divider to resize the children on each side. * *

    The DividedBox class is the base class for the more commonly used * HDividedBox and VDividedBox classes.

    * *

    The direction property of a DividedBox container, inherited * from Box container, determines whether it has horizontal * or vertical layout.

    * *

    A DividedBox, HDividedBox, or VDividedBox container has the following default sizing characteristics:

    * * * * * * * * * * * * * * * * * *
    CharacteristicDescription
    Default sizeVertical DividedBox Height is large enough to hold all of its children at the default or explicit * heights of the children, plus any vertical gap between the children, plus the top and bottom padding of the * container. The width is the default or explicit width of the widest child, plus the left and right padding of * the container. *
    Horizontal DividedBox Width is large enough to hold all of its children at the * default or explicit widths of the children, plus any horizontal gap between the children, plus the left and * right padding of the container. Height is the default or explicit height of the tallest child * plus the top and bottom padding of the container.
    Default padding0 pixels for the top, bottom, left, and right values.
    Default gap10 pixels for the horizontal and vertical gaps.
    * * @mxml * *

    The <mx:DividedBox> tag inherits all of the tag * attributes of its superclass, and adds the following tag attributes:

    * *
     *  <mx:DividedBox
     *    Properties
     *    liveDragging=""false|true""
     *    resizeToContent=""false|true""
     *  
     *    Styles
     *    dividerAffordance=""6""
     *    dividerAlpha=""0.75""
     *    dividerColor=""0x6F7777""
     *    dividerSkin=""'mx.skins.BoxDividerSkin' symbol in Assets.swf""
     *    dividerThickness=""3""
     *    horizontalDividerCursor=""'mx.skins.cursor.HBoxDivider' symbol in Assets.swf""
     *    verticalDividerCursor=""'mx.skins.cursor.VBoxDivider' symbol in Assets.swf""
     * 
     *    Events
     *    dividerPress=""No default""
     *    dividerDrag=""No default""
     *    dividerRelease=""No default""
     *    >
     *      ...
     *      child tags
     *      ...
     *  </mx:DividedBox>
     *  
    * * @see mx.containers.HDividedBox * @see mx.containers.VDividedBox * * @includeExample examples/DividedBoxExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DividedBox extends Box { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static const PROXY_DIVIDER_INDEX:int = 999; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function DividedBox() { super(); // addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler); // addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, // childRemoveHandler); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Container for holding divider objects. */ private var dividerLayer:UIComponent = null; /** * @private */ //mx_internal var activeDivider:BoxDivider; /** * @private */ private var activeDividerIndex:int = -1; /** * @private */ private var activeDividerStartPosition:Number; /** * @private */ private var dragStartPosition:Number; /** * @private */ private var dragDelta:Number; /** * @private */ private var oldChildSizes:Array /* of ChildSizeInfo */; /** * @private */ private var minDelta:Number; /** * @private */ private var maxDelta:Number; /** * @private * Only allow a single divider to move at a time. */ private var dontCoalesceDividers:Boolean; /** * @private */ //private var cursorID:int = CursorManager.NO_CURSOR; /** * @private * We'll measure ourselves once and then store the results here * for the lifetime of the DividedBox. */ private var dbMinWidth:Number; private var dbMinHeight:Number; private var dbPreferredWidth:Number; private var dbPreferredHeight:Number; /** * @private */ private var layoutStyleChanged:Boolean = false; /** * @private */ private var _resizeToContent:Boolean = false; /** * @private * Number of children with their includeInLayout set to true. The rest of * the children don't count. */ private var numLayoutChildren:int = 0; //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- /** * @private */ // override public function set moduleFactory(moduleFactory:IFlexModuleFactory):void // { // super.moduleFactory = moduleFactory; // // styleManager.registerSizeInvalidatingStyle(""dividerAffordance""); // styleManager.registerSizeInvalidatingStyle(""dividerThickness""); // } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // direction //---------------------------------- /** * @private */ override public function set direction(value:String):void { if (super.direction != value) { super.direction = value; // Need to invalidate all our dividers // if (dividerLayer) // { // for (var i:int = 0; i < dividerLayer.numChildren; i++) // getDividerAt(i).invalidateDisplayList(); // } } } //---------------------------------- // dividerClass //---------------------------------- /** * The class for the divider between the children. * * @default mx.containers.dividedBoxClasses.BoxDivider * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // protected var dividerClass:Class = BoxDivider; //---------------------------------- // liveDragging //---------------------------------- // [Inspectable(category=""General"")] /** * If true, the children adjacent to a divider * are continuously resized while the user drags it. * If false, they are not resized * until the user releases the divider. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public var liveDragging:Boolean = false; //---------------------------------- // numDividers //---------------------------------- /** * The number of dividers. * The count is always numChildren - 1. * * @return The number of dividers. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get numDividers():int { // if (dividerLayer) // if (!liveDragging && activeDivider) // return dividerLayer.numChildren-1; // else // return dividerLayer.numChildren; // else // return 0; trace(""numDividers not implemented""); return 0; } //---------------------------------- // resizeToContent //---------------------------------- /** * If true, the DividedBox automatically resizes to the size * of its children. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get resizeToContent():Boolean { return _resizeToContent; } /** * @private */ public function set resizeToContent(value:Boolean):void { if (value != _resizeToContent) { _resizeToContent = value; if (value) invalidateSize(); } } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private * Override of the measure method of Box. * *

    This function is almost identical to the Box version except * that more extensive testing of the min, max * boundary conditions is performed. This is because the DividedBox allows * default values to be less than the min value of a control.

    */ // override protected function measure():void // { // super.measure(); // // // We only measure ourselves once, since as we change the // // size of children, they in turn change the preferred sizes // // // // We need to copy the cached values into the measured fields // // again to handle the case where scaleX or scaleY is not 1.0. // // When the ViewStack is zoomed, code in UIComponent.measureSizes // // scales the measuredWidth/Height values every time that // // measureSizes is called. (Bug 100749) // if (!isNaN(dbPreferredWidth) && !_resizeToContent && !layoutStyleChanged) // { // measuredMinWidth = dbMinWidth; // measuredMinHeight = dbMinHeight; // measuredWidth = dbPreferredWidth; // measuredHeight = dbPreferredHeight; // return; // } // // layoutStyleChanged = false; // // var isVertical:Boolean = this.isVertical(); // var minWidth:Number = 0; // var minHeight:Number = 0; // var preferredWidth:Number = 0; // var preferredHeight:Number = 0; // // var n:int = numChildren; // for (var i:int = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // var prefW:Number = child.getExplicitOrMeasuredWidth(); // var prefH:Number = child.getExplicitOrMeasuredHeight(); // // var minW:Number = child.minWidth; // var minH:Number = child.minHeight; // // var wFlex:Boolean = !isNaN(child.percentWidth); // var hFlex:Boolean = !isNaN(child.percentHeight); // // // Make sure we take the lowest of the low, since pref < min. // var smallestMinW:Number = Math.min(prefW, minW); // var smallestMinH:Number = Math.min(prefH, minH); // // if (isVertical) // { // minWidth = Math.max(wFlex ? minW : prefW, minWidth); // preferredWidth = Math.max(prefW, preferredWidth); // minHeight += hFlex ? smallestMinH : prefH; // preferredHeight += prefH; // } // else // { // minWidth += wFlex ? smallestMinW : prefW; // preferredWidth += prefW; // minHeight = Math.max(hFlex ? minH : prefH, minHeight); // preferredHeight = Math.max(prefH, preferredHeight); // } // } // // var wPadding:Number = layoutObject.widthPadding(numLayoutChildren); // var hPadding:Number = layoutObject.heightPadding(numLayoutChildren); // // measuredMinWidth = dbMinWidth = minWidth + wPadding; // measuredMinHeight = dbMinHeight = minHeight + hPadding; // measuredWidth = dbPreferredWidth = preferredWidth + wPadding; // measuredHeight = dbPreferredHeight = preferredHeight + hPadding; // } /** * @private */ // override protected function updateDisplayList(unscaledWidth:Number, // unscaledHeight:Number):void // { // var n:int; // var i:int; // // // This method gets called while dragging a divider, // // but we don't want to do anything then. // if (!liveDragging && activeDivider) // { // n = numChildren; // for (i = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // // Clear out measured min/max // // so super.layout() doesn't use them. // child.measuredMinWidth = 0; // child.measuredMinHeight = 0; // } // return; // } // // // Before we allow layout, let's clear out any measured min // // values of our children so that they don't restrict us. // // We only honour explicitly set mins/maxs. // // We also try to remove any excess space, but tweaking // // the % values on the flexible components. // preLayoutAdjustment(); // // // Let Box lay out the children. // super.updateDisplayList(unscaledWidth, unscaledHeight); // // postLayoutAdjustment(); // // // Lay out the dividers. // if (!dividerLayer) // return; // // var vm:EdgeMetrics = viewMetrics; // // dividerLayer.x = vm.left; // dividerLayer.y = vm.top; // // var prevChild:IUIComponent = null; // var dividerIndex:int = 0; // n = numChildren; // for (i = 0; i < n; i++) // { // child = UIComponent(getChildAt(i)); // if (child.includeInLayout) // { // if (prevChild) // { // layoutDivider(dividerIndex, unscaledWidth, unscaledHeight, prevChild, child); // dividerIndex++; // } // prevChild = child; // } // } // } /** * @private */ // override protected function scrollChildren():void // { // super.scrollChildren(); // // // Scroll divider layer. // if (contentPane && dividerLayer) // dividerLayer.scrollRect = contentPane.scrollRect; // } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Returns a reference to the specified BoxDivider object * in this DividedBox container or null if it doesn't exist. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @return A BoxDivider object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public function getDividerAt(i:int):BoxDivider // { // if (dividerLayer) { // // Check whether this is a valid divider index. // if (i < 0 || i >= dividerLayer.numChildren) // return null; // else // return BoxDivider(dividerLayer.getChildAt(i)); // } // else { // return null; // } // } /** * Move a specific divider a given number of pixels. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @param amt The number of pixels to move the divider. * A negative number can be specified in order to move * a divider up or left. The divider movement is * constrained in the same manner as if a user * had moved it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public function moveDivider(i:int, amt:Number):void // { // // Check whether this is a valid divider index. // if (i < 0 || i >= numDividers) // return; // // // Make sure the user is not currently dragging. // if (activeDividerIndex >= 0) // return; // // // We have to first hit the children if we haven't // // yet done so since the first movement . // // // Mimic a divider moving. // activeDividerIndex = i; // // // Store away child sizes, // // then determine the limits on our movement. // cacheChildSizes(); // computeMinAndMaxDelta(); // dragDelta = limitDelta(amt); // // // Now update the children sizes accordingly. // adjustChildSizes(); // // invalidateSize(); // invalidateDisplayList(); // // // Reset the divider tracking stuff. // resetDividerTracking(); // } /** * @private */ // private function createDivider(i:int):BoxDivider // { // // Create separate layer for holding divider objects. // if (!dividerLayer) // { // dividerLayer = UIComponent(rawChildren.addChild(new UIComponent())); // } // // var divider:BoxDivider = BoxDivider(new dividerClass()); // dividerLayer.addChild(divider); // // // if we are creating the active divider bring the divider layer // // to the top most so that users can see the divider line over // // the other children // if (i == PROXY_DIVIDER_INDEX) // { // rawChildren.setChildIndex(dividerLayer, // rawChildren.numChildren-1); // } // // // Tell BoxDivider to use DividedBox's styles, // // unless we are sliding the divider; in that case, // // use the styles of the divider we are sliding. // var basedOn:IFlexDisplayObject = (i == PROXY_DIVIDER_INDEX) ? // getDividerAt(activeDividerIndex) : // this; // // divider.styleName = basedOn; // // divider.owner = this; // // return divider; // } /** * @private */ private function layoutDivider(i:int, unscaledWidth:Number, unscaledHeight:Number, prevChild:IUIComponent, nextChild:IUIComponent):void { // The mouse-over thickness of the divider is normally determined // by the dividerAffordance style, and the visible thickness is // normally determined by the dividerThickness style, assuming that // the relationship thickness <= affordance <= gap applies. But if // one of the other five orderings applies, here is a table of what // happens: // // divider divider horizontalGap/ dividerWidth/ visible width/ // Thickness Affordance verticalGap dividerHeight visible height // // 4 6 8 6 4 // 4 8 6 6 4 // 6 4 8 6 6 // 6 8 4 4 4 // 8 4 6 6 6 // 8 6 4 4 4 // var divider:BoxDivider = BoxDivider(getDividerAt(i)); // // var vm:EdgeMetrics = viewMetrics; // // var verticalGap:Number = getStyle(""verticalGap""); // var horizontalGap:Number = getStyle(""horizontalGap""); // // var thickness:Number = divider.getStyle(""dividerThickness""); // var affordance:Number = divider.getStyle(""dividerAffordance""); // // if (isVertical()) // { // var dividerHeight:Number = affordance; // // dividerHeight is the mouse-over height, // // not necessarily the visible height. // // // The specified affordance should be greater than the thickness. // // But if it isn't, use the thickness instead to determine the // // divider height. // if (dividerHeight < thickness) // dividerHeight = thickness; // // // Don't let the divider overlap the children. // if (dividerHeight > verticalGap) // dividerHeight = verticalGap; // // divider.setActualSize(unscaledWidth - vm.left - vm.right, dividerHeight); // // divider.move(vm.left, // Math.round((prevChild.y + prevChild.height + // nextChild.y - dividerHeight) / 2)); // } // else // { // var dividerWidth:Number = affordance; // // dividerWidth is the mouse-over width, // // not necessarily the visible width. // // // The specified affordance should be greater than the thickness. // // But if it isn't, use the thickness instead to determine the // // divider width. // if (dividerWidth < thickness) // dividerWidth = thickness; // // // Don't let the divider overlap the children. // if (dividerWidth > horizontalGap) // dividerWidth = horizontalGap; // // divider.setActualSize(dividerWidth, unscaledHeight - vm.top - vm.bottom); // // divider.move(Math.round((prevChild.x + prevChild.width + // nextChild.x - dividerWidth) / 2), // vm.top); // } // // divider.invalidateDisplayList(); } /** * @private */ // mx_internal function changeCursor(divider:BoxDivider):void // { // if (cursorID == CursorManager.NO_CURSOR) // { // // If a cursor skin has been set for the specified BoxDivider, // // use it. Otherwise, use the cursor skin for the DividedBox. // var cursorClass:Class = isVertical() ? // getStyle(""verticalDividerCursor"") as Class : // getStyle(""horizontalDividerCursor"") as Class; // // cursorID = cursorManager.setCursor(cursorClass, // CursorManagerPriority.HIGH, 0, 0); // } // } /** * @private */ // mx_internal function restoreCursor():void // { // if (cursorID != CursorManager.NO_CURSOR) // { // cursorManager.removeCursor(cursorID); // cursorID = CursorManager.NO_CURSOR; // } // } /** * @private */ // mx_internal function getDividerIndex(divider:BoxDivider):int // { // var n:int = numChildren; // for (var i:int = 0; i < n - 1; i++) // { // if (getDividerAt(i) == divider) // return i; // } // return -1; // } /** * @private */ // private function getMousePosition(event:MouseEvent):Number // { // var point:Point = new Point(event.stageX, event.stageY); // point = globalToLocal(point); // return isVertical() ? point.y : point.x; // } /** * @private */ // mx_internal function startDividerDrag(divider:BoxDivider, // trigger:MouseEvent):void // { // // Make sure the user is not currently dragging. // if (activeDividerIndex >= 0) // return; // // activeDividerIndex = getDividerIndex(divider); // // var event:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_PRESS); // event.dividerIndex = activeDividerIndex; // dispatchEvent(event); // // if (liveDragging) // activeDivider = divider; // else // { // activeDivider = createDivider(PROXY_DIVIDER_INDEX); // activeDivider.visible = false; // activeDivider.state = DividerState.DOWN; // activeDivider.setActualSize(divider.width, divider.height); // activeDivider.move(divider.x, divider.y); // activeDivider.visible = true; // divider.state = DividerState.UP; // } // // if (isVertical()) // activeDividerStartPosition = activeDivider.y; // else // activeDividerStartPosition = activeDivider.x; // // dragStartPosition = getMousePosition(trigger); // dragDelta = 0; // // cacheChildSizes(); // adjustChildSizes(); // // computeMinAndMaxDelta(); // // systemManager.getSandboxRoot().addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); // systemManager.deployMouseShields(true); // } /** * @private * Store away some important information about * each child for us to use while we move the divider. */ // private function cacheSizes():void // { // oldChildSizes = []; // empty array // // var vertical:Boolean = isVertical(); // // var smallest:Number = Number.MAX_VALUE; // use a big number // // var n:int = numChildren; // for (var i:int = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // if (!child.includeInLayout) // continue; // // var sz:Number = vertical ? child.height : child.width; // // var mx:Number = vertical ? child.maxHeight : child.maxWidth; // // var umn:Number = vertical ? // child.explicitMinHeight : // child.explicitMinWidth; // avoid measured values // // // A NaN min means 0. // var mn:Number = (isNaN(umn)) ? 0 : umn; // // // Compute these for later use. // var dMin:Number = Math.max(0, sz - mn); // var dMax:Number = Math.max(0, mx - sz); // // if (sz > 0 && sz < smallest) // smallest = sz; // // oldChildSizes.push(new ChildSizeInfo(sz, mn, mx, dMin, dMax)); // } // // // Remember the smallest child size we saw. // oldChildSizes.push(new ChildSizeInfo((smallest == Number.MAX_VALUE) ? 1 : smallest)); // } /** * @private */ // private function cacheChildSizes():void // { // oldChildSizes = []; // clear or store // // cacheSizes(); // } /** * @private */ // private function mouseMoveHandler(event:MouseEvent):void // { // dragDelta = limitDelta(getMousePosition(event) - dragStartPosition); // // var dividerEvent:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_DRAG); // dividerEvent.dividerIndex = activeDividerIndex; // dividerEvent.delta = dragDelta; // dispatchEvent(dividerEvent); // // if (liveDragging) // { // adjustChildSizes(); // // invalidateDisplayList(); // // updateDisplayList(unscaledWidth, unscaledHeight); // } // else // { // if (isVertical()) // activeDivider.move(0, activeDividerStartPosition + dragDelta); // else // activeDivider.move(activeDividerStartPosition + dragDelta, 0); // } // } /** * @private * * @param trigger May be null if the event is not a MouseEvent but * a mouse event from another sandbox. */ // mx_internal function stopDividerDrag(divider:BoxDivider, // trigger:MouseEvent):void // { // if (trigger) // dragDelta = limitDelta(getMousePosition(trigger) - dragStartPosition); // // var event:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_RELEASE); // event.dividerIndex = activeDividerIndex; // event.delta = dragDelta; // dispatchEvent(event); // // if (!liveDragging) // { // if (dragDelta == 0) // getDividerAt(activeDividerIndex).state = DividerState.OVER; // // if (activeDivider) // dividerLayer.removeChild(activeDivider); // activeDivider = null; // // adjustChildSizes(); // // invalidateSize(); // invalidateDisplayList(); // } // // resetDividerTracking(); // systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); // systemManager.deployMouseShields(false); // } /** * @private */ // private function resetDividerTracking():void // { // activeDivider = null; // activeDividerIndex = -1; // activeDividerStartPosition = NaN; // dragStartPosition = NaN; // dragDelta = NaN; // oldChildSizes = null; // minDelta = NaN; // maxDelta = NaN; // } /** * @private * Determine the maximum amount of movement that * a divider, i, can move both up and down. * * We base this calculation on the amount of * travel that each divider supports, assuming * that as one divider reaches its limits, the next * divider will move. In this way dividers will * cascade. */ // private function computeAllowableMovement(at:int):void // { // // We break the computation into two loops, // // so that we can calc min and max travel // // independently as one would move the divider // // either up or down. // var deltaMinAbove:Number = 0; // var deltaMaxAbove:Number = 0; // var deltaMinBelow:Number = 0; // var deltaMaxBelow:Number = 0; // // var n:int = numLayoutChildren; // var i:int; // var child:ChildSizeInfo; // // if (at < 0) // return; // // for (i = at; i >= 0; i--) // { // child = ChildSizeInfo(oldChildSizes[i]); // // deltaMinAbove += (dontCoalesceDividers && deltaMinAbove) ? // 0 : child.deltaMin; // // deltaMaxAbove += (dontCoalesceDividers && deltaMaxAbove) ? // 0 : child.deltaMax; // } // // for (i = at + 1; i < n; i++) // { // child = ChildSizeInfo(oldChildSizes[i]); // // deltaMinBelow += (dontCoalesceDividers && deltaMinBelow) ? // 0 : child.deltaMin; // // deltaMaxBelow += (dontCoalesceDividers && deltaMaxBelow) ? // 0 : child.deltaMax; // } // // // Now the maximum movement we can have if // // the divider is moved up is equal to the // // smaller of how much we can shrink all // // components above our divider or the // // maximum of how much the components below // // our divider can grow. Similarly for the // // divider moving in the opposite direction. // var deltaUp:Number = Math.min(deltaMinAbove, deltaMaxBelow); // var deltaDn:Number = Math.min(deltaMinBelow, deltaMaxAbove); // // // deltaUp needs to be in -ve in order for our // // update logic to work // minDelta = -deltaUp; // maxDelta = deltaDn; // } /** * @private */ // private function computeMinAndMaxDelta():void // { // computeAllowableMovement(activeDividerIndex); // } /** * @private */ // private function limitDelta(delta:Number):Number // { // if (delta < minDelta) // delta = minDelta; // else if (delta > maxDelta) // delta = maxDelta; // // // Make sure it is not fractional, // // otherwise we lose pixels. (Bug 87339) // delta = Math.round(delta); // return delta; // } /** * @private * We distribute the delta space in the same * fashion that we calculated it. That is we * start at the divider and give out space * until we hit a limit on the component or * we run out of space to distribute. * We need to do this in both directions since * in one direction we are shrinking and * in the other we are growing. */ // private function distributeDelta():void // { // // if there is no movement of divider we need not // // do any child resizing. // if (!dragDelta) // return; // // var vertical:Boolean = isVertical(); // var n:int = numLayoutChildren; // var k:int = activeDividerIndex; // var smallest:Number = oldChildSizes[n].size - // Math.abs(dragDelta); // smallest possible child size // // if (smallest <= 0 || isNaN(smallest)) // smallest = 1; // // var i:int; // var size:ChildSizeInfo; // var move:Number; // var newSize:Number; // var child:IUIComponent; // var childSize:Number; // // // Find the index of the child before the active divider // var activeDividerChildIndex:int = -1; // var dividerIndex:int = -1; // while (dividerIndex < activeDividerIndex) // { // if (UIComponent(getChildAt(++activeDividerChildIndex)).includeInLayout) // ++dividerIndex; // } // // // Distribute space starting from the center and // // moving upwards. // var curChildIndex:int = activeDividerChildIndex; // var amt:Number = dragDelta; // for (i = k; i >= 0; i--) // { // // If dragDelta -ve => shrink upper components // // otherwise grow them. // size = ChildSizeInfo(oldChildSizes[i]); // move = (amt < 0) ? // -Math.min(-amt, size.deltaMin) : // Math.min(amt, size.deltaMax); // // // Adjust the component and reduce the remaining delta // newSize = size.size + move; // amt -= move; // // // Find the previous child included in the layout // do // { // child = IUIComponent(getChildAt(curChildIndex--)); // } // while (!child.includeInLayout); // // // Adjust the child size. // childSize = (newSize / smallest) * 100; // // if (vertical) // child.percentHeight = childSize; // else // child.percentWidth = childSize; // // // Force a re-measure. // if (child is IInvalidating) // IInvalidating(child).invalidateSize(); // } // // // assert(amt == 0) // // // Now do the same distribution but moving downwards. // curChildIndex = activeDividerChildIndex + 1; // amt = dragDelta; // for (i = k + 1; i < n; i++) // { // // If dragDelta -ve => grow lower components // // otherwise shrink them. // size = ChildSizeInfo(oldChildSizes[i]); // move = (amt < 0) ? // Math.min(-amt, size.deltaMax) : // -Math.min(amt, size.deltaMin); // // // Adjust the component and reduce the remaining delta. // newSize = size.size + move; // amt += move; // // // Find the next child included in the layout // do // { // child = IUIComponent(getChildAt(curChildIndex++)); // } // while (!child.includeInLayout); // // childSize = (newSize / smallest) * 100; // // if (vertical) // child.percentHeight = childSize; // else // child.percentWidth = childSize; // // // Force a re-measure. // if (child is IInvalidating) // IInvalidating(child).invalidateSize(); // } // } /** * @private * For 1.5 we normalize all children to the smallest one * So that we can remove n-1 children and still guarantee * one child can consume 100%. * Also we support the concept of fixed sized children, * which allows us to have one or more children be rigid * in the DividedBox in this case, the dividers above * and below the fixed component move in unison. */ // private function adjustChildSizes():void // { // distributeDelta(); // } /** * @private * Algorithm employed pre-layout to ensure that * we don't leave any dangling space and to ensure * that only explicit min/max values are honored. * * We first compute the sum of %'s across all * children to ensure that we have at least 100%. * If so, we are done. If not, then we attempt * to attach the remaining amount to the last * component, if not, then we distribute the * percentages evenly across all % components. * */ // private function preLayoutAdjustment():void // { // // Calculate the total % // var vertical:Boolean = isVertical(); // // var totalPerc:Number = 0; // var percCount:Number = 0; // // var n:int = numChildren; // var i:int; // var child:IUIComponent; // var perc:Number; // // for (i = 0; i < n; i++) // { // child = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // // Clear out measured min/max // // so super.layout() doesn't use them. // child.measuredMinWidth = 0; // child.measuredMinHeight = 0; // // perc = vertical ? child.percentHeight : child.percentWidth; // // if (!isNaN(perc)) // { // totalPerc += perc; // percCount++; // } // } // // // during preLayoutAdjustment, we make some changes to the children's // // widths and heights. We keep track of the original values in postLayoutChanges // // so we can later go back and reset them so another layout pass is working // // with the correct values rather than these modified values. // postLayoutChanges = []; // var changeObject:Object; // // // No flexible children, so we make the last one 100%. // if (totalPerc == 0 && percCount == 0) // { // // Everyone is fixed and we can give 100% to the last // // included in layout one without concern. // for (i = n-1; i >= 0; i--) // { // child = UIComponent(getChildAt(i)); // if (child.includeInLayout) // { // // create a changeObject to keep track of the original values // // that this child had for width and height // changeObject = {child: child}; // if (vertical) // { // // we know there's no percentHeight originally // if (child.explicitHeight) // changeObject.explicitHeight = child.explicitHeight; // else // changeObject.percentHeight = NaN; // // child.percentHeight = 100; // } // else // { // // we know there's no percentWidth originally // if (child.explicitWidth) // changeObject.explicitWidth = child.explicitWidth; // else if (child.percentWidth) // changeObject.percentWidth = NaN; // // child.percentWidth = 100; // } // postLayoutChanges.push(changeObject); // break; // } // } // } // else if (totalPerc < 100) // { // // We have some %s but they don't total to 100, so lets // // distribute the delta across all of them and in the // // meantime normalize all %s to unscaledHeight/Width. // // The normalization takes care of the case where any one // // of the components hits a min/max limit on their size, // // which could result in the others filling less than 100%. // var delta:Number = Math.ceil((100 - totalPerc) / percCount); // for (i = 0; i < n; i++) // { // child = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // changeObject = {child: child}; // // if (vertical) // { // perc = child.percentHeight; // if (!isNaN(perc)) // { // changeObject.percentHeight = child.percentHeight; // postLayoutChanges.push(changeObject); // // child.percentHeight = (perc + delta) * unscaledHeight; // } // } // else // { // perc = child.percentWidth; // if (!isNaN(perc)) // { // changeObject.percentWidth = child.percentWidth; // postLayoutChanges.push(changeObject); // // child.percentWidth = (perc + delta) * unscaledWidth; // } // } // } // } // // // OK after all this magic we still can't guarantee that the space is // // entirely filled. For example, all percent components hit their max // // values. In this case, the layout will include empty space at the end, // // and once the divider is touched, the non-percent based components // // will be converted into percent based ones and fill the remaining // // space. It seems to me that this scenario is highly unlikely. // // Thus I've choosen the route of stretching the percent based // // components and not touching the explicitly sized or default // // sized ones. // // // // Another option would be to stretch the default sized components // // either in addition to the percent based ones or instead of. // // This seemed a little odd to me as the user never indicated // // that these components are to be stretched initially, so in the end // // I choose to tweak the components that the user has indicated // // as being stretchable. // } /** * @private * During preLayoutAdjustment, we make some changes to the children's * widths and heights. We keep track of the original values in postLayoutChanges * so we can later go back and reset them so another layout pass is working * with the correct values rather than these modified values. */ // private var postLayoutChanges:Array; /** * @private * Post layout work. In preLayoutAdjustment() * sometimes we set a child's percentWidth/percentHeight. * postLayoutAdjustment() will reset the child's width or height * back to what it was. */ // private function postLayoutAdjustment():void // { // // each object has a child property and may have a set of width/height // // properties that it would like to be set // var len:int = postLayoutChanges.length; // for (var i:int = 0; i < len; i++) // { // var changeObject:Object = postLayoutChanges[i]; // // if (changeObject.percentWidth !== undefined) // changeObject.child.percentWidth = changeObject.percentWidth; // // if (changeObject.percentHeight !== undefined) // changeObject.child.percentHeight = changeObject.percentHeight; // // if (changeObject.explicitWidth !== undefined) // changeObject.child.explicitWidth = changeObject.explicitWidth; // // if (changeObject.explicitHeight !== undefined) // changeObject.child.explicitHeight = changeObject.explicitHeight; // } // postLayoutChanges = null; // } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ // private function childAddHandler(event:ChildExistenceChangedEvent):void // { // var child:DisplayObject = event.relatedObject; // // child.addEventListener(""includeInLayoutChanged"", // child_includeInLayoutChangedHandler); // // if (!IUIComponent(child).includeInLayout) // return; // // numLayoutChildren++; // // if (numLayoutChildren > 1) // createDivider(numLayoutChildren - 2); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // } /** * @private */ // private function childRemoveHandler(event:ChildExistenceChangedEvent):void // { // var child:DisplayObject = event.relatedObject; // // child.removeEventListener(""includeInLayoutChanged"", // child_includeInLayoutChangedHandler); // // if (!IUIComponent(child).includeInLayout) // return; // // numLayoutChildren--; // // if (numLayoutChildren > 0) // dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // invalidateSize(); // } /** * @private * When a child's includeInLayout changes, we either remove or add a * divider. */ // private function child_includeInLayoutChangedHandler(event:Event):void // { // var child:UIComponent = UIComponent(event.target); // // if (child.includeInLayout && ++numLayoutChildren > 1) // createDivider(numLayoutChildren - 2); // // else if (!child.includeInLayout && --numLayoutChildren > 0) // dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // invalidateSize(); // } } } //////////////////////////////////////////////////////////////////////////////// // // Helper class: ChildSizeInfo // //////////////////////////////////////////////////////////////////////////////// /** * @private */ //class ChildSizeInfo //{ // //-------------------------------------------------------------------------- // // // // Constructor // // // //-------------------------------------------------------------------------- // // /** // * @private // */ // public function ChildSizeInfo(size:Number, // min:Number = 0, max:Number = 0, // deltaMin:Number = 0, deltaMax:Number = 0) // { // super(); // // this.size = size; // this.min = min; // this.max = max; // this.deltaMin = deltaMin; // this.deltaMax = deltaMax; // } // // //-------------------------------------------------------------------------- // // // // Properties // // // //-------------------------------------------------------------------------- // // //---------------------------------- // // deltaMin // //---------------------------------- // // /** // * @private // */ // public var deltaMin:Number; // // //---------------------------------- // // deltaMax // //---------------------------------- // // /** // * @private // */ // public var deltaMax:Number; // // //---------------------------------- // // min // //---------------------------------- // // /** // * @private // */ // public var min:Number; // // //---------------------------------- // // max // //---------------------------------- // // /** // * @private // */ // public var max:Number; // // //---------------------------------- // // size // //---------------------------------- // // /** // * @private // */ // public var size:Number; //} ",12352,False,2341.7994138412378,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc //// = Writing REST Services with RESTEasy Reactive include::./attributes.adoc[] :jaxrsapi: https://javadoc.io/doc/javax.ws.rs/javax.ws.rs-api/2.1.1 :jaxrsspec: /specs/jaxrs/2.1/index.html :jdkapi: https://docs.oracle.com/en/java/javase/11/docs/api/java.base :mutinyapi: https://smallrye.io/smallrye-mutiny/apidocs :httpspec: https://tools.ietf.org/html/rfc7231 :jsonpapi: https://javadoc.io/doc/javax.json/javax.json-api/1.1.4 :vertxapi: https://javadoc.io/static/io.vertx/vertx-core/4.1.0 :resteasy-reactive-api: https://javadoc.io/doc/io.quarkus.resteasy.reactive/resteasy-reactive/2.0.0.Final :resteasy-reactive-common-api: https://javadoc.io/doc/io.quarkus.resteasy.reactive/resteasy-reactive-common/2.0.0.Final This guide explains how to write REST Services with RESTEasy Reactive in Quarkus. == What is RESTEasy Reactive? RESTEasy Reactive is a new link:{jaxrsspec}[JAX-RS] implementation written from the ground up to work on our common https://vertx.io/[Vert.x] layer and is thus fully reactive, while also being very tightly integrated with Quarkus and consequently moving a lot of work to build time. You should be able to use it in place of any JAX-RS implementation, but on top of that it has great performance for both blocking and non-blocking endpoints, and a lot of new features on top of what JAX-RS provides. == Writing endpoints === Getting started Add the following import to your build file: [source,xml,role=""primary asciidoc-tabs-target-sync-cli asciidoc-tabs-target-sync-maven""] .pom.xml ---- io.quarkus quarkus-resteasy-reactive ---- [source,gradle,role=""secondary asciidoc-tabs-target-sync-gradle""] .build.gradle ---- implementation(""io.quarkus:quarkus-resteasy-reactive"") ---- You can now write your first endpoint in the `org.acme.rest.Endpoint` class: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("""") public class Endpoint { @GET public String hello() { return ""Hello, World!""; } } ---- === Terminology REST:: https://en.wikipedia.org/wiki/Representational_state_transfer[REpresentational State Transfer] Endpoint:: Java method which is called to serve a REST call URL / URI (Uniform Resource Locator / Identifier):: Used to identify the location of REST resources (https://tools.ietf.org/html/rfc7230#section-2.7[specification]) Resource:: Represents your domain object. This is what your API serves and modifies. Also called an `entity` in JAX-RS. Representation:: How your resource is represented on the wire, can vary depending on content types Content type:: Designates a particular representation (also called a media type), for example `text/plain` or `application/json` HTTP:: Underlying wire protocol for routing REST calls (see https://tools.ietf.org/html/rfc7230[HTTP specifications]) HTTP request:: the request part of the HTTP call, consisting of an HTTP method, a target URI, headers and an optional message body HTTP response:: the response part of the HTTP call, consisting of an HTTP response status, headers and an optional message body === Declaring endpoints: URI mapping Any class annotated with a link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation can have its methods exposed as REST endpoints, provided they have an HTTP method annotation (see below). That link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation defines the URI prefix under which those methods will be exposed. It can be empty, or contain a prefix such as `rest` or `rest/V1`. Each exposed endpoint method can in turn have another link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation which adds to its containing class annotation. For example, this defines a `rest/hello` endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path(""rest"") public class Endpoint { @Path(""hello"") @GET public String hello() { return ""Hello, World!""; } } ---- See <> for more information about URI mapping. You can set the root path for all rest endpoints using the `@ApplicationPath` annotation, as shown below. [source,java] ---- package org.acme.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath(""/api"") public static class MyApplication extends Application { } ---- This will cause all rest endpoints to be resolve relative to `/api`, so the endpoint above with `@Path(""rest"")` would be accessible at `/api/rest/. You can also set the `quarkus.rest.path` build time property to set the root path if you don't want to use an annotation. === Declaring endpoints: HTTP methods Each endpoint method must be annotated with one of the following annotations, which defines which HTTP method will be mapped to the method: .Table HTTP method annotations |=== |Annotation|Usage |link:{jaxrsapi}/javax/ws/rs/GET.html[`@GET`] |Obtain a resource representation, should not modify state, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.1[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/HEAD.html[`@HEAD`] |Obtain metadata about a resource, similar to `GET` with no body (link:{httpspec}#section-4.3.2[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/POST.html[`@POST`] |Create a resource and obtain a link to it (link:{httpspec}#section-4.3.3[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/PUT.html[`@PUT`] |Replace a resource or create one, should be link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.4[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/DELETE.html[`@DELETE`] |Delete an existing resource, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.5[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/OPTIONS.html[`@OPTIONS`] |Obtain information about a resource, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.7[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/PATCH.html[`@PATCH`] |Update a resource, or create one, not link:{httpspec}#section-4.2.2[idempotent] (https://tools.ietf.org/html/rfc5789#section-2[HTTP docs]) |=== You can also declare other HTTP methods by declaring them as an annotation with the link:{jaxrsapi}/javax/ws/rs/HttpMethod.html[`@HttpMethod`] annotation: [source,java] ---- package org.acme.rest; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.ws.rs.HttpMethod; import javax.ws.rs.Path; @Retention(RetentionPolicy.RUNTIME) @HttpMethod(""FROMAGE"") @interface FROMAGE { } @Path("""") public class Endpoint { @FROMAGE public String hello() { return ""Hello, Cheese World!""; } } ---- === Declaring endpoints: representation / content types Each endpoint method may consume or produce specific resource representations, which are indicated by the HTTP link:{httpspec}#section-3.1.1.5[`Content-Type`] header, which in turn contains link:{httpspec}#section-3.1.1.1[MIME (Media Type)] values, such as the following: - `text/plain` which is the default for any endpoint returning a `String`. - `text/html` for HTML (such as with xref:qute.adoc[Qute templating]) - `application/json` for a <> - `text/*` which is a sub-type wildcard for any text media type - `\\*/*` which is a wildcard for any media type You may annotate your endpoint class with the link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces`] or link:{jaxrsapi}/javax/ws/rs/Consumes.html[`@Consumes`] annotations, which allow you to specify one or more media types that your endpoint may accept as HTTP request body or produce as HTTP response body. Those class annotations apply to each method. Any method may also be annotated with the link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces`] or link:{jaxrsapi}/javax/ws/rs/Consumes.html[`@Consumes`] annotations, in which case they override any eventual class annotation. The link:{jaxrsapi}/javax/ws/rs/core/MediaType.html[`MediaType`] class has many constants you can use to point to specific pre-defined media types. See <> for more information. === Accessing request parameters [[request-parameters]] NOTE: don't forget to configure your compiler to generate parameter name information with `-parameters` (javac) or `` or `` (https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#parameters[Maven]). The following HTTP request elements may be obtained by your endpoint method: .Table HTTP request parameter annotations |=== |HTTP element|Annotation|Usage |[[path-parameter]]Path parameter |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`] (or nothing) |URI template parameter (simplified version of the https://tools.ietf.org/html/rfc6570[URI Template specification]), see <> for more information. |Query parameter |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestQuery.html[`@RestQuery`] |The value of an https://tools.ietf.org/html/rfc3986#section-3.4[URI query parameter] |Header |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestHeader.html[`@RestHeader`] |The value of an https://tools.ietf.org/html/rfc7230#section-3.2[HTTP header] |Cookie |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestCookie.html[`@RestCookie`] |The value of an https://tools.ietf.org/html/rfc6265#section-4.2[HTTP cookie] |Form parameter |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`] |The value of an https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST[HTTP URL-encoded FORM] |Matrix parameter |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestMatrix.html[`@RestMatrix`] |The value of an https://tools.ietf.org/html/rfc3986#section-3.3[URI path segment parameter] |=== For each of those annotations, you may specify the name of the element they refer to, otherwise they will use the name of the annotated method parameter. If a client made the following HTTP call: [source,http] ---- POST /cheeses;variant=goat/tomme?age=matured HTTP/1.1 Content-Type: application/x-www-form-urlencoded Cookie: level=hardcore X-Cheese-Secret-Handshake: fist-bump smell=strong ---- Then you could obtain all the various parameters with this endpoint method: [source,java] ---- package org.acme.rest; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.jboss.resteasy.reactive.RestCookie; import org.jboss.resteasy.reactive.RestForm; import org.jboss.resteasy.reactive.RestHeader; import org.jboss.resteasy.reactive.RestMatrix; import org.jboss.resteasy.reactive.RestPath; import org.jboss.resteasy.reactive.RestQuery; @Path(""/cheeses/{type}"") public class Endpoint { @POST public String allParams(@RestPath String type, @RestMatrix String variant, @RestQuery String age, @RestCookie String level, @RestHeader(""X-Cheese-Secret-Handshake"") String secretHandshake, @RestForm String smell) { return type + ""/"" + variant + ""/"" + age + ""/"" + level + ""/"" + secretHandshake + ""/"" + smell; } } ---- NOTE: the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`] annotation is optional: any parameter whose name matches an existing URI template variable will be automatically assumed to have link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestPath.html[`@RestPath`]. You can also use any of the JAX-RS annotations link:{jaxrsapi}/javax/ws/rs/PathParam.html[`@PathParam`], link:{jaxrsapi}/javax/ws/rs/QueryParam.html[`@QueryParam`], link:{jaxrsapi}/javax/ws/rs/HeaderParam.html[`@HeaderParam`], link:{jaxrsapi}/javax/ws/rs/CookieParam.html[`@CookieParam`], link:{jaxrsapi}/javax/ws/rs/FormParam.html[`@FormParam`] or link:{jaxrsapi}/javax/ws/rs/MatrixParam.html[`@MatrixParam`] for this, but they require you to specify the parameter name. See <> for more advanced use-cases. === Declaring URI parameters [[uri-parameters]] You can declare URI parameters and use regular expressions in your path, so for instance the following endpoint will serve requests for `/hello/stef/23` and `/hello` but not `/hello/stef/0x23`: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path(""hello"") public class Endpoint { @Path(""{name}/{age:\\\\d+}"") @GET public String personalisedHello(String name, int age) { return ""Hello "" + name + "" is your age really "" + age + ""?""; } @GET public String genericHello() { return ""Hello stranger""; } } ---- === Accessing the request body Any method parameter with no annotation will receive the method body.footnote:[Unless it is a <> or a <>.], after it has been mapped from its HTTP representation to the Java type of the parameter. The following parameter types will be supported out of the box: [[resource-types]] .Table Request body parameter type |=== |Type|Usage |link:{jdkapi}/java/io/File.html[`File`] |The entire request body in a temporary file |`byte[]` |The entire request body, not decoded |`char[]` |The entire request body, decoded |link:{jdkapi}/java/lang/String.html[`String`] |The entire request body, decoded |link:{jdkapi}/java/io/InputStream.html[`InputStream`] |The request body in a blocking stream |link:{jdkapi}/java/io/Reader.html[`Reader`] |The request body in a blocking stream |All Java primitives and their wrapper classes |Java primitive types |link:{jdkapi}/java/math/BigDecimal.html[`BigDecimal`], link:{jdkapi}/java/math/BigInteger.html[`BigInteger`] |Large integers and decimals. |link:{jsonpapi}/javax/json/JsonArray.html[`JsonArray`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonObject`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonStructure`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonValue`] |JSON value types |link:{vertxapi}io/vertx/core/buffer/Buffer.html[`Buffer`] |Vert.x Buffer |any other type |Will be <> |=== NOTE: You can add support for more <>. === Handling Multipart Form data To handle HTTP requests that have `multipart/form-data` as their content type, RESTEasy Reactive introduces the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/MultipartForm.html[`@MultipartForm`] annotation. Let us look at an example of its use. Assuming an HTTP request containing a file upload and a form value containing a string description need to be handled, we could write a POJO that will hold this information like so: [source,java] ---- import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.PartType; import org.jboss.resteasy.reactive.RestForm; import org.jboss.resteasy.reactive.multipart.FileUpload; public class FormData { @RestForm @PartType(MediaType.TEXT_PLAIN) public String description; @RestForm(""image"") public FileUpload file; } ---- The `name` field will contain the data contained in the part of HTTP request called `description` (because link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`] does not define a value, the field name is used), while the `file` field will contain data about the uploaded file in the `image` part of HTTP request. NOTE: link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/multipart/FileUpload.html[`FileUpload`] provides access to various metadata of the uploaded file. If however all you need is a handle to the uploaded file, `java.nio.file.Path` or `java.io.File` could be used. NOTE: When access to all uploaded files without specifying the form names is needed, RESTEasy Reactive allows the use of `@RestForm List`, where it is important to **not** set a name for the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestForm.html[`@RestForm`] annotation. NOTE: link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/PartType.html[`@PartType`] is used to aid in deserialization of the corresponding part of the request into the desired Java type. It is very useful when for example the corresponding body part is JSON and needs to be converted to a POJO. This POJO could be used in a Resource method like so: [source,java] ---- import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.MultipartForm; @Path(""multipart"") public class Endpoint { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.MULTIPART_FORM_DATA) @Path(""form"") public String form(@MultipartForm FormData formData) { // return something } } ---- The use of link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/MultipartForm.html[`@MultipartForm`] as method parameter makes RESTEasy Reactive handle the request as a multipart form request. TIP: The use of `@MultipartForm` is actually unnecessary as RESTEasy Reactive can infer this information from the use of `@Consumes(MediaType.MULTIPART_FORM_DATA)` WARNING: When handling file uploads, it is very important to move the file to permanent storage (like a database, a dedicated file system or a cloud storage) in your code that handles the POJO. Otherwise, the file will no longer be accessible when the request terminates. Moreoever if `quarkus.http.body.delete-uploaded-files-on-end` is set to true, Quarkus will delete the uploaded file when the HTTP response is sent. If the setting is disabled, the file will reside on the file system of the server (in the directory defined by the `quarkus.http.body.uploads-directory` configuration option), but as the uploaded files are saved with a UUID file name and no additional metadata is saved, these files are essentially a random dump of files. Similarly, RESTEasy Reactive can produce Multipart Form data to allow users download files from the server. For example, we could write a POJO that will hold the information we want to expose as: [source,java] ---- import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.PartType; import org.jboss.resteasy.reactive.RestForm; public class DownloadFormData { @RestForm String name; @RestForm @PartType(MediaType.APPLICATION_OCTET_STREAM) File file; } ---- And then expose this POJO via a Resource like so: [source,java] ---- import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path(""multipart"") public class Endpoint { @GET @Produces(MediaType.MULTIPART_FORM_DATA) @Path(""file"") public DownloadFormData getFile() { // return something } } ---- WARNING: For the time being, returning Multipart data is limited to be blocking endpoints. === Returning a response body In order to return an HTTP response, simply return the resource you want from your method. The method return type and its optional content type will be used to decide how to serialise it to the HTTP response (see <> for more advanced information). You can return any of the pre-defined types that you can read from the <>, and any other type will be mapped <>. In addition, the following return types are also supported: .Table Additional response body parameter type |=== |Type|Usage |link:{jdkapi}/java/nio/file/Path.html[`Path`] |The contents of the file specified by the given path |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/PathPart.html[`PathPart`] |The partial contents of the file specified by the given path |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/FilePart.html[`FilePart`] |The partial contents of a file |link:{vertxapi}/io/vertx/core/file/AsyncFile.html[`AsyncFile`] |Vert.x AsyncFile, which can be in full, or partial |=== Alternately, you can also return a <> such as link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`], link:{mutinyapi}/io/smallrye/mutiny/Multi.html[`Multi`] or link:{jdkapi}/java/util/concurrent/CompletionStage.html[`CompletionStage`] that resolve to one of the mentioned return types. === Setting other response properties ==== Manually setting the response If you need to set more properties on the HTTP response than just the body, such as the status code or headers, you can make your method return `org.jboss.resteasy.reactive.RestResponse` from a resource method. An example of this could look like: [source,java] ---- package org.acme.rest; import java.time.Duration; import java.time.Instant; import java.util.Date; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import org.jboss.resteasy.reactive.RestResponse; import org.jboss.resteasy.reactive.RestResponse.ResponseBuilder; @Path("""") public class Endpoint { @GET public RestResponse hello() { // HTTP OK status with text/plain content type return ResponseBuilder.ok(""Hello, World!"", MediaType.TEXT_PLAIN_TYPE) // set a response header .header(""X-FroMage"", ""Camembert"") // set the Expires response header to two days from now .expires(Date.from(Instant.now().plus(Duration.ofDays(2)))) // send a new cookie .cookie(new NewCookie(""Flavour"", ""praliné"")) // end of builder API .build(); } } ---- NOTE: You can also use the JAX-RS type link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] but it is not strongly typed to your entity. ==== Using annotations Alternatively, if you only need to set the status code and / or HTTP headers with static values, you can use `@org.jboss.resteasy.reactive.ResponseStatus` and /or `ResponseHeader` respectively. An example of this could look like: [source,java] ---- package org.acme.rest; import org.jboss.resteasy.reactive.Header; import org.jboss.resteasy.reactive.ResponseHeaders; import org.jboss.resteasy.reactive.ResponseStatus; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("""") public class Endpoint { @ResponseStatus(201) @ResponseHeader(name = ""X-FroMage"", value = ""Camembert"") @GET public String hello() { return ""Hello, World!""; } } ---- === Async/reactive support [[reactive]] If your endpoint method needs to accomplish an asynchronous or reactive task before being able to answer, you can declare your method to return the link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] type (from https://smallrye.io/smallrye-mutiny/[Mutiny]), in which case the current HTTP request will be automatically suspended after your method, until the returned link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] instance resolves to a value, which will be mapped to a response exactly according to the previously described rules: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.mutiny.Uni; @Path(""escoffier"") public class Endpoint { @GET public Uni culinaryGuide() { return Book.findByIsbn(""978-2081229297""); } } ---- This allows you to not block the event-loop thread while the book is being fetched from the database, and allows Quarkus to serve more requests until your book is ready to be sent to the client and terminate this request. Check out our <> for more information. The link:{jdkapi}/java/util/concurrent/CompletionStage.html[`CompletionStage`] return type is also supported. === Streaming support If you want to stream your response element by element, you can make your endpoint method return a link:{mutinyapi}/io/smallrye/mutiny/Multi.html[`Multi`] type (from https://smallrye.io/smallrye-mutiny/[Mutiny]). This is especially useful for streaming text or binary data. This example, using https://github.com/quarkiverse/quarkus-reactive-messaging-http[Reactive Messaging HTTP] shows how to stream text data: [source,java] ---- package org.acme.rest; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.eclipse.microprofile.reactive.messaging.Channel; import io.smallrye.mutiny.Multi; @Path(""logs"") public class Endpoint { @Inject @Channel(""log-out"") Multi logs; @GET public Multi streamLogs() { return logs; } } ---- NOTE: Response filters are not invoked on streamed responses, because they would give a false impression that you can set headers or HTTP status codes, which is not true after the initial response. === Server-Sent Event (SSE) support If you want to stream JSON objects in your response, you can use https://html.spec.whatwg.org/multipage/server-sent-events.html[Server-Sent Events] by just annotating your endpoint method with link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces(MediaType.SERVER_SENT_EVENTS)`] and specifying that each element should be <> with `@RestStreamElementType(MediaType.APPLICATION_JSON)`. [source,java] ---- package org.acme.rest; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.RestStreamElementType; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import io.smallrye.reactive.messaging.annotations.Channel; @Path(""escoffier"") public class Endpoint { // Inject our Book channel @Inject @Channel(""book-out"") Multi books; @GET // Send the stream over SSE @Produces(MediaType.SERVER_SENT_EVENTS) // Each element will be sent as JSON @RestStreamElementType(MediaType.APPLICATION_JSON) public Multi stream() { return books; } } ---- === Controlling HTTP Caching features RESTEasy Reactive provides the link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/Cache.html[`@Cache`] and link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/NoCache.html[`@NoCache`] annotations to facilitate handling HTTP caching semantics, i.e. setting the 'Cache-Control' HTTP header. These annotations can be placed either on a Resource Method or a Resource Class (in which case it applies to all Resource Methods of the class that do *not* contain the same annotation) and allow users to return domain objects and not have to deal with building up the `Cache-Control` HTTP header explicitly. While link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/Cache.html[`@Cache`] builds a complex `Cache-Control` header, link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/NoCache.html[`@NoCache`] is a simplified notation to say that you don't want anything cached; i.e. `Cache-Control: nocache`. NOTE: More information on the `Cache-Control` header and be found in link:https://datatracker.ietf.org/doc/html/rfc7234[RFC 7234] === Accessing context objects [[context-objects]] There are a number of contextual objects that the framework will give you, if your endpoint method takes parameters of the following type: .Table Context object |=== |Type|Usage |link:{jaxrsapi}/javax/ws/rs/core/HttpHeaders.html[`HttpHeaders`] |All the request headers |link:{jaxrsapi}/javax/ws/rs/container/ResourceInfo.html[`ResourceInfo`] |Information about the current endpoint method and class (requires reflection) |link:{jaxrsapi}/javax/ws/rs/core/SecurityContext.html[`SecurityContext`] |Access to the current user and roles |link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/SimpleResourceInfo.html[`SimpleResourceInfo`] |Information about the current endpoint method and class (no reflection required) |link:{jaxrsapi}/javax/ws/rs/core/UriInfo.html[`UriInfo`] |Provides information about the current endpoint and application URI |link:{jaxrsapi}/javax/ws/rs/core/Application.html[`Application`] |Advanced: Current JAX-RS application class |link:{jaxrsapi}/javax/ws/rs/core/Configuration.html[`Configuration`] |Advanced: Configuration about the deployed JAX-RS application |link:{jaxrsapi}/javax/ws/rs/ext/Providers.html[`Providers`] |Advanced: Runtime access to JAX-RS providers |link:{jaxrsapi}/javax/ws/rs/core/Request.html[`Request`] |Advanced: Access to the current HTTP method and <> |link:{jaxrsapi}/javax/ws/rs/core/ResourceContext.html[`ResourceContext`] |Advanced: access to instances of endpoints |link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/spi/ServerRequestContext.html[`ServerRequestContext`] |Advanced: RESTEasy Reactive access to the current request/response |link:{jaxrsapi}/javax/ws/rs/sse/Sse.html[`Sse`] |Advanced: Complex SSE use-cases |link:{vertxapi}/io/vertx/core/http/HttpServerRequest.html[`HttpServerRequest`] |Advanced: Vert.x HTTP Request |link:{vertxapi}/io/vertx/core/http/HttpServerResponse.html[`HttpServerResponse`] |Advanced: Vert.x HTTP Response |=== For example, here is how you can return the name of the currently logged-in user: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { @GET public String userName(SecurityContext security) { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- You can also inject those context objects using https://javadoc.io/static/javax.inject/javax.inject/1/javax/inject/Inject.html[`@Inject`] on fields of the same type: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { @Inject SecurityContext security; @GET public String userName() { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- Or even on your endpoint constructor: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { SecurityContext security; Endpoint(SecurityContext security) { this.security = security; } @GET public String userName() { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- === JSON serialisation [[json]] Instead of importing `io.quarkus:quarkus-resteasy-reactive`, you can import either of the following modules to get support for JSON: .Table Context object |=== |GAV|Usage |`io.quarkus:quarkus-resteasy-reactive-jackson` |https://github.com/FasterXML/jackson[Jackson support] |`io.quarkus:quarkus-resteasy-reactive-jsonb` |https://eclipse-ee4j.github.io/jsonb-api/[JSON-B support] |=== In both cases, importing those modules will allow HTTP message bodies to be read from JSON and serialised to JSON, for <>. ==== Advanced Jackson-specific features When using the `quarkus-resteasy-reactive-jackson` extension there are some advanced features that RESTEasy Reactive supports. [[secure-serialization]] ===== Secure serialization When used with Jackson to perform JSON serialization, RESTEasy Reactive provides the ability to limit the set of fields that are serialized based on the roles of the current user. This is achieved by simply annotating the fields (or getters) of the POJO being returned with `@io.quarkus.resteasy.reactive.jackson.SecureField`. A simple example could be the following: Assume we have a POJO named `Person` which looks like so: [source,java] ---- package org.acme.rest; import io.quarkus.resteasy.reactive.jackson.SecureField; public class Person { @SecureField(rolesAllowed = ""admin"") private final Long id; private final String first; private final String last; public Person(Long id, String first, String last) { this.id = id; this.first = first; this.last = last; } public Long getId() { return id; } public String getFirst() { return first; } public String getLast() { return last; } } ---- A very simple JAX-RS Resource that uses `Person` could be: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path(""person"") public class Person { @Path(""{id}"") @GET public Person getPerson(Long id) { return new Person(id, ""foo"", ""bar""); } } ---- Assuming security has been set up for the application (see our xref:security.adoc[guide] for more details), when a user with the `admin` role performs an HTTP GET on `/person/1` they will receive: [source,json] ---- { ""id"": 1, ""first"": ""foo"", ""last"": ""bar"" } ---- as the response. Any user however that does not have the `admin` role will receive: [source,json] ---- { ""first"": ""foo"", ""last"": ""bar"" } ---- NOTE: No additional configuration needs to be applied for this secure serialization to take place. However, users can use the `@io.quarkus.resteasy.reactive.jackson.EnableSecureSerialization` and `@io.quarkus.resteasy.reactive.jackson.DisableSecureSerialization` annotation to opt-in or out for specific JAX-RS Resource classes or methods. ===== @JsonView support JAX-RS methods can be annotated with https://fasterxml.github.io/jackson-annotations/javadoc/2.10/com/fasterxml/jackson/annotation/JsonView.html[@JsonView] in order to customize the serialization of the returned POJO, on a per method-basis. This is best explained with an example. A typical use of `@JsonView` is to hide certain fields on certain methods. In that vein, let's define two views: [source,java] ---- public class Views { public static class Public { } public static class Private extends Public { } } ---- Let's assume we have the `User` POJO on which we want to hide some field during serialization. A simple example of this is: [source,java] ---- public class User { @JsonView(Views.Private.class) public int id; @JsonView(Views.Public.class) public String name; } ---- Depending on the JAX-RS method that returns this user, we might want to exclude the `id` field from serialization - for example you might want an insecure method to not expose this field. The way we can achieve that in RESTEasy Reactive is shown in the following example: [source,java] ---- @JsonView(Views.Public.class) @GET @Path(""/public"") public User userPublic() { return testUser(); } @JsonView(Views.Private.class) @GET @Path(""/private"") public User userPrivate() { return testUser(); } ---- When the result the `userPublic` method is serialized, the `id` field will not be contained in the response as the `Public` view does not include it. The result of `userPrivate` however will include the `id` as expected when serialized. ===== Completely customized per method serialization There are times when you need to completely customize the serialization of a POJO on a per JAX-RS method basis. For such use cases, the `@io.quarkus.resteasy.reactive.jackson.CustomSerialization` annotation is a great tool, as it allows you to configure a per-method `com.fasterxml.jackson.databind.ObjectWriter` which can be configured at will. Here is an example use case: [source,java] ---- @CustomSerialization(UnquotedFields.class) @GET @Path(""/invalid-use-of-custom-serializer"") public User invalidUseOfCustomSerializer() { return testUser(); } ---- where `UnquotedFields` is a `BiFunction` defined as so: [source,java] ---- public static class UnquotedFields implements BiFunction { @Override public ObjectWriter apply(ObjectMapper objectMapper, Type type) { return objectMapper.writer().without(JsonWriteFeature.QUOTE_FIELD_NAMES); } } ---- Essentially what this class does is force Jackson to not include quotes in the field names. It is important to note that this customization is only performed for the serialization of the JAX-RS methods that use `@CustomSerialization(UnquotedFields.class)`. === XML serialisation [[xml]] To enable XML support, add the `quarkus-resteasy-reactive-jaxb` extension to your project. .Table Context object |=== |GAV|Usage |`io.quarkus:quarkus-resteasy-reactive-jaxb` |https://javaee.github.io/jaxb-v2/[XML support] |=== Importing this module will allow HTTP message bodies to be read from XML and serialised to XML, for <>. == More advanced usage Here are some more advanced topics that you may not need to know about initially, but could prove useful for more complex use cases. === Execution model, blocking, non-blocking [[execution-model]] RESTEasy Reactive is implemented using two main thread types: - Event-loop threads: which are responsible, among other things, for reading bytes from the HTTP request and writing bytes back to the HTTP response - Worker threads: they are pooled and can be used to offload long-running operations The event-loop threads (also called IO threads) are responsible for actually performing all the IO operations in an asynchronous way, and to trigger any listener interested in the completion of those IO operations. By default, the thread RESTEasy Reactive will run endpoint methods on depends on the signature of the method. If a method returns one of the following types then it is considered non-blocking, and will be run on the IO thread by default: - `io.smallrye.mutiny.Uni` - `io.smallrye.mutiny.Multi` - `java.util.concurrent.CompletionStage` - `org.reactivestreams.Publisher` - Kotlin `suspended` methods This 'best guess' approach means that the majority of operations will run on the correct thread by default. If you are writing reactive code then your method will generally return one of these types, and will be executed on the IO thread. If you are writing blocking code your methods will generally return the result directly, and these will be run on a worker thread. You can override this behaviour using the https://javadoc.io/doc/io.smallrye.common/smallrye-common-annotation/1.5.0/io/smallrye/common/annotation/Blocking.html[`@Blocking`] and https://javadoc.io/doc/io.smallrye.common/smallrye-common-annotation/1.5.0/io/smallrye/common/annotation/NonBlocking.html[`@NonBlocking`] annotations. This can be applied at the method, class or `javax.ws.rs.core.Application` level. The example below will override the default behaviour and always run on a worker thread, even though it returns a `Uni`. [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.common.annotation.Blocking; @Path(""yawn"") public class Endpoint { @Blocking @GET public Uni blockingHello() throws InterruptedException { // do a blocking operation Thread.sleep(1000); return Uni.createFrom().item(""Yaaaawwwwnnnnnn…""); } } ---- Most of the time, there are ways to achieve the same blocking operations in an asynchronous/reactive way, using https://smallrye.io/smallrye-mutiny/[Mutiny], http://hibernate.org/reactive/[Hibernate Reactive] or any of the xref:quarkus-reactive-architecture.adoc#quarkus-extensions-enabling-reactive[Quarkus Reactive extensions] for example: [source,java] ---- package org.acme.rest; import java.time.Duration; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.mutiny.Uni; @Path(""yawn"") public class Endpoint { @GET public Uni blockingHello() throws InterruptedException { return Uni.createFrom().item(""Yaaaawwwwnnnnnn…"") // do a non-blocking sleep .onItem().delayIt().by(Duration.ofSeconds(2)); } } ---- If a method or class is annotated with `javax.transaction.Transactional` then it will also be treated as a blocking method. This is because JTA is a blocking technology, and is generally used with other blocking technology such as Hibernate and JDBC. An explicit `@Blocking` or `@NonBlocking` on the class will override this behaviour. ==== Overriding the default behaviour If you want to override the default behaviour you can annotate a `javax.ws.rs.core.Application` subclass in your application with `@Blocking` or `@NonBlocking`, and this will set the default for every method that does not have an explicit annotation. Behaviour can still be overridden on a class or method level by annotating them directly, however all endpoints without an annotation will now follow the default, no matter their method signature. === Exception mapping If your application needs to return non-nominal HTTP codes in error cases, the best is to throw exceptions that will result in the proper HTTP response being sent by the framework using link:{jaxrsapi}/javax/ws/rs/WebApplicationException.html[`WebApplicationException`] or any of its subtypes: [source,java] ---- package org.acme.rest; import javax.ws.rs.BadRequestException; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.Path; @Path(""fromages/{fromage}"") public class Endpoint { @GET public String findFromage(String fromage) { if(fromage == null) // send a 400 throw new BadRequestException(); if(!fromage.equals(""camembert"")) // send a 404 throw new NotFoundException(""Unknown cheese: "" + fromage); return ""Camembert is a very nice cheese""; } } ---- If your endpoint method is delegating calls to another service layer which does not know of JAX-RS, you need a way to turn service exceptions to an HTTP response, and you can do that using the link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerExceptionMapper.html[`@ServerExceptionMapper`] annotation on a method, with one parameter of the exception type you want to handle, and turning that exception into a link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] (or a link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni>`]): [source,java] ---- package org.acme.rest; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.BadRequestException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import org.jboss.resteasy.reactive.server.ServerExceptionMapper; import org.jboss.resteasy.reactive.RestResponse; class UnknownCheeseException extends RuntimeException { public final String name; public UnknownCheeseException(String name) { this.name = name; } } @ApplicationScoped class CheeseService { private static final Map cheeses = Map.of(""camembert"", ""Camembert is a very nice cheese"", ""gouda"", ""Gouda is acceptable too, especially with cumin""); public String findCheese(String name) { String ret = cheeses.get(name); if(ret != null) return ret; throw new UnknownCheeseException(name); } } @Path(""fromages/{fromage}"") public class Endpoint { @Inject CheeseService cheeses; @ServerExceptionMapper public RestResponse mapException(UnknownCheeseException x) { return RestResponse.status(Response.Status.NOT_FOUND, ""Unknown cheese: "" + x.name); } @GET public String findFromage(String fromage) { if(fromage == null) // send a 400 throw new BadRequestException(); return cheeses.findCheese(fromage); } } ---- NOTE: exception mappers defined in REST endpoint classes will only be called if the exception is thrown in the same class. If you want to define global exception mappers, simply define them outside a REST endpoint class: [source,java] ---- package org.acme.rest; import org.jboss.resteasy.reactive.server.ServerExceptionMapper; import org.jboss.resteasy.reactive.RestResponse; class ExceptionMappers { @ServerExceptionMapper public RestResponse mapException(UnknownCheeseException x) { return RestResponse.status(Response.Status.NOT_FOUND, ""Unknown cheese: "" + x.name); } } ---- You can also declare link:{jaxrsspec}#exceptionmapper[exception mappers in the JAX-RS way]. Your exception mapper may declare any of the following parameter types: .Table Exception mapper parameters |=== |Type|Usage |An exception type |Defines the exception type you want to handle |Any of the <> | |link:{jaxrsapi}/javax/ws/rs/container/ContainerRequestContext.html[`ContainerRequestContext`] |A context object to access the current request |=== It may declare any of the following return types: .Table Exception mapper return types |=== |Type|Usage |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] |The response to send to the client when the exception occurs |link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] or link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] |An asynchronous response to send to the client when the exception occurs |=== === Request or response filters You can declare functions which are invoked in the following phases of the request processing: - Before the endpoint method is identified: pre-routing request filter - After routing, but before the endpoint method is called: normal request filter - After the endpoint method is called: response filter These filters allow you to do various things such as examine the request URI, HTTP method, influence routing, look or change request headers, abort the request, or modify the response. Request filters can be declared with the link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerRequestFilter.html[`@ServerRequestFilter`] annotation: [source,java] ---- import java.util.Optional; class Filters { @ServerRequestFilter(preMatching = true) public void preMatchingFilter(ContainerRequestContext requestContext) { // make sure we don't lose cheese lovers if(""yes"".equals(requestContext.getHeaderString(""Cheese""))) { requestContext.setRequestUri(URI.create(""/cheese"")); } } @ServerRequestFilter public Optional> getFilter(ContainerRequestContext ctx) { // only allow GET methods for now if(ctx.getMethod().equals(HttpMethod.GET)) { return Optional.of(RestResponse.status(Response.Status.METHOD_NOT_ALLOWED)); } return Optional.empty(); } } ---- [IMPORTANT] ==== Request filters are usually executed on the same thread that the method that handles the request will be executed. That means that if the method servicing the request is annotated with `@Blocking`, then the filters will also be run on the worker thread. If the method is annotated with `@NonBlocking` (or is not annotated at all), then the filters will also be run on the same event-loop thread. If however a filter needs to be run on the event-loop despite the fact that the method servicing the request will be run on a worker thread, then `@ServerRequestFilter(nonBlocking=true)` can be used. Note however, that these filters need to be run before **any** filter that does not use that setting and would run on a worker thread. ==== Similarly, response filters can be declared with the link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/ServerResponseFilter.html[`@ServerResponseFilter`] annotation: [source,java] ---- class Filters { @ServerResponseFilter public void getFilter(ContainerResponseContext responseContext) { Object entity = responseContext.getEntity(); if(entity instanceof String) { // make it shout responseContext.setEntity(((String)entity).toUpperCase()); } } } ---- You can also link:{jaxrsspec}#filters[declare request and response filters in the JAX-RS way]. Your filters may declare any of the following parameter types: .Table Filter parameters |=== |Type|Usage |Any of the <> | |link:{jaxrsapi}/javax/ws/rs/container/ContainerRequestContext.html[`ContainerRequestContext`] |A context object to access the current request |link:{jaxrsapi}/javax/ws/rs/container/ContainerResponseContext.html[`ContainerResponseContext`] |A context object to access the current response |link:{jdkapi}/java/lang/Throwable.html[`Throwable`] |Any thrown exception, or `null` (only for response filters) |=== It may declare any of the following return types: .Table Filter return types |=== |Type|Usage |link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] |The response to send to the client instead of continuing the filter chain, or `null` if the filter chain should proceed |link:{jdkapi}/java/util/Optional.html[`Optional>`] or link:{jdkapi}/java/util/Optional.html[`Optional`] |An optional response to send to the client instead of continuing the filter chain, or an empty value if the filter chain should proceed |link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni>`] or link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] |An asynchronous response to send to the client instead of continuing the filter chain, or `null` if the filter chain should proceed |=== NOTE: You can restrict the Resource methods for which a filter runs, by using link:{jaxrsapi}/javax/ws/rs/NameBinding.html[`@NameBinding`] meta-annotations. === Readers and Writers: mapping entities and HTTP bodies [[readers-writers]] Whenever your endpoint methods return a object (of when they return a link:{resteasy-reactive-common-api}/org/jboss/resteasy/reactive/RestResponse.html[`RestResponse`] or link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] with an entity), RESTEasy Reactive will look for a way to map that into an HTTP response body. Similarly, whenever your endpoint method takes an object as parameter, we will look for a way to map the HTTP request body into that object. This is done via a pluggable system of link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyReader.html[`MessageBodyReader`] and link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyWriter.html[`MessageBodyWriter`] interfaces, which are responsible for defining which Java type they map from/to, for which media types, and how they turn HTTP bodies to/from Java instances of that type. For example, if we have our own `FroMage` type on our endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; class FroMage { public String name; public FroMage(String name) { this.name = name; } } @Path(""cheese"") public class Endpoint { @GET public FroMage sayCheese() { return new FroMage(""Cheeeeeese""); } @PUT public void addCheese(FroMage fromage) { System.err.println(""Received a new cheese: "" + fromage.name); } } ---- Then we can define how to read and write it with our body reader/writers, annotated with link:{jaxrsapi}/javax/ws/rs/ext/Provider.html[`@Provider`]: [source,java] ---- package org.acme.rest; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; @Provider public class FroMageBodyHandler implements MessageBodyReader, MessageBodyWriter { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == FroMage.class; } @Override public void writeTo(FroMage t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write((""[FroMageV1]"" + t.name) .getBytes(StandardCharsets.UTF_8)); } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == FroMage.class; } @Override public FroMage readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { String body = new String(entityStream.readAllBytes(), StandardCharsets.UTF_8); if(body.startsWith(""[FroMageV1]"")) return new FroMage(body.substring(11)); throw new IOException(""Invalid fromage: "" + body); } } ---- If you want to get the most performance our of your writer, you can extend the link:{resteasy-reactive-api}/org/jboss/resteasy/reactive/server/spi/ServerMessageBodyWriter.html[`ServerMessageBodyWriter`] instead of link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyWriter.html[`MessageBodyWriter`] where you will be able to use less reflection and bypass the blocking IO layer: [source,java] ---- package org.acme.rest; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo; import org.jboss.resteasy.reactive.server.spi.ServerMessageBodyWriter; import org.jboss.resteasy.reactive.server.spi.ServerRequestContext; @Provider public class FroMageBodyHandler implements MessageBodyReader, ServerMessageBodyWriter { // … @Override public boolean isWriteable(Class type, ResteasyReactiveResourceInfo target, MediaType mediaType) { return type == FroMage.class; } @Override public void writeResponse(FroMage t, ServerRequestContext context) throws WebApplicationException, IOException { context.serverResponse().end(""[FroMageV1]"" + t.name); } } ---- NOTE: You can restrict which content-types your reader/writer apply to by adding link:{jaxrsapi}/javax/ws/rs/Consumes.html[`Consumes`]/link:{jaxrsapi}/javax/ws/rs/Produces.html[`Produces`] annotations on your provider class. === Reader and Writer interceptors Just as you can intercept requests and responses, you can also intercept readers and writers, by extending the link:{jaxrsapi}/javax/ws/rs/ext/ReaderInterceptor.html[`ReaderInterceptor`] or link:{jaxrsapi}/javax/ws/rs/ext/WriterInterceptor.html[`WriterInterceptor`] on a class annotated with link:{jaxrsapi}/javax/ws/rs/ext/Provider.html[`@Provider`]. If we look at this endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; @Path(""cheese"") public class Endpoint { @GET public String sayCheese() { return ""Cheeeeeese""; } @PUT public void addCheese(String fromage) { System.err.println(""Received a new cheese: "" + fromage); } } ---- We can add reader and writer interceptors like this: [source,java] ---- package org.acme.rest; import java.io.IOException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.ReaderInterceptor; import javax.ws.rs.ext.ReaderInterceptorContext; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; @Provider public class FroMageIOInterceptor implements ReaderInterceptor, WriterInterceptor { @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { System.err.println(""Before writing "" + context.getEntity()); context.proceed(); System.err.println(""After writing "" + context.getEntity()); } @Override public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException { System.err.println(""Before reading "" + context.getGenericType()); Object entity = context.proceed(); System.err.println(""After reading "" + entity); return entity; } } ---- === Parameter mapping All <> can be declared as link:{jdkapi}/java/lang/String.html[`String`], but also any of the following types: - Types for which a link:{jaxrsapi}/javax/ws/rs/ext/ParamConverter.html[`ParamConverter`] is available via a registered link:{jaxrsapi}/javax/ws/rs/ext/ParamConverterProvider.html[`ParamConverterProvider`]. - Primitive types. - Types that have a constructor that accepts a single link:{jdkapi}/java/lang/String.html[`String`] argument. - Types that have a static method named `valueOf` or `fromString` with a single link:{jdkapi}/java/lang/String.html[`String`] argument that return an instance of the type. If both methods are present then `valueOf` will be used unless the type is an `enum` in which case `fromString` will be used. - link:{jdkapi}/java/util/List.html[`List`], link:{jdkapi}/java/util/Set.html[`Set`], or link:{jdkapi}/java/util/SortedSet.html[`SortedSet`], where `T` satisfies any above criterion. The following example illustrates all those possibilities: [source,java] ---- package org.acme.rest; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import javax.ws.rs.ext.Provider; import org.jboss.resteasy.reactive.RestQuery; @Provider class MyConverterProvider implements ParamConverterProvider { @Override public ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) { // declare a converter for this type if(rawType == Converter.class) { return (ParamConverter) new MyConverter(); } return null; } } // this is my custom converter class MyConverter implements ParamConverter { @Override public Converter fromString(String value) { return new Converter(value); } @Override public String toString(Converter value) { return value.value; } } // this uses a converter class Converter { String value; Converter(String value) { this.value = value; } } class Constructor { String value; // this will use the constructor public Constructor(String value) { this.value = value; } } class ValueOf { String value; private ValueOf(String value) { this.value = value; } // this will use the valueOf method public static ValueOf valueOf(String value) { return new ValueOf(value); } } @Path(""hello"") public class Endpoint { @Path(""{converter}/{constructor}/{primitive}/{valueOf}"") @GET public String convertions(Converter converter, Constructor constructor, int primitive, ValueOf valueOf, @RestQuery List list) { return converter + ""/"" + constructor + ""/"" + primitive + ""/"" + valueOf + ""/"" + list; } } ---- ==== Handling dates RESTEasy Reactive supports the use of the implementations of `java.time.Temporal` (like `java.time.LocalDateTime`) as query, path or form params. Furthermore it provides the `@org.jboss.resteasy.reactive.DateFormat` annotation which can be used to set a custom expected pattern (otherwise the JDK's default format for each type is used implicitly). === Preconditions https://tools.ietf.org/html/rfc7232[HTTP allows requests to be conditional], based on a number of conditions, such as: - Date of last resource modification - A resource tag, similar to a hash code of the resource to designate its state or version Let's see how you can do conditional request validation using the link:{jaxrsapi}/javax/ws/rs/core/Request.html[`Request`] context object: [source,java] ---- package org.acme.rest; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; import java.util.Date; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path(""conditional"") public class Endpoint { // It's important to keep our date on seconds because that's how it's sent to the // user in the Last-Modified header private Date date = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS)); private int version = 1; private EntityTag tag = new EntityTag(""v1""); private String resource = ""Some resource""; @GET public Response get(Request request) { // first evaluate preconditions ResponseBuilder conditionalResponse = request.evaluatePreconditions(date, tag); if(conditionalResponse != null) return conditionalResponse.build(); // preconditions are OK return Response.ok(resource) .lastModified(date) .tag(tag) .build(); } @PUT public Response put(Request request, String body) { // first evaluate preconditions ResponseBuilder conditionalResponse = request.evaluatePreconditions(date, tag); if(conditionalResponse != null) return conditionalResponse.build(); // preconditions are OK, we can update our resource resource = body; date = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS)); version++; tag = new EntityTag(""v"" + version); return Response.ok(resource) .lastModified(date) .tag(tag) .build(); } } ---- When we call `GET /conditional` the first time, we will get this response: [source] ---- HTTP/1.1 200 OK Content-Type: text/plain;charset=UTF-8 ETag: ""v1"" Last-Modified: Wed, 09 Dec 2020 16:10:19 GMT Content-Length: 13 Some resource ---- So now if we want to check if we need to fetch a new version, we can make the following request: [source] ---- GET /conditional HTTP/1.1 Host: localhost:8080 If-Modified-Since: Wed, 09 Dec 2020 16:10:19 GMT ---- And we would get the following response: [source] ---- HTTP/1.1 304 Not Modified ---- Because the resource has not been modified since that date. This saves on sending the resource, but can also help your users detect concurrent modification, for example, let's suppose that one client wants to update the resource, but another user has modified it since. You can follow the previous `GET` request with this update: [source] ---- PUT /conditional HTTP/1.1 Host: localhost:8080 If-Unmodified-Since: Wed, 09 Dec 2020 16:25:43 GMT If-Match: v1 Content-Length: 8 Content-Type: text/plain newstuff ---- And if some other user has modified the resource between your `GET` and your `PUT` you would get this answer back: [source] ---- HTTP/1.1 412 Precondition Failed ETag: ""v2"" Content-Length: 0 ---- === Negotiation One of the main ideas of REST (https://tools.ietf.org/html/rfc7231#section-3.4[and HTTP]) is that your resource is independent from its representation, and that both the client and server are free to represent their resources in as many media types as they want. This allows the server to declare support for multiple representations and let the client declare which ones it supports and get served something appropriate. The following endpoint supports serving cheese in plain text or JSON: [source,java] ---- package org.acme.rest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.fasterxml.jackson.annotation.JsonCreator; class FroMage { public String name; @JsonCreator public FroMage(String name) { this.name = name; } @Override public String toString() { return ""Cheese: "" + name; } } @Path(""negotiated"") public class Endpoint { @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) @GET public FroMage get() { return new FroMage(""Morbier""); } @Consumes(MediaType.TEXT_PLAIN) @PUT public FroMage putString(String cheese) { return new FroMage(cheese); } @Consumes(MediaType.APPLICATION_JSON) @PUT public FroMage putJson(FroMage fromage) { return fromage; } } ---- The user will be able to select which representation it gets with the link:{httpspec}#section-5.3.2[`Accept`] header, in the case of JSON: [source,sh] ---- > GET /negotiated HTTP/1.1 > Host: localhost:8080 > Accept: application/json < HTTP/1.1 200 OK < Content-Type: application/json < Content-Length: 18 < < {""name"":""Morbier""} ---- And for text: [source,sh] ---- > GET /negotiated HTTP/1.1 > Host: localhost:8080 > Accept: text/plain > < HTTP/1.1 200 OK < Content-Type: text/plain < Content-Length: 15 < < Cheese: Morbier ---- Similarly, you can `PUT` two different representations. JSON: [source,sh] ---- > PUT /negotiated HTTP/1.1 > Host: localhost:8080 > Content-Type: application/json > Content-Length: 16 > > {""name"": ""brie""} < HTTP/1.1 200 OK < Content-Type: application/json;charset=UTF-8 < Content-Length: 15 < < {""name"":""brie""} ---- Or plain text: [source,sh] ---- > PUT /negotiated HTTP/1.1 > Host: localhost:8080 > Content-Type: text/plain > Content-Length: 9 > > roquefort < HTTP/1.1 200 OK < Content-Type: application/json;charset=UTF-8 < Content-Length: 20 < < {""name"":""roquefort""} ---- == Include/Exclude JAX-RS classes with build time conditions Quarkus enables the inclusion or exclusion of JAX-RS Resources, Providers and Features directly thanks to build time conditions in the same that it does for CDI beans. Thus, the various JAX-RS classes can be annotated with profile conditions (`@io.quarkus.arc.profile.IfBuildProfile` or `@io.quarkus.arc.profile.UnlessBuildProfile`) and/or with property conditions (`io.quarkus.arc.properties.IfBuildProperty` or `io.quarkus.arc.properties.UnlessBuildProperty`) to indicate to Quarkus at build time under which conditions these JAX-RS classes should be included. In the following example, Quarkus includes the endpoint `sayHello` if and only if the build profile `app1` has been enabled. [source,java] ---- @IfBuildProfile(""app1"") public class ResourceForApp1Only { @GET @Path(""sayHello"") public String sayHello() { return ""hello""; } } ---- Please note that if a JAX-RS Application has been detected and the method `getClasses()` and/or `getSingletons()` has/have been overridden, Quarkus will ignore the build time conditions and consider only what has been defined in the JAX-RS Application. == RESTEasy Reactive client In addition to the Server side, RESTEasy Reactive comes with a new MicroProfile Rest Client implementation that is non-blocking at its core. Please note that the `quarkus-rest-client` extension may not be used with RESTEasy Reactive, use `quarkus-rest-client-reactive` instead. See the xref:rest-client-reactive.adoc[REST Client Reactive Guide] for more information about the reactive REST client. ",16227,True,2828.218477172241,median "[[spring-cloud-dataflow-task]] = Tasks [partintro] -- This section goes into more detail about how you can orchestrate https://cloud.spring.io/spring-cloud-task/[Spring Cloud Task] applications on Spring Cloud Data Flow. If you are just starting out with Spring Cloud Data Flow, you should probably read the Getting Started guide for ""`<>`"" , ""`<>`"", ""`<>`"" before diving into this section. -- [[spring-cloud-dataflow-task-intro]] == Introduction A task application is short lived, meaning it stops running on purpose, and can be executed on demand or scheduled for execution. A use case might be to scrape a web page and write to the database. The https://cloud.spring.io/spring-cloud-task/[Spring Cloud Task] framework is based on Spring Boot and adds the capability for Boot applications to record the lifecycle events of a short lived application such as when it starts, when it ends and the exit status. The https://docs.spring.io/spring-cloud-task/docs/{spring-cloud-task-version}/reference/htmlsingle/#features-task-execution-details[TaskExecution] documentation shows which information is stored in the database. The entry point for code execution in a Spring Cloud Task application is most often an implementation of Boot's `CommandLineRunner` interface, as shown in this https://docs.spring.io/spring-cloud-task/docs/{spring-cloud-task-version}/reference/htmlsingle/#getting-started-writing-the-code[example]. The Spring Batch project is probably what comes to mind for Spring developers writing short lived applications. Spring Batch provides a much richer set of functionality than Spring Cloud Task and is recommended when processing large volumes of data. A use case might be to read many CSV files, transform each row of data, and write each transformed row to a database. Spring Batch provides its own database schema with a much more rich https://docs.spring.io/spring-batch/{spring-batch-doc-version}/reference/html/schema-appendix.html#metaDataSchema[set of information] about the execution of a Spring Batch job. Spring Cloud Task is integrated with Spring Batch so that if a Spring Cloud Task application defined a Spring Batch `Job`, a link between the Spring Cloud Task and Spring Cloud Batch execution tables is created. When running Data Flow on your local machine, Tasks are launched in a separate JVM. When running on Cloud Foundry, tasks are launched using https://docs.cloudfoundry.org/devguide/using-tasks.html[Cloud Foundry's Task] functionality and when running on Kubernetes, tasks are launched using either a `Pod` or a `Job` resource. == The Lifecycle of a Task Before we dive deeper into the details of creating Tasks, we need to understand the typical lifecycle for tasks in the context of Spring Cloud Data Flow: . <> . <> . <> . <> . <> . <> . <> [[spring-cloud-dataflow-create-task-apps]] === Creating a Task Application While Spring Cloud Task does provide a number of out-of-the-box applications (at https://github.com/spring-cloud-task-app-starters[spring-cloud-task-app-starters]), most task applications require custom development. To create a custom task application: . Use the https://start.spring.io[Spring Initializer] to create a new project, making sure to select the following starters: .. `Cloud Task`: This dependency is the `spring-cloud-starter-task`. .. `JDBC`: This dependency is the `spring-jdbc` starter. .. Select your database dependency: Enter the database dependency that Data Flow is currently using. For example: `H2`. . Within your new project, create a new class to serve as your main class, as follows: + [source,java] ---- @EnableTask @SpringBootApplication public class MyTask { public static void main(String[] args) { SpringApplication.run(MyTask.class, args); } } ---- + . With this class, you need one or more `CommandLineRunner` or `ApplicationRunner` implementations within your application. You can either implement your own or use the ones provided by Spring Boot (there is one for running batch jobs, for example). . Packaging your application with Spring Boot into an über jar is done through the standard {spring-boot-docs-reference}/html/getting-started-first-application.html#getting-started-first-application-executable-jar[Spring Boot conventions]. The packaged application can be registered and deployed as noted below. ==== Task Database Configuration CAUTION: When launching a task application, be sure that the database driver that is being used by Spring Cloud Data Flow is also a dependency on the task application. For example, if your Spring Cloud Data Flow is set to use Postgresql, be sure that the task application also has Postgresql as a dependency. TIP: When you run tasks externally (that is, from the command line) and you want Spring Cloud Data Flow to show the TaskExecutions in its UI, be sure that common datasource settings are shared among the both. By default, Spring Cloud Task uses a local H2 instance, and the execution is recorded to the database used by Spring Cloud Data Flow. [[spring-cloud-dataflow-register-task-apps]] === Registering a Task Application You can register a Task App with the App Registry by using the Spring Cloud Data Flow Shell `app register` command. You must provide a unique name and a URI that can be resolved to the app artifact. For the type, specify ""task"". The following listing shows three examples: [source,bash] ---- dataflow:>app register --name task1 --type task --uri maven://com.example:mytask:1.0.2 dataflow:>app register --name task2 --type task --uri file:///Users/example/mytask-1.0.2.jar dataflow:>app register --name task3 --type task --uri https://example.com/mytask-1.0.2.jar ---- When providing a URI with the `maven` scheme, the format should conform to the following: `maven://:[:[:]]:` If you would like to register multiple apps at one time, you can store them in a properties file where the keys are formatted as `.` and the values are the URIs. For example, the followinng listing would be a valid properties file: [source] ---- task.foo=file:///tmp/foo-1.2.1.BUILD-SNAPSHOT.jar task.bar=file:///tmp/bar-1.2.1.BUILD-SNAPSHOT.jar ---- Then you can use the `app import` command and provide the location of the properties file by using the `--uri` option, as follows: ``` app import --uri file:///tmp/task-apps.properties ``` For example, if you would like to register all out-of-the-box task applications in bulk, you can do so with the following command: ``` dataflow:>app import --uri https://dataflow.spring.io/task-maven-latest ``` You can also pass the `--local` option (which is `TRUE` by default) to indicate whether the properties file location should be resolved within the shell process itself. If the location should be resolved from the Data Flow Server process, specify `--local false`. When using either `app register` or `app import`, if a task app is already registered with the provided name and version, it is not overridden by default. If you would like to override the pre-existing task app with a different uri or uri-metadata location, then include the `--force` option. [NOTE] In some cases, the Resource is resolved on the server side. In other cases, the URI is passed to a runtime container instance where it is resolved. Consult the specific documentation of each Data Flow Server for more detail. [[spring-cloud-dataflow-create-task-definition]] === Creating a Task Definition You can create a task Definition from a task app by providing a definition name as well as properties that apply to the task execution. Creating a task definition can be done through the RESTful API or the shell. To create a task definition by using the shell, use the `task create` command to create the task definition, as shown in the following example: [source,bash,subs=attributes] ---- dataflow:>task create mytask --definition ""timestamp --format=\\""yyyy\\"""" Created new task 'mytask' ---- A listing of the current task definitions can be obtained through the RESTful API or the shell. To get the task definition list by using the shell, use the `task list` command. ==== Automating the Creation of Task Definitions As of version 2.3.0, the Data Flow server can be configured to auto create task definitions by setting `spring.cloud.dataflow.task.autocreate-task-definitions` to `true`. This is not the default behavior but provided as a convenience. When this property is enabled, a task launch request can specify the registered task application name as the task name. If the task application is registered, the server will create a basic task definition that specifies only the app name, as required. This eliminates a manual step equivalent to something like: [source,bash,subs=attributes] ---- dataflow:>task create mytask --definition ""mytask"" ---- Command line arguments and deployment properties can still be specified for each task launch request. [[spring-cloud-dataflow-task-launch]] === Launching a Task An adhoc task can be launched through the RESTful API or the shell. To launch an ad-hoc task through the shell, use the `task launch` command, as shown in the following example: [source,bash,subs=attributes] ---- dataflow:>task launch mytask Launched task 'mytask' ---- When a task is launched, any properties that need to be passed as command line arguments to the task application can be set when launching the task, as follows: [source,bash,subs=attributes] ---- dataflow:>task launch mytask --arguments ""--server.port=8080 --custom=value"" ---- [NOTE] The arguments need to be passed as `space` delimited values. Additional properties meant for a `TaskLauncher` itself can be passed in by using a `--properties` option. The format of this option is a comma-separated string of properties prefixed with `app..`. Properties are passed to `TaskLauncher` as application properties. It is up to an implementation to choose how those are passed into an actual task application. If the property is prefixed with `deployer` instead of `app`, it is passed to `TaskLauncher` as a deployment property and its meaning may be `TaskLauncher` implementation specific. `dataflow:>task launch mytask --properties ""deployer.timestamp.custom1=value1,app.timestamp.custom2=value2""` ==== Application properties Each application takes properties to customize its behavior. As an example, the `timestamp` task `format` setting establishes a output format that is different from the default value. `dataflow:> task create --definition ""timestamp --format=\\""yyyy\\"""" --name printTimeStamp` This `timestamp` property is actually the same as the `timestamp.format` property specified by the timestamp application. Data Flow adds the ability to use the shorthand form `format` instead of `timestamp.format`. One may also specify the longhand version as well, as shown in the following example: `dataflow:> task create --definition ""timestamp --timestamp.format=\\""yyyy\\"""" --name printTimeStamp` This shorthand behavior is discussed more in the section on <>. If you have <> you can use tab completion in the shell after typing `--` to get a list of candidate property names. The shell provides tab completion for application properties. The shell command `app info --name --type ` provides additional documentation for all the supported properties. The supported Task `` is task. NOTE: When restarting Spring Batch Jobs on Kubernetes, you must use the entry point of `shell` or `boot`. ===== Application Properties With Sensitive Information on Kubernetes When launching task applications where some of the properties may contain sensitive information, use the `shell` or `boot` as the `entryPointStyle`. This is because the `exec` (default) converts all properties to command line arguments and thus may not be secure in some environments. ==== Common application properties In addition to configuration through DSL, Spring Cloud Data Flow provides a mechanism for setting common properties to all the task applications that are launched by it. This can be done by adding properties prefixed with `spring.cloud.dataflow.applicationProperties.task` when starting the server. When doing so, the server passes all the properties, without the prefix, to the instances it launches. For example, all the launched applications can be configured to use the properties `prop1` and `prop2` by launching the Data Flow server with the following options: [source,bash,subs=attributes] ---- --spring.cloud.dataflow.applicationProperties.task.prop1=value1 --spring.cloud.dataflow.applicationProperties.task.prop2=value2 ---- This causes the properties, `prop1=value1` and `prop2=value2`, to be passed to all the launched applications. [NOTE] Properties configured by using this mechanism have lower precedence than task deployment properties. They are overridden if a property with the same key is specified at task launch time (for example, `app.trigger.prop2` overrides the common property). [[spring-cloud-dataflow-task-limit-concurrent-executions]] === Limit the number concurrent task launches Spring Cloud Data Flow allows a user to limit the maximum number of concurrently running tasks for each configured platform to prevent the saturation of IaaS/hardware resources. The limit is set to `20` for all supported platforms by default. If the number of concurrently running tasks on a platform instance is greater or equal to the limit, the next task launch request will fail and an error message will be returned via the RESTful API, Shell or UI. This limit can be configured for a platform instance by setting the corresponding deployer property, `spring.cloud.dataflow.task.platform..accounts[].deployment.maximumConcurrentTasks` property, where `` is the name of a configured platform account (`default` if no accounts are explicitly configured). The `` refers to one of the currently supported deployers: `local`, `cloudfoundry`, or `kubernetes`. The TaskLauncher implementation for each supported platform determines the number of currently executing tasks by querying the underlying platform's runtime state if possible. The method for identifying a `task` varies by platform. For example, launching a task on the local host uses the `LocalTaskLauncher`. The LocalTaskLauncher executes a process for each launch request and keeps track of these processes in memory. In this case, we don't query the underlying OS, as it is impractical to identify tasks this way. For Cloud Foundry, tasks are a core concept supported by its deployment model. The state of all tasks, running, completed, or failed, is available directly via the API. This means that every running task container in the account's org and space is included in the running execution count, whether or not it was launched using Spring Cloud Data Flow, or invoking the `CloudFoundryTaskLauncher` directly. For Kubernetes, launching a task via the `KubernetesTaskLauncher`, if successful, results in a running pod which we expect to eventually complete or fail. In this environment there is generally no easy way to identify pods that correspond to a task. For this reason, we only count pods that were launched by the `KubernetesTaskLauncher`. Since the task launcher provides `task-name` label in the pod's metadata, we filter all running pods by the presence of this label. [[spring-cloud-dataflow-task-review-executions]] === Reviewing Task Executions Once the task is launched, the state of the task is stored in a relational DB. The state includes: * Task Name * Start Time * End Time * Exit Code * Exit Message * Last Updated Time * Parameters A user can check the status of their task executions through the RESTful API or the shell. To display the latest task executions through the shell, use the `task execution list` command. To get a list of task executions for just one task definition, add `--name` and the task definition name, for example `task execution list --name foo`. To retrieve full details for a task execution use the `task execution status` command with the id of the task execution, for example `task execution status --id 549`. [[spring-cloud-dataflow-task-definition-destroying]] === Destroying a Task Definition Destroying a Task Definition removes the definition from the definition repository. This can be done through the RESTful API or the shell. To destroy a task through the shell, use the `task destroy` command, as shown in the following example: [source,bash,subs=attributes] ---- dataflow:>task destroy mytask Destroyed task 'mytask' ---- The `task destroy` command also has an option to `cleanup` the task executions of the task being destroyed, as shown in the following example: [source,bash,subs=attributes] ---- dataflow:>task destroy mytask --cleanup Destroyed task 'mytask' ---- By default, the `cleanup` option is set to `false` (ie., by default, the task executions are not cleaned up when destroying the task). To destroy all tasks through the shell, use the `task all destroy` command as shown in the following example: [source,bash,subs=attributes] ---- dataflow:>task all destroy Really destroy all tasks? [y, n]: y All tasks destroyed ---- Or use the force command: [source,bash,subs=attributes] ---- dataflow:>task all destroy --force All tasks destroyed ---- The task execution information for previously launched tasks for the definition remains in the task repository. NOTE: This does not stop any currently executing tasks for this definition. Instead, it removes the task definition from the database. NOTE: The `task destroy ` deletes only the definition and not the task deployed on Cloud Foundry. The only way to do this now is through the CLI in two steps. First, obtain a list of the apps by using the `cf apps` command. . Identify the task application to be deleted and run the `cf delete ` command. [[spring-cloud-dataflow-validate-task]] === Validating a Task Sometimes the one or more of the apps contained within a task definition contain an invalid URI in its registration. This can be caused by an invalid URI entered at app registration time or the app was removed from the repository from which it was to be drawn. To verify that all the apps contained in a task are resolve-able, a user can use the `validate` command. For example: [source,bash] ---- dataflow:>task validate time-stamp ╔══════════╤═══════════════╗ ║Task Name │Task Definition║ ╠══════════╪═══════════════╣ ║time-stamp│timestamp ║ ╚══════════╧═══════════════╝ time-stamp is a valid task. ╔═══════════════╤═════════════════╗ ║ App Name │Validation Status║ ╠═══════════════╪═════════════════╣ ║task:timestamp │valid ║ ╚═══════════════╧═════════════════╝ ---- In the example above the user validated their time-stamp task. As we see `task:timestamp` app is valid. Now let's see what happens if we have a stream definition with a registered app with an invalid URI. [source,bash] ---- dataflow:>task validate bad-timestamp ╔═════════════╤═══════════════╗ ║ Task Name │Task Definition║ ╠═════════════╪═══════════════╣ ║bad-timestamp│badtimestamp ║ ╚═════════════╧═══════════════╝ bad-timestamp is an invalid task. ╔══════════════════╤═════════════════╗ ║ App Name │Validation Status║ ╠══════════════════╪═════════════════╣ ║task:badtimestamp │invalid ║ ╚══════════════════╧═════════════════╝ ---- In this case Spring Cloud Data Flow states that the task is invalid because task:badtimestamp has an invalid URI. [[spring-cloud-dataflow-stopping-task-execution]] === Stopping a Task Execution In some cases a task that is executing on a platform may not stop because of a problem on the platform or the application business logic itself. For such cases Spring Cloud Data Flow offers the user the ability to send a request to the platform to terminate the task execution. To do this a user can submit a `task execution stop` for a given set of task executions. For example: [source,bash] ---- task execution stop --ids 5 Request to stop the task execution with id(s): 5 has been submitted ---- With the above command, the trigger to stop the execution of id=5 will be submitted to the underlying deployer implementation, and as a result, the operation will stop the execution of that task. When we view the result for the task execution, we will see that the task execution completed with a 0 exit code. [source,bash] ---- dataflow:>task execution list ╔══════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗ ║Task Name │ID│ Start Time │ End Time │Exit Code║ ╠══════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣ ║batch-demo│5 │Mon Jul 15 13:58:41 EDT 2019│Mon Jul 15 13:58:55 EDT 2019│0 ║ ║timestamp │1 │Mon Jul 15 09:26:41 EDT 2019│Mon Jul 15 09:26:41 EDT 2019│0 ║ ╚══════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝ ---- If a user submits a stop for a task execution that has child task executions associated with it, like a composed task, a stop request will be sent for each of the child task executions. [WARNING] ==== When stopping a task execution that has a running Spring Batch job, the job will be left with the batch status of `STARTED`. Each of the supported platforms send a SIG-INT to the task application when a stop is requested that allows Spring Cloud Task to capture the state of the app, however Spring Batch does not handle a SIG-INT and thus the job stops in the STARTED status. ==== ==== Stopping a Task Execution that was started outside of Spring Cloud Data Flow You may wish to stop a task that has been launched outside of Spring Cloud Data Flow. An example of this is the worker applications launched by a Remote Batch Partitioned application. In such cases the Remote Batch Partitioned Application stores the external-execution-id for each of the worker applications, however no platform information is stored. So when Spring Cloud Data Flow has to stop a Remote Batch Partitioned application and its worker applications, you will need to specify the platform name as shown below: [source,bash] ---- dataflow:>task execution stop --ids 1 --platform myplatform Request to stop the task execution with id(s): 1 for platform myplatform has been submitted ---- [[spring-cloud-dataflow-task-events]] == Subscribing to Task/Batch Events You can also tap into various task and batch events when the task is launched. If the task is enabled to generate task or batch events (with the additional dependencies `spring-cloud-task-stream` and, in the case of Kafka as the binder, `spring-cloud-stream-binder-kafka`), those events are published during the task lifecycle. By default, the destination names for those published events on the broker (Rabbit, Kafka, and others) are the event names themselves (for instance: `task-events`, `job-execution-events`, and so on). [source,bash,subs=attributes] ---- dataflow:>task create myTask --definition ""myBatchJob"" dataflow:>stream create task-event-subscriber1 --definition "":task-events > log"" --deploy dataflow:>task launch myTask ---- You can control the destination name for those events by specifying explicit names when launching the task, as follows: [source,bash,subs=attributes] ---- dataflow:>stream create task-event-subscriber2 --definition "":myTaskEvents > log"" --deploy dataflow:>task launch myTask --properties ""app.myBatchJob.spring.cloud.stream.bindings.task-events.destination=myTaskEvents"" ---- The following table lists the default task and batch event and destination names on the broker: .Task and Batch Event Destinations [cols=""2*""] |=== |*Event*|*Destination* |Task events |`task-events` |Job Execution events |`job-execution-events` |Step Execution events|`step-execution-events` |Item Read events|`item-read-events` |Item Process events|`item-process-events` |Item Write events|`item-write-events` |Skip events|`skip-events` |=== [[spring-cloud-dataflow-composed-tasks]] == Composed Tasks Spring Cloud Data Flow lets a user create a directed graph where each node of the graph is a task application. This is done by using the DSL for composed tasks. A composed task can be created through the RESTful API, the Spring Cloud Data Flow Shell, or the Spring Cloud Data Flow UI. === Configuring the Composed Task Runner Composed tasks are executed through a task application called the https://github.com/spring-cloud-task-app-starters/composed-task-runner[Composed Task Runner]. ==== Registering the Composed Task Runner By default, Spring Cloud Data Flow retrieves the Composed Task Runner application from Maven Central for Cloud Foundry and local deployments and DockerHub for Kubernetes. It retrieves the Composed Task Runner upon the first use of composed tasks. If Maven Central or DockerHub cannot be reached for a given Spring Cloud Data Flow deployment a new URI can be specified to retrieve the Composed Task Runner using the `spring.cloud.dataflow.task.composed.task.runner.uri` property. ==== Configuring the Composed Task Runner The Composed Task Runner application has a `dataflow.server.uri` property that is used for validation and for launching child tasks. This defaults to `http://localhost:9393`. If you run a distributed Spring Cloud Data Flow server, as you would if you deploy the server on Cloud Foundry or Kubernetes, you need to provide the URI that can be used to access the server. You can either provide this `dataflow.server.uri` property for the Composed Task Runner application when launching a composed task or you can provide a `spring.cloud.dataflow.server.uri` property for the Spring Cloud Data Flow server when it is started. For the latter case, the `dataflow.server.uri` Composed Task Runner application property is automatically set when a composed task is launched. ===== Configuration Options The ComposedTaskRunner task has the following options: * *composed-task-arguments* The command line arguments to be used for each of the tasks. (String, default: ). * *increment-instance-enabled* Allows a single ComposedTaskRunner instance to be re-executed without changing the parameters. Default is false which means a ComposedTaskRunner instance can only be executed once with a given set of parameters, if true it can be re-executed. (Boolean, default: false). ComposedTaskRunner is built using https://github.com/spring-projects/spring-batch[Spring Batch] and thus upon a successful execution the batch job is considered complete. To launch the same ComposedTaskRunner definition multiple times you must set the `increment-instance-enabled` property to true or change the parameters for the definition for each launch. When using this option it must be applied for all task launches for the desired application including the first launch. * *interval-time-between-checks* The amount of time in millis that the ComposedTaskRunner will wait between checks of the database to see if a task has completed. (Integer, default: 10000). ComposedTaskRunner uses the datastore to determine the status of each child tasks. This interval indicates to ComposedTaskRunner how often it should check the status its child tasks. * *max-wait-time* The maximum amount of time in millis that a individual step can run before the execution of the Composed task is failed (Integer, default: 0). Determines the maximum time each child task is allowed to run before the CTR will terminate with a failure. The default of `0` indicates no timeout. * *split-thread-allow-core-thread-timeout* Specifies whether to allow split core threads to timeout. Default is false; (Boolean, default: false) Sets the policy governing whether core threads may timeout and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive. * *split-thread-core-pool-size* Split's core pool size. Default is 1; (Integer, default: 1) Each child task contained in a split requires a thread in order to execute. So for example a definition like: ` && ` would require a split-thread-core-pool-size of 3. This is because the largest split contains 3 child tasks. A count of 2 would mean that `AAA` and `BBB` would run in parallel but CCC would wait until either `AAA` or `BBB` to finish in order to run. Then `DDD` and `EEE` would run in parallel. * *split-thread-keep-alive-seconds* Split's thread keep alive seconds. Default is 60. (Integer, default: 60) If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime. * *split-thread-max-pool-size* Split's maximum pool size. Default is {@code Integer.MAX_VALUE} (Integer, default: ). Establish the maximum number of threads allowed for the thread pool. * *split-thread-queue-capacity* Capacity for Split's BlockingQueue. Default is {@code Integer.MAX_VALUE}. (Integer, default: ) ** If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing. ** If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread. ** If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected. * *split-thread-wait-for-tasks-to-complete-on-shutdown* Whether to wait for scheduled tasks to complete on shutdown, not interrupting running tasks and executing all tasks in the queue. Default is false; (Boolean, default: false) * *dataflow-server-uri* The URI for the dataflow server that will receive task launch requests. (String, default: http://localhost:9393) * *dataflow-server-username* The optional username for the dataflow server that will receive task launch requests. Used to access the the dataflow server using Basic Authentication. Not used if `dataflow-server-access-token` is set. * *dataflow-server-password* The optional password for the dataflow server that will receive task launch requests. Used to access the the dataflow server using Basic Authentication. Not used if `dataflow-server-access-token` is set. * *dataflow-server-access-token* This property sets optional OAuth2 Access Token. Typically the value is automatically set using the token from the currently logged in user, if available. However, for special use-cases this value can also be set explicitly. [INFO] ==== A special boolean property `dataflow-server-use-user-access-token` exists for the case where you want to use the access token of the currently logged user and propgate it to the Composed Task Runner. This property is only used by Spring Cloud Data Flow and if set to `true` will auto-populate the property `dataflow-server-access-token`. ==== Note when using the options above as environment variables, convert to uppercase, remove the dash character and replace with the underscore character. For example: increment-instance-enabled would be INCREMENT_INSTANCE_ENABLED. NOTE: For the latest configuration options for Composed Task Runner click the link https://github.com/spring-cloud-task-app-starters/composed-task-runner/blob/master/spring-cloud-starter-task-composedtaskrunner/README.adoc#options[here]. === The Lifecycle of a Composed Task The lifecycle of a composed task has three parts: * <> * <> * <> [[spring-cloud-data-flow-composed-task-creating]] ==== Creating a Composed Task The DSL for the composed tasks is used when creating a task definition through the task create command, as shown in the following example: [source,bash,subs=attributes] ---- dataflow:> app register --name timestamp --type task --uri maven://org.springframework.cloud.task.app:timestamp-task: dataflow:> app register --name mytaskapp --type task --uri file:///home/tasks/mytask.jar dataflow:> task create my-composed-task --definition ""mytaskapp && timestamp"" dataflow:> task launch my-composed-task ---- In the preceding example, we assume that the applications to be used by our composed task have not been registered yet. Consequently, in the first two steps, we register two task applications. We then create our composed task definition by using the `task create` command. The composed task DSL in the preceding example, when launched, runs mytaskapp and then runs the timestamp application. But before we launch the `my-composed-task` definition, we can view what Spring Cloud Data Flow generated for us. This can be done by executing the task list command, as shown (including its output) in the following example: [source,bash,options=""nowrap""] ---- dataflow:>task list ╔══════════════════════════╤══════════════════════╤═══════════╗ ║ Task Name │ Task Definition │Task Status║ ╠══════════════════════════╪══════════════════════╪═══════════╣ ║my-composed-task │mytaskapp && timestamp│unknown ║ ║my-composed-task-mytaskapp│mytaskapp │unknown ║ ║my-composed-task-timestamp│timestamp │unknown ║ ╚══════════════════════════╧══════════════════════╧═══════════╝ ---- In the example, Spring Cloud Data Flow created three task definitions, one for each of the applications that makes up our composed task (`my-composed-task-mytaskapp` and `my-composed-task-timestamp`) as well as the composed task (`my-composed-task`) definition. We also see that each of the generated names for the child tasks is made up of the name of the composed task and the name of the application, separated by a dash `-` (as in _my-composed-task_ `-` _mytaskapp_). ===== Task Application Parameters The task applications that make up the composed task definition can also contain parameters, as shown in the following example: `dataflow:> task create my-composed-task --definition ""mytaskapp --displayMessage=hello && timestamp --format=YYYY""` ==== Launching a Composed Task Launching a composed task is done the same way as launching a stand-alone task, as follows: `task launch my-composed-task` Once the task is launched, and assuming all the tasks complete successfully, you can see three task executions when executing a `task execution list`, as shown in the following example: [source,bash,options=""nowrap""] ---- dataflow:>task execution list ╔══════════════════════════╤═══╤════════════════════════════╤════════════════════════════╤═════════╗ ║ Task Name │ID │ Start Time │ End Time │Exit Code║ ╠══════════════════════════╪═══╪════════════════════════════╪════════════════════════════╪═════════╣ ║my-composed-task-timestamp│713│Wed Apr 12 16:43:07 EDT 2017│Wed Apr 12 16:43:07 EDT 2017│0 ║ ║my-composed-task-mytaskapp│712│Wed Apr 12 16:42:57 EDT 2017│Wed Apr 12 16:42:57 EDT 2017│0 ║ ║my-composed-task │711│Wed Apr 12 16:42:55 EDT 2017│Wed Apr 12 16:43:15 EDT 2017│0 ║ ╚══════════════════════════╧═══╧════════════════════════════╧════════════════════════════╧═════════╝ ---- In the preceding example, we see that `my-compose-task` launched and that it also launched the other tasks in sequential order. All of them executed successfully with `Exit Code` as `0`. ===== Passing properties to the child tasks To set the properties for child tasks in a composed task graph at task launch time, you would use the following format of `app...`. Using the following Composed Task definition as an example: [source,bash] ---- dataflow:> task create my-composed-task --definition ""mytaskapp && mytimestamp"" ---- To have mytaskapp display 'HELLO' and set the mytimestamp timestamp format to 'YYYY' for the Composed Task definition, you would use the following task launch format: [source,bash] ---- task launch my-composed-task --properties ""app.my-composed-task.mytaskapp.displayMessage=HELLO,app.my-composed-task.mytimestamp.timestamp.format=YYYY"" ---- Similar to application properties, the `deployer` properties can also be set for child tasks using the format format of `deployer...`. [source,bash] ---- task launch my-composed-task --properties ""deployer.my-composed-task.mytaskapp.memory=2048m,app.my-composed-task.mytimestamp.timestamp.format=HH:mm:ss"" Launched task 'a1' ---- ===== Passing arguments to the composed task runner Command line arguments for the composed task runner can be passed using `--arguments` option. For example: [source,bash] ---- dataflow:>task create my-composed-task --definition """" Created new task 'my-composed-task' dataflow:>task launch my-composed-task --arguments ""--increment-instance-enabled=true --max-wait-time=50000 --split-thread-core-pool-size=4"" --properties ""app.my-composed-task.bbb.timestamp.format=dd/MM/yyyy HH:mm:ss"" Launched task 'my-composed-task' ---- ===== Launching a Composed Task using Custom Composed Task Runner In some cases a user will need to launch a composed task using a custom version of a Composed Task Runner other than default application that is shipped out-of-the-box. To do this, a user will need to register the custom version of the Composed Task Runner and then specify the --composedTaskRunnerName property pointing to the custom application at task launch as shown below: [source,bash,options=""nowrap""] ---- dataflow:>app register --name best-ctr --type task --uri maven://the.best.ctr.composed-task-runner:1.0.0.RELEASE dataflow:>task create mycomposedtask --definition ""te:timestamp && tr:timestamp"" Created new task 'mycomposedtask' dataflow:>task launch --name mycomposedtask --composedTaskRunnerName best-ctr ---- NOTE: The app specified by the `composedTaskRunnerName` needs to be a task registered in the Application Registry. ===== Exit Statuses The following list shows how the Exit Status is set for each step (task) contained in the composed task following each step execution: * If the `TaskExecution` has an `ExitMessage`, that is used as the `ExitStatus`. * If no `ExitMessage` is present and the `ExitCode` is set to zero, then the `ExitStatus` for the step is `COMPLETED`. * If no `ExitMessage` is present and the `ExitCode` is set to any non-zero number, the `ExitStatus` for the step is `FAILED`. ==== Destroying a Composed Task The command used to destroy a stand-alone task is the same as the command used to destroy a composed task. The only difference is that destroying a composed task also destroys the child tasks associated with it. The following example shows the task list before and after using the `destroy` command: [source,bash,options=""nowrap""] ---- dataflow:>task list ╔══════════════════════════╤══════════════════════╤═══════════╗ ║ Task Name │ Task Definition │Task Status║ ╠══════════════════════════╪══════════════════════╪═══════════╣ ║my-composed-task │mytaskapp && timestamp│COMPLETED ║ ║my-composed-task-mytaskapp│mytaskapp │COMPLETED ║ ║my-composed-task-timestamp│timestamp │COMPLETED ║ ╚══════════════════════════╧══════════════════════╧═══════════╝ ... dataflow:>task destroy my-composed-task dataflow:>task list ╔═════════╤═══════════════╤═══════════╗ ║Task Name│Task Definition│Task Status║ ╚═════════╧═══════════════╧═══════════╝ ---- [[spring-cloud-data-flow-composed-task-stopping]] ==== Stopping a Composed Task In cases where a composed task execution needs to be stopped, you can do so through the: * RESTful API * Spring Cloud Data Flow Dashboard To stop a composed task through the dashboard, select the Jobs tab and click the Stop button next to the job execution that you want to stop. The composed task run is stopped when the currently running child task completes. The step associated with the child task that was running at the time that the composed task was stopped is marked as `STOPPED` as well as the composed task job execution. [[spring-cloud-data-flow-composed-task-restarting]] ==== Restarting a Composed Task In cases where a composed task fails during execution and the status of the composed task is `FAILED`, the task can be restarted. You can do so through the: * RESTful API * The shell * Spring Cloud Data Flow Dashboard To restart a composed task through the shell, launch the task with the same parameters. To restart a composed task through the dashboard, select the Jobs tab and click the Restart button next to the job execution that you want to restart. NOTE: Restarting a Composed Task job that has been stopped (through the Spring Cloud Data Flow Dashboard or RESTful API) relaunches the `STOPPED` child task and then launches the remaining (unlaunched) child tasks in the specified order. == Composed Tasks DSL Composed tasks can be run in three ways: * <> * <> * <> [[spring-cloud-data-flow-conditional-execution]] === Conditional Execution Conditional execution is expressed by using a double ampersand symbol (`&&`). This lets each task in the sequence be launched only if the previous task successfully completed, as shown in the following example: `task create my-composed-task --definition ""task1 && task2""` When the composed task called `my-composed-task` is launched, it launches the task called `task1` and, if it completes successfully, then the task called `task2` is launched. If `task1` fails, then `task2` does not launch. You can also use the Spring Cloud Data Flow Dashboard to create your conditional execution, by using the designer to drag and drop applications that are required and connecting them together to create your directed graph, as shown in the following image: .Conditional Execution image::{dataflow-asciidoc}/images/dataflow-ctr-conditional-execution.png[Composed Task Conditional Execution, scaledwidth=""50%""] The preceding diagram is a screen capture of the directed graph as it being created by using the Spring Cloud Data Flow Dashboard. You can see that are four components in the diagram that comprise a conditional execution: * Start icon: All directed graphs start from this symbol. There is only one. * Task icon: Represents each task in the directed graph. * End icon: Represents the termination of a directed graph. * Solid line arrow: Represents the flow conditional execution flow between: ** Two applications. ** The start control node and an application. ** An application and the end control node. * End icon: All directed graphs end at this symbol. TIP: You can view a diagram of your directed graph by clicking the Detail button next to the composed task definition on the Definitions tab. [[spring-cloud-data-flow-transitional-execution]] === Transitional Execution The DSL supports fine-grained control over the transitions taken during the execution of the directed graph. Transitions are specified by providing a condition for equality based on the exit status of the previous task. A task transition is represented by the following symbol `->`. ==== Basic Transition A basic transition would look like the following: ``` task create my-transition-composed-task --definition ""foo 'FAILED' -> bar 'COMPLETED' -> baz"" ``` In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch. If the exit status of `foo` was `COMPLETED`, `baz` would launch. All other statuses returned by `foo` have no effect, and the task would terminate normally. Using the Spring Cloud Data Flow Dashboard to create the same "" `basic transition` "" would resemble the following image: .Basic Transition image::{dataflow-asciidoc}/images/dataflow-ctr-transition-basic.png[Composed Task Basic Transition, scaledwidth=""50%""] The preceding diagram is a screen capture of the directed graph as it being created in the Spring Cloud Data Flow Dashboard. Notice that there are two different types of connectors: * Dashed line: Represents transitions from the application to one of the possible destination applications. * Solid line: Connects applications in a conditional execution or a connection between the application and a control node (start or end). To create a transitional connector: . When creating a transition, link the application to each possible destination by using the connector. . Once complete, go to each connection and select it by clicking it. . A bolt icon appears. . Click that icon. . Enter the exit status required for that connector. . The solid line for that connector turns to a dashed line. ==== Transition With a Wildcard Wildcards are supported for transitions by the DSL, as shown in the following: ``` task create my-transition-composed-task --definition ""foo 'FAILED' -> bar '*' -> baz"" ``` In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch. For any exit status of `foo` other than `FAILED`, `baz` would launch. Using the Spring Cloud Data Flow Dashboard to create the same ""`transition with wildcard`"" would resemble the following image: .Basic Transition With Wildcard image::{dataflow-asciidoc}/images/dataflow-ctr-transition-basic-wildcard.png[Composed Task Basic Transition with Wildcard, scaledwidth=""50%""] ==== Transition With a Following Conditional Execution A transition can be followed by a conditional execution so long as the wildcard is not used, as shown in the following example: ``` task create my-transition-conditional-execution-task --definition ""foo 'FAILED' -> bar 'UNKNOWN' -> baz && qux && quux"" ``` In the preceding example, `foo` would launch, and, if it had an exit status of `FAILED`, the `bar` task would launch. If `foo` had an exit status of `UNKNOWN`, `baz` would launch. For any exit status of `foo` other than `FAILED` or `UNKNOWN`, `qux` would launch and, upon successful completion, `quux` would launch. Using the Spring Cloud Data Flow Dashboard to create the same ""`transition with conditional execution`"" would resemble the following image: .Transition With Conditional Execution image::{dataflow-asciidoc}/images/dataflow-ctr-transition-conditional-execution.png[Composed Task Transition with Conditional Execution, scaledwidth=""50%""] NOTE: In this diagram we see the dashed line (transition) connecting the `foo` application to the target applications, but a solid line connecting the conditional executions between `foo`, `qux`, and `quux`. [[spring-cloud-data-flow-split-execution]] === Split Execution Splits allow multiple tasks within a composed task to be run in parallel. It is denoted by using angle brackets (`<>`) to group tasks and flows that are to be run in parallel. These tasks and flows are separated by the double pipe `||` symbol, as shown in the following example: `task create my-split-task --definition """"` The preceding example above launches tasks `foo`, `bar` and `baz` in parallel. Using the Spring Cloud Data Flow Dashboard to create the same ""`split execution`"" would resemble the following image: .Split image::{dataflow-asciidoc}/images/dataflow-ctr-split.png[Composed Task Split, scaledwidth=""50%""] With the task DSL, a user may also execute multiple split groups in succession, as shown in the following example: `task create my-split-task --definition "" && ""' In the preceding example, tasks `foo`, `bar`, and `baz` are launched in parallel. Once they all complete, then tasks `qux` and `quux` are launched in parallel. Once they complete, the composed task ends. However, if `foo`, `bar`, or `baz` fails, the split containing `qux` and `quux` does not launch. Using the Spring Cloud Data Flow Dashboard to create the same ""`split with multiple groups`"" would resemble the following image: .Split as a part of a conditional execution image::{dataflow-asciidoc}/images/dataflow-ctr-multiple-splits.png[Composed Task Split, scaledwidth=""50%""] Notice that there is a `SYNC` control node that is inserted by the designer when connecting two consecutive splits. NOTE: Tasks that are used in a split should not set the their `ExitMessage`. Setting the `ExitMessage` is only to be used with <>. ==== Split Containing Conditional Execution A split can also have a conditional execution within the angle brackets, as shown in the following example: `task create my-split-task --definition """"` In the preceding example, we see that `foo` and `baz` are launched in parallel. However, `bar` does not launch until `foo` completes successfully. Using the Spring Cloud Data Flow Dashboard to create the same "" `split containing conditional execution` "" resembles the following image: .Split with conditional execution image::{dataflow-asciidoc}/images/dataflow-ctr-split-contains-conditional.png[Composed Task Split With Conditional Execution, scaledwidth=""50%""] ==== Establishing the proper thread count for splits Each child task contained in a split requires a thread in order to execute. To set this properly you want to look at your graph and count the split that has the largest number of child tasks, this will be the number of threads you will need to utilize. To set the thread count use the split-thread-core-pool-size property (defaults to 1). So for example a definition like: ` && ` would require a split-thread-core-pool-size of 3. This is because the largest split contains 3 child tasks. A count of 2 would mean that `AAA` and `BBB` would run in parallel but CCC would wait until either `AAA` or `BBB` to finish in order to run. Then `DDD` and `EEE` would run in parallel. [[spring-cloud-dataflow-launch-tasks-from-stream]] == Launching Tasks from a Stream You can launch a task from a stream by using the https://github.com/spring-cloud-stream-app-starters/tasklauncher-dataflow/blob/master/spring-cloud-starter-stream-sink-task-launcher-dataflow/README.adoc[tasklauncher-dataflow] sink. The sink connects to a Data Flow server and uses its REST API to launch any defined task. The sink accepts a https://github.com/spring-cloud-stream-app-starters/tasklauncher-dataflow/blob/master/spring-cloud-starter-stream-sink-task-launcher-dataflow/README.adoc#payload[JSON payload] representing a `task launch request` which provides the name of the task to launch, and may include command line arguments and deployment properties. The https://github.com/spring-cloud-stream-app-starters/core/blob/master/common/app-starters-task-launch-request-common/README.adoc[app-starters-task-launch-request-common] component , in conjunction with Spring Cloud Stream https://docs.spring.io/spring-cloud-stream/docs/current-snapshot/reference/htmlsingle/#_functional_composition[functional composition], can transform the output of any source or processor to a task launch request. Adding a dependency to `app-starters-task-launch-request-common`, auto-configures a `java.util.function.Function` implementation, registered via https://cloud.spring.io/spring-cloud-function/[Spring Cloud Function] as `taskLaunchRequest`. For example, you can start with the https://github.com/spring-cloud-stream-app-starters/time/tree/master/spring-cloud-starter-stream-source-time[time] source, add the following dependency, build it, and register it as a custom source. We'll call it `time-tlr` in this example. [source,xml] ---- org.springframework.cloud.stream.app app-starters-task-launch-request-common ---- TIP: https://start-scs.cfapps.io/[Spring Cloud Stream Initializr] provides a great starting point for creating stream applications. Next, <> the `tasklauncher-dataflow` sink, and create a task (we will use the provided timestamp task). ``` stream create --name task-every-minute --definition ""time-tlr --trigger.fixed-delay=60 --spring.cloud.stream.function.definition=taskLaunchRequest --task.launch.request.task-name=timestamp-task | tasklauncher-dataflow"" --deploy ``` The preceding stream will produce a task launch request every minute. The request provides the name of the task to launch : `{""name"":""timestamp-task""}`. The following stream definition illustrates the use of command line arguments. It will produce messages like `{""args"":[""foo=bar"",""time=12/03/18 17:44:12""],""deploymentProps"":{},""name"":""timestamp-task""}` to provide command line arguments to the task: ``` stream create --name task-every-second --definition ""time-tlr --spring.cloud.stream.function.definition=taskLaunchRequest --task.launch.request.task-name=timestamp-task --task.launch.request.args=foo=bar --task.launch.request.arg-expressions=time=payload | tasklauncher-dataflow"" --deploy ``` Note the use of SpEL expressions to map each message payload to the `time` command line argument, along with a static argument `foo=bar`. You can then see the list of task executions by using the shell command `task execution list`, as shown (with its output) in the following example: [source,bash,options=""nowrap""] ---- dataflow:>task execution list ╔════════════════════╤══╤════════════════════════════╤════════════════════════════╤═════════╗ ║ Task Name │ID│ Start Time │ End Time │Exit Code║ ╠════════════════════╪══╪════════════════════════════╪════════════════════════════╪═════════╣ ║timestamp-task_26176│4 │Tue May 02 12:13:49 EDT 2017│Tue May 02 12:13:49 EDT 2017│0 ║ ║timestamp-task_32996│3 │Tue May 02 12:12:49 EDT 2017│Tue May 02 12:12:49 EDT 2017│0 ║ ║timestamp-task_58971│2 │Tue May 02 12:11:50 EDT 2017│Tue May 02 12:11:50 EDT 2017│0 ║ ║timestamp-task_13467│1 │Tue May 02 12:10:50 EDT 2017│Tue May 02 12:10:50 EDT 2017│0 ║ ╚════════════════════╧══╧════════════════════════════╧════════════════════════════╧═════════╝ ---- In this example, we have shown how to use the `time` source to launch a task at a fixed rate. This pattern may be applied to any source to launch a task in response to any event. === Launching a Composed Task From a Stream A composed task can be launched with the `tasklauncher-dataflow` sink, as discussed <>. Since we use the `ComposedTaskRunner` directly, we need to set up the task definitions for the composed task runner itself, along with the composed tasks, prior to the creation of the composed task launching stream. Suppose we wanted to create the following composed task definition: `AAA && BBB`. The first step would be to create the task definitions, as shown in the following example: [source] ---- task create composed-task-runner --definition ""composed-task-runner"" task create AAA --definition ""timestamp"" task create BBB --definition ""timestamp"" ---- NOTE: Releases of `ComposedTaskRunner` can be found https://github.com/spring-cloud-task-app-starters/composed-task-runner/releases[here]. Now that the task definitions we need for composed task definition are ready, we need to create a stream that launches `ComposedTaskRunner`. So, in this case, we create a stream with * The `time` source customized to emit task launch requests, as shown <>. * The `tasklauncher-dataflow` sink that launches the `ComposedTaskRunner` The stream should resemble the following: [source] ---- stream create ctr-stream --definition ""time --fixed-delay=30 --task.launch.request.task-name=composed-task-launcher --task.launch.request.args=--graph=AAA&&BBB,--increment-instance-enabled=true | tasklauncher-dataflow"" ---- For now, we focus on the configuration that is required to launch the `ComposedTaskRunner`: * *graph*: this is the graph that is to be executed by the `ComposedTaskRunner`. In this case it is `AAA&&BBB`. * *increment-instance-enabled*: This lets each execution of `ComposedTaskRunner` be unique. `ComposedTaskRunner` is built by using https://projects.spring.io/spring-batch/[Spring Batch]. Thus, we want a new Job Instance for each launch of the `ComposedTaskRunner`. To do this, we set `increment-instance-enabled` to be `true`. [[sharing-spring-cloud-dataflows-datastore-with-tasks]] == Sharing Spring Cloud Data Flow's Datastore with Tasks As discussed in the <> documentation Spring Cloud Data Flow allows a user to view Spring Cloud Task App executions. So in this section we will discuss what is required by a Task Application and Spring Cloud Data Flow to share the task execution information. [[a-common-datastore-dependency]] === A Common DataStore Dependency Spring Cloud Data Flow supports many databases out-of-the-box, so all the user typically has to do is declare the `spring_datasource_*` environment variables to establish what data store Spring Cloud Data Flow will need. So whatever database you decide to use for Spring Cloud Data Flow make sure that the your task also includes that database dependency in its `pom.xml` or `gradle.build` file. If the database dependency that is used by Spring Cloud Data Flow is not present in the Task Application, the task will fail and the task execution will not be recorded. [[a-common-datastore]] === A Common Data Store Spring Cloud Data Flow and your task application must access the same datastore instance. This is so that the task executions recorded by the task application can be read by Spring Cloud Data Flow to list them in the Shell and Dashboard views. Also the task app must have read & write privileges to the task data tables that are used by Spring Cloud Data Flow. Given the understanding of Datasource dependency between Task apps and Spring Cloud Data Flow, let's review how to apply them in various Task orchestration scenarios. [[datasource-simple-task-launch]] ==== Simple Task Launch When launching a task from Spring Cloud Data Flow, Data Flow adds its datasource properties (`spring.datasource.url`, `spring.datasource.driverClassName`, `spring.datasource.username`, `spring.datasource.password`) to the app properties of the task being launched. Thus a task application will record its task execution information to the Spring Cloud Data Flow repository. ==== Composed Task Runner Spring Cloud Data Flow allows a user to create a directed graph where each node of the graph is a task application and this is done via the https://github.com/spring-cloud-task-app-starters/composed-task-runner/blob/master/spring-cloud-starter-task-composedtaskrunner/README.adoc[Composed Task Runner]. In this case the rules that applied to a <> or Task Launcher Sink apply to the composed task runner as well. All child apps must also have access to the datastore that is being used by the composed task runner Also, All child apps must have the same database dependency as the composed task runner enumerated in their `pom.xml` or `gradle.build` file. ==== Launching a task externally from Spring Cloud Data Flow Users may wish to launch Spring Cloud Task applications via another method (scheduler for example) but still track the task execution via Spring Cloud Data Flow. This can be done so long as the task applications observe the rules specified <> and <>. NOTE: If a user wishes to use Spring Cloud Data Flow to view their https://projects.spring.io/spring-batch/[Spring Batch] jobs, the user must make sure that their batch application use the `@EnableTask` annotation and follow the rules enumerated <> and <>. More information is available https://github.com/spring-projects/spring-batch-admin/blob/master/MIGRATION.md[here]. [[spring-cloud-dataflow-schedule-launch-tasks]] == Scheduling Tasks Spring Cloud Data Flow lets a user schedule the execution of tasks via a cron expression. A schedule can be created through the RESTful API or the Spring Cloud Data Flow UI. === The Scheduler Spring Cloud Data Flow will schedule the execution of its tasks via a scheduling agent that is available on the cloud platform. When using the Cloud Foundry platform Spring Cloud Data Flow will use the https://www.cloudfoundry.org/the-foundry/scheduler/[PCF Scheduler]. When using Kubernetes, a https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/[CronJob] will be used. NOTE: Scheduled tasks do not implement the continuous deployment feature. Any changes to application version or properties for a task definition via Spring Cloud Data Flow will not affect scheduled tasks. .Architectural Overview image::{dataflow-asciidoc}/images/dataflow-scheduling-architecture.png[Scheduler Architecture Overview, scaledwidth=""50%""] === Enabling Scheduling By default the Spring Cloud Data Flow leaves the scheduling feature disabled. To enable the scheduling feature the following feature properties must be set to `true`: * `spring.cloud.dataflow.features.schedules-enabled` * `spring.cloud.dataflow.features.tasks-enabled` === The Lifecycle of a Schedule The lifecycle of a schedule has 2 parts: * <> * <> * <> [[spring-cloud-data-flow-schedule-scheduling]] ==== Scheduling a Task Execution You can schedule a task execution via the: * Spring Cloud Data Flow Shell * Spring Cloud Data Flow Dashboard * Spring Cloud Data Flow RESTful API ==== Scheduling a Task To schedule a task using the shell, use the `task schedule create` command to create the schedule as shown in the following example: ``` dataflow:>task schedule create --definitionName mytask --name mytaskschedule --expression '*/1 * * * *' Created schedule 'mytaskschedule' ``` In the example above we created a schedule `mytaskschedule` for the task definition `mytask`. This schedule will launch `mytask` once a minute. NOTE: If using Cloud Foundry the cron expression above would be: `*/1 * ? * *`. This is because Cloud Foundry uses the Quartz cron expression format. [[spring-cloud-data-flow-schedule-unscheduling]] ==== Deleting a Schedule You can delete a schedule via the: * Spring Cloud Data Flow Shell * Spring Cloud Data Flow Dashboard * Spring Cloud Data Flow RESTful API To delete a task schedule using the shell, use the `task schedule destroy` command as shown in the following example: ``` dataflow:>task schedule destroy --name mytaskschedule Deleted task schedule 'mytaskschedule' ``` [[spring-cloud-data-flow-schedule-list]] ==== Listing Schedules You can view the available schedules via the: * Spring Cloud Data Flow Shell * Spring Cloud Data Flow Dashboard * Spring Cloud Data Flow RESTful API To view your schedules via the shell use the `task schedule list` command as shown in the following example: [source,bas,options=""nowrap""h] ---- dataflow:>task schedule list ╔══════════════════════════╤════════════════════╤════════════════════════════════════════════════════╗ ║ Schedule Name │Task Definition Name│ Properties ║ ╠══════════════════════════╪════════════════════╪════════════════════════════════════════════════════╣ ║mytaskschedule │mytask │spring.cloud.scheduler.cron.expression = */1 * * * *║ ╚══════════════════════════╧════════════════════╧════════════════════════════════════════════════════╝ ---- NOTE: Instructions to create, delete and list schedules via the Spring Cloud Data Flow UI can be found https://dataflow.spring.io/docs/feature-guides/batch/scheduling/[here]. [[spring-cloud-dataflow-task-cd]] == Continuous Deployment As task applications evolve, you want to get your updates to production. This section walks through the capabilities that Spring Cloud Data Flow provides around being able to update task applications. When a task application is registered (<>), a version is associated with it. A task application can have multiple versions associated with it, with one selected as the default. The following image illustrates an application with multiple versions associated with it (see the timestamp entry). image::{dataflow-asciidoc}/images/dataflow-task-application-versions.png[Task Application Versions, scaledwidth=""50%""] Versions of an application are managed by registering multiple applications with the same name and coordinates, _except_ the version. For example, if you were to register an application with the following values, you would get one application registered with two versions (2.0.0.RELEASE and 2.1.0.RELEASE): * Application 1 ** Name: `timestamp` ** Type: `task` ** URI: `maven://org.springframework.cloud.task.app:timestamp-task:2.0.0.RELEASE` * Application 2 ** Name: `timestamp` ** Type: `task` ** URI: `maven://org.springframework.cloud.task.app:timestamp-task:2.1.0.RELEASE` Besides having multiple versions, Spring Cloud Data Flow needs to know which version to run on the next launch. This is indicated by setting a version to be the default version. Whatever version of a task application is configured as the default version is the one to be run on the next launch request. You can see which version is the default in the UI as this image shows: image::{dataflow-asciidoc}/images/dataflow-task-default-version.png[Task Application Default Version, scaledwidth=""50%""] === Task Launch Lifecycle In previous versions of Spring Cloud Data Flow, when the request to launch a task was received, Spring Cloud Data Flow would deploy the application (if needed) and run it. If the application was being run on a platform that did not need to have the application deployed every time (CloudFoundry for example), the previously deployed application was used. This flow has changed in 2.3. The following image shows what happens when a task launch request comes in now: image::{dataflow-asciidoc}/images/dataflow-task-launch-flow.png[Flow For Launching A Task, scaledwidth=""50%""] There are three main flows to consider in the preceding diagram. Launching the first time or launching with no changes is one. The other is launching when there are changes. We look at the flow with no changes first. ==== Launch a Task With No Changes 1. A launch request comes into to Data Flow. Data Flow determines that an upgrade is not required, since nothing has changed (no properties, deployment properites, or versions have changed since the last execution). [start=5] 5. On platforms that cache a deployed artifact (CloudFoundry at the writing of this documentation), Data Flow checks whether the application was previously deployed. 6. If the application needs to be deployed, Data Flow does the deployment of the task application. 7. Data Flow launches the application. That flow is the default behavior and occurs every time a request comes in if nothing has changed. It is important to note that this is the same flow that Data Flow has always executed for launching of tasks. ==== Launch a Task With Changes That Is Not Currently Running The second flow to consider when launching a task is whether there was a change in any of the task application version, application properties, or deployment properties. In this case, the following flow is executed: 1. A launch request comes into Data Flow. Data Flow determines that an upgrade is required since there was a change in either task application version, application properties, or deployment properties. 2. Data Flow checks to see whether another instance of the task definition is currently running. [start=4] 4. If there is not another instance of the task definition currently running, the old deployment is deleted. 5. On platforms that cache a deployed artifact (CloudFoundry at the writing of this documentation), Data Flow checks whether the application was previously deployed (this check will evaluate to `false` in this flow since the old deployment was deleted). 6. Data Flow does the deployment of the task application with the updated values (new application version, new merged properties, and new merged deployment properties). 7. Data Flow launches the application. This flow is what fundamentally enables continuous deployment for Spring Cloud Data Flow. ==== Launch a Task With Changes While Another Instance Is Running The last main flow is when a launch request comes to Spring Cloud Data Flow to do an upgrade but the task definition is currently running. In this case, the launch is blocked due to the requirement to delete the current application. On some platforms (CloudFoundry at the writing of this document), deleting the application causes all currently running applications to be shut down. This feature prevents that from happening. The following process describes what happens when a task changes while another instance is running: 1. A launch request comes into to Data Flow. Data Flow determines that an upgrade is required, since there was a change in either task application version, application properties, or deployment properties. 2. Data Flow checks to see whether another instance of the task definition is currently running. 3. Data Flow prevents the launch from happening because other instances of the task definition are running. NOTE: Any launch that requires an upgrade of a task definition that is running at the time of the request is blocked from executing due to the need to delete any currently running tasks. ",16186,True,2884.533416366119,median " //// /** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * ""License""); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //// :doctype: book :numbered: :toc: left :icons: font :experimental: [[hbase_default_configurations]] === HBase Default Configuration The documentation below is generated using the default hbase configuration file, _hbase-default.xml_, as source. [[hbase.tmp.dir]] *`hbase.tmp.dir`*:: + .Description Temporary directory on the local filesystem. Change this setting to point to a location more permanent than '/tmp', the usual resolve for java.io.tmpdir, as the '/tmp' directory is cleared on machine restart. + .Default `${java.io.tmpdir}/hbase-${user.name}` [[hbase.rootdir]] *`hbase.rootdir`*:: + .Description The directory shared by region servers and into which HBase persists. The URL should be 'fully-qualified' to include the filesystem scheme. For example, to specify the HDFS directory '/hbase' where the HDFS instance's namenode is running at namenode.example.org on port 9000, set this value to: hdfs://namenode.example.org:9000/hbase. By default, we write to whatever ${hbase.tmp.dir} is set to -- usually /tmp -- so change this configuration or else all data will be lost on machine restart. + .Default `${hbase.tmp.dir}/hbase` [[hbase.cluster.distributed]] *`hbase.cluster.distributed`*:: + .Description The mode the cluster will be in. Possible values are false for standalone mode and true for distributed mode. If false, startup will run all HBase and ZooKeeper daemons together in one JVM. + .Default `false` [[hbase.zookeeper.quorum]] *`hbase.zookeeper.quorum`*:: + .Description Comma separated list of servers in the ZooKeeper ensemble (This config. should have been named hbase.zookeeper.ensemble). For example, ""host1.mydomain.com,host2.mydomain.com,host3.mydomain.com"". By default this is set to localhost for local and pseudo-distributed modes of operation. For a fully-distributed setup, this should be set to a full list of ZooKeeper ensemble servers. If HBASE_MANAGES_ZK is set in hbase-env.sh, this is the list of servers which hbase will start/stop ZooKeeper on as part of cluster start/stop. Client-side, we will take this list of ensemble members and put it together with the hbase.zookeeper.clientPort config and pass it into zookeeper constructor as the connectString parameter. + .Default `localhost` [[hbase.local.dir]] *`hbase.local.dir`*:: + .Description Directory on the local filesystem to be used as a local storage. + .Default `${hbase.tmp.dir}/local/` [[hbase.master.info.port]] *`hbase.master.info.port`*:: + .Description The port for the HBase Master web UI. Set to -1 if you do not want a UI instance run. + .Default `16010` [[hbase.master.info.bindAddress]] *`hbase.master.info.bindAddress`*:: + .Description The bind address for the HBase Master web UI + .Default `0.0.0.0` [[hbase.master.logcleaner.plugins]] *`hbase.master.logcleaner.plugins`*:: + .Description A comma-separated list of BaseLogCleanerDelegate invoked by the LogsCleaner service. These WAL cleaners are called in order, so put the cleaner that prunes the most files in front. To implement your own BaseLogCleanerDelegate, just put it in HBase's classpath and add the fully qualified class name here. Always add the above default log cleaners in the list. + .Default `org.apache.hadoop.hbase.master.cleaner.TimeToLiveLogCleaner` [[hbase.master.logcleaner.ttl]] *`hbase.master.logcleaner.ttl`*:: + .Description Maximum time a WAL can stay in the oldWALs directory, after which it will be cleaned by a Master thread. + .Default `600000` [[hbase.master.hfilecleaner.plugins]] *`hbase.master.hfilecleaner.plugins`*:: + .Description A comma-separated list of BaseHFileCleanerDelegate invoked by the HFileCleaner service. These HFiles cleaners are called in order, so put the cleaner that prunes the most files in front. To implement your own BaseHFileCleanerDelegate, just put it in HBase's classpath and add the fully qualified class name here. Always add the above default log cleaners in the list as they will be overwritten in hbase-site.xml. + .Default `org.apache.hadoop.hbase.master.cleaner.TimeToLiveHFileCleaner` [[hbase.master.infoserver.redirect]] *`hbase.master.infoserver.redirect`*:: + .Description Whether or not the Master listens to the Master web UI port (hbase.master.info.port) and redirects requests to the web UI server shared by the Master and RegionServer. + .Default `true` [[hbase.regionserver.port]] *`hbase.regionserver.port`*:: + .Description The port the HBase RegionServer binds to. + .Default `16020` [[hbase.regionserver.info.port]] *`hbase.regionserver.info.port`*:: + .Description The port for the HBase RegionServer web UI Set to -1 if you do not want the RegionServer UI to run. + .Default `16030` [[hbase.regionserver.info.bindAddress]] *`hbase.regionserver.info.bindAddress`*:: + .Description The address for the HBase RegionServer web UI + .Default `0.0.0.0` [[hbase.regionserver.info.port.auto]] *`hbase.regionserver.info.port.auto`*:: + .Description Whether or not the Master or RegionServer UI should search for a port to bind to. Enables automatic port search if hbase.regionserver.info.port is already in use. Useful for testing, turned off by default. + .Default `false` [[hbase.regionserver.handler.count]] *`hbase.regionserver.handler.count`*:: + .Description Count of RPC Listener instances spun up on RegionServers. Same property is used by the Master for count of master handlers. + .Default `30` [[hbase.ipc.server.callqueue.handler.factor]] *`hbase.ipc.server.callqueue.handler.factor`*:: + .Description Factor to determine the number of call queues. A value of 0 means a single queue shared between all the handlers. A value of 1 means that each handler has its own queue. + .Default `0.1` [[hbase.ipc.server.callqueue.read.ratio]] *`hbase.ipc.server.callqueue.read.ratio`*:: + .Description Split the call queues into read and write queues. The specified interval (which should be between 0.0 and 1.0) will be multiplied by the number of call queues. A value of 0 indicates to not split the call queues, meaning that both read and write requests will be pushed to the same set of queues. A value lower than 0.5 means that there will be less read queues than write queues. A value of 0.5 means there will be the same number of read and write queues. A value greater than 0.5 means that there will be more read queues than write queues. A value of 1.0 means that all the queues except one are used to dispatch read requests. Example: Given the total number of call queues being 10 a read.ratio of 0 means that: the 10 queues will contain both read/write requests. a read.ratio of 0.3 means that: 3 queues will contain only read requests and 7 queues will contain only write requests. a read.ratio of 0.5 means that: 5 queues will contain only read requests and 5 queues will contain only write requests. a read.ratio of 0.8 means that: 8 queues will contain only read requests and 2 queues will contain only write requests. a read.ratio of 1 means that: 9 queues will contain only read requests and 1 queues will contain only write requests. + .Default `0` [[hbase.ipc.server.callqueue.scan.ratio]] *`hbase.ipc.server.callqueue.scan.ratio`*:: + .Description Given the number of read call queues, calculated from the total number of call queues multiplied by the callqueue.read.ratio, the scan.ratio property will split the read call queues into small-read and long-read queues. A value lower than 0.5 means that there will be less long-read queues than short-read queues. A value of 0.5 means that there will be the same number of short-read and long-read queues. A value greater than 0.5 means that there will be more long-read queues than short-read queues A value of 0 or 1 indicates to use the same set of queues for gets and scans. Example: Given the total number of read call queues being 8 a scan.ratio of 0 or 1 means that: 8 queues will contain both long and short read requests. a scan.ratio of 0.3 means that: 2 queues will contain only long-read requests and 6 queues will contain only short-read requests. a scan.ratio of 0.5 means that: 4 queues will contain only long-read requests and 4 queues will contain only short-read requests. a scan.ratio of 0.8 means that: 6 queues will contain only long-read requests and 2 queues will contain only short-read requests. + .Default `0` [[hbase.regionserver.msginterval]] *`hbase.regionserver.msginterval`*:: + .Description Interval between messages from the RegionServer to Master in milliseconds. + .Default `3000` [[hbase.regionserver.regionSplitLimit]] *`hbase.regionserver.regionSplitLimit`*:: + .Description Limit for the number of regions after which no more region splitting should take place. This is not a hard limit for the number of regions but acts as a guideline for the regionserver to stop splitting after a certain limit. Default is MAX_INT; i.e. do not block splitting. + .Default `2147483647` [[hbase.regionserver.logroll.period]] *`hbase.regionserver.logroll.period`*:: + .Description Period at which we will roll the commit log regardless of how many edits it has. + .Default `3600000` [[hbase.regionserver.logroll.errors.tolerated]] *`hbase.regionserver.logroll.errors.tolerated`*:: + .Description The number of consecutive WAL close errors we will allow before triggering a server abort. A setting of 0 will cause the region server to abort if closing the current WAL writer fails during log rolling. Even a small value (2 or 3) will allow a region server to ride over transient HDFS errors. + .Default `2` [[hbase.regionserver.hlog.reader.impl]] *`hbase.regionserver.hlog.reader.impl`*:: + .Description The WAL file reader implementation. + .Default `org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader` [[hbase.regionserver.hlog.writer.impl]] *`hbase.regionserver.hlog.writer.impl`*:: + .Description The WAL file writer implementation. + .Default `org.apache.hadoop.hbase.regionserver.wal.ProtobufLogWriter` [[hbase.regionserver.global.memstore.size]] *`hbase.regionserver.global.memstore.size`*:: + .Description Maximum size of all memstores in a region server before new updates are blocked and flushes are forced. Defaults to 40% of heap. Updates are blocked and flushes are forced until size of all memstores in a region server hits hbase.regionserver.global.memstore.size.lower.limit. + .Default `0.4` [[hbase.regionserver.global.memstore.size.lower.limit]] *`hbase.regionserver.global.memstore.size.lower.limit`*:: + .Description Maximum size of all memstores in a region server before flushes are forced. Defaults to 95% of hbase.regionserver.global.memstore.size. A 100% value for this property causes the minimum possible flushing to occur when updates are blocked due to memstore limiting. + .Default `0.95` [[hbase.regionserver.optionalcacheflushinterval]] *`hbase.regionserver.optionalcacheflushinterval`*:: + .Description Maximum amount of time an edit lives in memory before being automatically flushed. Default 1 hour. Set it to 0 to disable automatic flushing. + .Default `3600000` [[hbase.regionserver.dns.interface]] *`hbase.regionserver.dns.interface`*:: + .Description The name of the Network Interface from which a region server should report its IP address. + .Default `default` [[hbase.regionserver.dns.nameserver]] *`hbase.regionserver.dns.nameserver`*:: + .Description The host name or IP address of the name server (DNS) which a region server should use to determine the host name used by the master for communication and display purposes. + .Default `default` [[hbase.regionserver.region.split.policy]] *`hbase.regionserver.region.split.policy`*:: + .Description A split policy determines when a region should be split. The various other split policies that are available currently are ConstantSizeRegionSplitPolicy, DisabledRegionSplitPolicy, DelimitedKeyPrefixRegionSplitPolicy, KeyPrefixRegionSplitPolicy, BusyRegionSplitPolicy, SteppingSplitPolicy etc. + .Default `org.apache.hadoop.hbase.regionserver.SteppingSplitPolicy` [[zookeeper.session.timeout]] *`zookeeper.session.timeout`*:: + .Description ZooKeeper session timeout in milliseconds. It is used in two different ways. First, this value is used in the ZK client that HBase uses to connect to the ensemble. It is also used by HBase when it starts a ZK server and it is passed as the 'maxSessionTimeout'. See https://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#ch_zkSessions. For example, if an HBase region server connects to a ZK ensemble that's also managed by HBase, then the session timeout will be the one specified by this configuration. But, a region server that connects to an ensemble managed with a different configuration will be subjected that ensemble's maxSessionTimeout. So, even though HBase might propose using 90 seconds, the ensemble can have a max timeout lower than this and it will take precedence. The current default maxSessionTimeout that ZK ships with is 40 seconds, which is lower than HBase's. + .Default `90000` [[zookeeper.znode.parent]] *`zookeeper.znode.parent`*:: + .Description Root ZNode for HBase in ZooKeeper. All of HBase's ZooKeeper files that are configured with a relative path will go under this node. By default, all of HBase's ZooKeeper file path are configured with a relative path, so they will all go under this directory unless changed. + .Default `/hbase` [[zookeeper.znode.acl.parent]] *`zookeeper.znode.acl.parent`*:: + .Description Root ZNode for access control lists. + .Default `acl` [[hbase.zookeeper.dns.interface]] *`hbase.zookeeper.dns.interface`*:: + .Description The name of the Network Interface from which a ZooKeeper server should report its IP address. + .Default `default` [[hbase.zookeeper.dns.nameserver]] *`hbase.zookeeper.dns.nameserver`*:: + .Description The host name or IP address of the name server (DNS) which a ZooKeeper server should use to determine the host name used by the master for communication and display purposes. + .Default `default` [[hbase.zookeeper.peerport]] *`hbase.zookeeper.peerport`*:: + .Description Port used by ZooKeeper peers to talk to each other. See https://zookeeper.apache.org/doc/r3.4.10/zookeeperStarted.html#sc_RunningReplicatedZooKeeper for more information. + .Default `2888` [[hbase.zookeeper.leaderport]] *`hbase.zookeeper.leaderport`*:: + .Description Port used by ZooKeeper for leader election. See https://zookeeper.apache.org/doc/r3.4.10/zookeeperStarted.html#sc_RunningReplicatedZooKeeper for more information. + .Default `3888` [[hbase.zookeeper.useMulti]] *`hbase.zookeeper.useMulti`*:: + .Description Instructs HBase to make use of ZooKeeper's multi-update functionality. This allows certain ZooKeeper operations to complete more quickly and prevents some issues with rare Replication failure scenarios (see the release note of HBASE-2611 for an example). IMPORTANT: only set this to true if all ZooKeeper servers in the cluster are on version 3.4+ and will not be downgraded. ZooKeeper versions before 3.4 do not support multi-update and will not fail gracefully if multi-update is invoked (see ZOOKEEPER-1495). + .Default `true` [[hbase.zookeeper.property.initLimit]] *`hbase.zookeeper.property.initLimit`*:: + .Description Property from ZooKeeper's config zoo.cfg. The number of ticks that the initial synchronization phase can take. + .Default `10` [[hbase.zookeeper.property.syncLimit]] *`hbase.zookeeper.property.syncLimit`*:: + .Description Property from ZooKeeper's config zoo.cfg. The number of ticks that can pass between sending a request and getting an acknowledgment. + .Default `5` [[hbase.zookeeper.property.dataDir]] *`hbase.zookeeper.property.dataDir`*:: + .Description Property from ZooKeeper's config zoo.cfg. The directory where the snapshot is stored. + .Default `${hbase.tmp.dir}/zookeeper` [[hbase.zookeeper.property.clientPort]] *`hbase.zookeeper.property.clientPort`*:: + .Description Property from ZooKeeper's config zoo.cfg. The port at which the clients will connect. + .Default `2181` [[hbase.zookeeper.property.maxClientCnxns]] *`hbase.zookeeper.property.maxClientCnxns`*:: + .Description Property from ZooKeeper's config zoo.cfg. Limit on number of concurrent connections (at the socket level) that a single client, identified by IP address, may make to a single member of the ZooKeeper ensemble. Set high to avoid zk connection issues running standalone and pseudo-distributed. + .Default `300` [[hbase.client.write.buffer]] *`hbase.client.write.buffer`*:: + .Description Default size of the BufferedMutator write buffer in bytes. A bigger buffer takes more memory -- on both the client and server side since server instantiates the passed write buffer to process it -- but a larger buffer size reduces the number of RPCs made. For an estimate of server-side memory-used, evaluate hbase.client.write.buffer * hbase.regionserver.handler.count + .Default `2097152` [[hbase.client.pause]] *`hbase.client.pause`*:: + .Description General client pause value. Used mostly as value to wait before running a retry of a failed get, region lookup, etc. See hbase.client.retries.number for description of how we backoff from this initial pause amount and how this pause works w/ retries. + .Default `100` [[hbase.client.retries.number]] *`hbase.client.retries.number`*:: + .Description Maximum retries. Used as maximum for all retryable operations such as the getting of a cell's value, starting a row update, etc. Retry interval is a rough function based on hbase.client.pause. At first we retry at this interval but then with backoff, we pretty quickly reach retrying every ten seconds. See HConstants#RETRY_BACKOFF for how the backup ramps up. Change this setting and hbase.client.pause to suit your workload. + .Default `35` [[hbase.client.max.total.tasks]] *`hbase.client.max.total.tasks`*:: + .Description The maximum number of concurrent tasks a single HTable instance will send to the cluster. + .Default `100` [[hbase.client.max.perserver.tasks]] *`hbase.client.max.perserver.tasks`*:: + .Description The maximum number of concurrent tasks a single HTable instance will send to a single region server. + .Default `2` [[hbase.client.max.perregion.tasks]] *`hbase.client.max.perregion.tasks`*:: + .Description The maximum number of concurrent connections the client will maintain to a single Region. That is, if there is already hbase.client.max.perregion.tasks writes in progress for this region, new puts won't be sent to this region until some writes finish. + .Default `1` [[hbase.client.scanner.caching]] *`hbase.client.scanner.caching`*:: + .Description Number of rows that will be fetched when calling next on a scanner if it is not served from (local, client) memory. Higher caching values will enable faster scanners but will eat up more memory and some calls of next may take longer and longer times when the cache is empty. Do not set this value such that the time between invocations is greater than the scanner timeout; i.e. hbase.client.scanner.timeout.period + .Default `100` [[hbase.client.keyvalue.maxsize]] *`hbase.client.keyvalue.maxsize`*:: + .Description Specifies the combined maximum allowed size of a KeyValue instance. This is to set an upper boundary for a single entry saved in a storage file. Since they cannot be split it helps avoiding that a region cannot be split any further because the data is too large. It seems wise to set this to a fraction of the maximum region size. Setting it to zero or less disables the check. + .Default `10485760` [[hbase.client.scanner.timeout.period]] *`hbase.client.scanner.timeout.period`*:: + .Description Client scanner lease period in milliseconds. + .Default `60000` [[hbase.client.localityCheck.threadPoolSize]] *`hbase.client.localityCheck.threadPoolSize`*:: + .Description + .Default `2` [[hbase.bulkload.retries.number]] *`hbase.bulkload.retries.number`*:: + .Description Maximum retries. This is a maximum number of iterations atomic bulk loads are attempted in the face of splitting operations, 0 means never give up. + .Default `10` [[hbase.compaction.after.bulkload.enable]] *`hbase.compaction.after.bulkload.enable`*:: + .Description Request Compaction after bulkload immediately. If bulkload is continuous, the triggered compactions may increase load, bring about performance side effect. (For HBase-2.x, the default value for ""hbase.compaction.after.bulkload.enable"" is true) + .Default `false` [[hbase.balancer.period ]] *`hbase.balancer.period `*:: + .Description Period at which the region balancer runs in the Master. + .Default `300000` [[hbase.regions.slop]] *`hbase.regions.slop`*:: + .Description Rebalance if any regionserver has average + (average * slop) regions. + .Default `0.2` [[hbase.server.thread.wakefrequency]] *`hbase.server.thread.wakefrequency`*:: + .Description Time to sleep in between searches for work (in milliseconds). Used as sleep interval by service threads such as log roller. + .Default `10000` [[hbase.server.versionfile.writeattempts]] *`hbase.server.versionfile.writeattempts`*:: + .Description How many time to retry attempting to write a version file before just aborting. Each attempt is separated by the hbase.server.thread.wakefrequency milliseconds. + .Default `3` [[hbase.hregion.memstore.flush.size]] *`hbase.hregion.memstore.flush.size`*:: + .Description Memstore will be flushed to disk if size of the memstore exceeds this number of bytes. Value is checked by a thread that runs every hbase.server.thread.wakefrequency. + .Default `134217728` [[hbase.hregion.percolumnfamilyflush.size.lower.bound]] *`hbase.hregion.percolumnfamilyflush.size.lower.bound`*:: + .Description If FlushLargeStoresPolicy is used, then every time that we hit the total memstore limit, we find out all the column families whose memstores exceed this value, and only flush them, while retaining the others whose memstores are lower than this limit. If none of the families have their memstore size more than this, all the memstores will be flushed (just as usual). This value should be less than half of the total memstore threshold (hbase.hregion.memstore.flush.size). + .Default `16777216` [[hbase.hregion.preclose.flush.size]] *`hbase.hregion.preclose.flush.size`*:: + .Description If the memstores in a region are this size or larger when we go to close, run a ""pre-flush"" to clear out memstores before we put up the region closed flag and take the region offline. On close, a flush is run under the close flag to empty memory. During this time the region is offline and we are not taking on any writes. If the memstore content is large, this flush could take a long time to complete. The preflush is meant to clean out the bulk of the memstore before putting up the close flag and taking the region offline so the flush that runs under the close flag has little to do. + .Default `5242880` [[hbase.hregion.memstore.block.multiplier]] *`hbase.hregion.memstore.block.multiplier`*:: + .Description Block updates if memstore has hbase.hregion.memstore.block.multiplier times hbase.hregion.memstore.flush.size bytes. Useful preventing runaway memstore during spikes in update traffic. Without an upper-bound, memstore fills such that when it flushes the resultant flush files take a long time to compact or split, or worse, we OOME. + .Default `4` [[hbase.hregion.memstore.mslab.enabled]] *`hbase.hregion.memstore.mslab.enabled`*:: + .Description Enables the MemStore-Local Allocation Buffer, a feature which works to prevent heap fragmentation under heavy write loads. This can reduce the frequency of stop-the-world GC pauses on large heaps. + .Default `true` [[hbase.hregion.max.filesize]] *`hbase.hregion.max.filesize`*:: + .Description Maximum file size. If the sum of the sizes of a region's HFiles has grown to exceed this value, the region is split in two. There are two choices of how this option works, the first is when any store's size exceed the threshold then split, and the other is overall region's size exceed the threshold then split, it can be configed by hbase.hregion.split.overallfiles. + .Default `10737418240` [[hbase.hregion.split.overallfiles]] *`hbase.hregion.split.overallfiles`*:: + .Description If we should sum overall region files size when check to split. + .Default `true` [[hbase.hregion.majorcompaction]] *`hbase.hregion.majorcompaction`*:: + .Description Time between major compactions, expressed in milliseconds. Set to 0 to disable time-based automatic major compactions. User-requested and size-based major compactions will still run. This value is multiplied by hbase.hregion.majorcompaction.jitter to cause compaction to start at a somewhat-random time during a given window of time. The default value is 7 days, expressed in milliseconds. If major compactions are causing disruption in your environment, you can configure them to run at off-peak times for your deployment, or disable time-based major compactions by setting this parameter to 0, and run major compactions in a cron job or by another external mechanism. + .Default `604800000` [[hbase.hregion.majorcompaction.jitter]] *`hbase.hregion.majorcompaction.jitter`*:: + .Description A multiplier applied to hbase.hregion.majorcompaction to cause compaction to occur a given amount of time either side of hbase.hregion.majorcompaction. The smaller the number, the closer the compactions will happen to the hbase.hregion.majorcompaction interval. + .Default `0.50` [[hbase.hstore.compactionThreshold]] *`hbase.hstore.compactionThreshold`*:: + .Description If more than this number of StoreFiles exist in any one Store (one StoreFile is written per flush of MemStore), a compaction is run to rewrite all StoreFiles into a single StoreFile. Larger values delay compaction, but when compaction does occur, it takes longer to complete. + .Default `3` [[hbase.hstore.flusher.count]] *`hbase.hstore.flusher.count`*:: + .Description The number of flush threads. With fewer threads, the MemStore flushes will be queued. With more threads, the flushes will be executed in parallel, increasing the load on HDFS, and potentially causing more compactions. + .Default `2` [[hbase.hstore.blockingStoreFiles]] *`hbase.hstore.blockingStoreFiles`*:: + .Description If more than this number of StoreFiles exist in any one Store (one StoreFile is written per flush of MemStore), updates are blocked for this region until a compaction is completed, or until hbase.hstore.blockingWaitTime has been exceeded. + .Default `10` [[hbase.hstore.blockingWaitTime]] *`hbase.hstore.blockingWaitTime`*:: + .Description The time for which a region will block updates after reaching the StoreFile limit defined by hbase.hstore.blockingStoreFiles. After this time has elapsed, the region will stop blocking updates even if a compaction has not been completed. + .Default `90000` [[hbase.hstore.compaction.min]] *`hbase.hstore.compaction.min`*:: + .Description The minimum number of StoreFiles which must be eligible for compaction before compaction can run. The goal of tuning hbase.hstore.compaction.min is to avoid ending up with too many tiny StoreFiles to compact. Setting this value to 2 would cause a minor compaction each time you have two StoreFiles in a Store, and this is probably not appropriate. If you set this value too high, all the other values will need to be adjusted accordingly. For most cases, the default value is appropriate. In previous versions of HBase, the parameter hbase.hstore.compaction.min was named hbase.hstore.compactionThreshold. + .Default `3` [[hbase.hstore.compaction.max]] *`hbase.hstore.compaction.max`*:: + .Description The maximum number of StoreFiles which will be selected for a single minor compaction, regardless of the number of eligible StoreFiles. Effectively, the value of hbase.hstore.compaction.max controls the length of time it takes a single compaction to complete. Setting it larger means that more StoreFiles are included in a compaction. For most cases, the default value is appropriate. + .Default `10` [[hbase.hstore.compaction.min.size]] *`hbase.hstore.compaction.min.size`*:: + .Description A StoreFile smaller than this size will always be eligible for minor compaction. HFiles this size or larger are evaluated by hbase.hstore.compaction.ratio to determine if they are eligible. Because this limit represents the ""automatic include""limit for all StoreFiles smaller than this value, this value may need to be reduced in write-heavy environments where many StoreFiles in the 1-2 MB range are being flushed, because every StoreFile will be targeted for compaction and the resulting StoreFiles may still be under the minimum size and require further compaction. If this parameter is lowered, the ratio check is triggered more quickly. This addressed some issues seen in earlier versions of HBase but changing this parameter is no longer necessary in most situations. Default: 128 MB expressed in bytes. + .Default `134217728` [[hbase.hstore.compaction.max.size]] *`hbase.hstore.compaction.max.size`*:: + .Description A StoreFile larger than this size will be excluded from compaction. The effect of raising hbase.hstore.compaction.max.size is fewer, larger StoreFiles that do not get compacted often. If you feel that compaction is happening too often without much benefit, you can try raising this value. Default: the value of LONG.MAX_VALUE, expressed in bytes. + .Default `9223372036854775807` [[hbase.hstore.compaction.ratio]] *`hbase.hstore.compaction.ratio`*:: + .Description For minor compaction, this ratio is used to determine whether a given StoreFile which is larger than hbase.hstore.compaction.min.size is eligible for compaction. Its effect is to limit compaction of large StoreFiles. The value of hbase.hstore.compaction.ratio is expressed as a floating-point decimal. A large ratio, such as 10, will produce a single giant StoreFile. Conversely, a low value, such as .25, will produce behavior similar to the BigTable compaction algorithm, producing four StoreFiles. A moderate value of between 1.0 and 1.4 is recommended. When tuning this value, you are balancing write costs with read costs. Raising the value (to something like 1.4) will have more write costs, because you will compact larger StoreFiles. However, during reads, HBase will need to seek through fewer StoreFiles to accomplish the read. Consider this approach if you cannot take advantage of Bloom filters. Otherwise, you can lower this value to something like 1.0 to reduce the background cost of writes, and use Bloom filters to control the number of StoreFiles touched during reads. For most cases, the default value is appropriate. + .Default `1.2F` [[hbase.hstore.compaction.ratio.offpeak]] *`hbase.hstore.compaction.ratio.offpeak`*:: + .Description Allows you to set a different (by default, more aggressive) ratio for determining whether larger StoreFiles are included in compactions during off-peak hours. Works in the same way as hbase.hstore.compaction.ratio. Only applies if hbase.offpeak.start.hour and hbase.offpeak.end.hour are also enabled. + .Default `5.0F` [[hbase.hstore.time.to.purge.deletes]] *`hbase.hstore.time.to.purge.deletes`*:: + .Description The amount of time to delay purging of delete markers with future timestamps. If unset, or set to 0, all delete markers, including those with future timestamps, are purged during the next major compaction. Otherwise, a delete marker is kept until the major compaction which occurs after the marker's timestamp plus the value of this setting, in milliseconds. + .Default `0` [[hbase.offpeak.start.hour]] *`hbase.offpeak.start.hour`*:: + .Description The start of off-peak hours, expressed as an integer between 0 and 23, inclusive. Set to -1 to disable off-peak. + .Default `-1` [[hbase.offpeak.end.hour]] *`hbase.offpeak.end.hour`*:: + .Description The end of off-peak hours, expressed as an integer between 0 and 23, inclusive. Set to -1 to disable off-peak. + .Default `-1` [[hbase.regionserver.thread.compaction.throttle]] *`hbase.regionserver.thread.compaction.throttle`*:: + .Description There are two different thread pools for compactions, one for large compactions and the other for small compactions. This helps to keep compaction of lean tables (such as hbase:meta) fast. If a compaction is larger than this threshold, it goes into the large compaction pool. In most cases, the default value is appropriate. Default: 2 x hbase.hstore.compaction.max x hbase.hregion.memstore.flush.size (which defaults to 128MB). The value field assumes that the value of hbase.hregion.memstore.flush.size is unchanged from the default. + .Default `2684354560` [[hbase.hstore.compaction.kv.max]] *`hbase.hstore.compaction.kv.max`*:: + .Description The maximum number of KeyValues to read and then write in a batch when flushing or compacting. Set this lower if you have big KeyValues and problems with Out Of Memory Exceptions Set this higher if you have wide, small rows. + .Default `10` [[hbase.storescanner.parallel.seek.enable]] *`hbase.storescanner.parallel.seek.enable`*:: + .Description Enables StoreFileScanner parallel-seeking in StoreScanner, a feature which can reduce response latency under special conditions. + .Default `false` [[hbase.storescanner.parallel.seek.threads]] *`hbase.storescanner.parallel.seek.threads`*:: + .Description The default thread pool size if parallel-seeking feature enabled. + .Default `10` [[hfile.block.cache.size]] *`hfile.block.cache.size`*:: + .Description Percentage of maximum heap (-Xmx setting) to allocate to block cache used by a StoreFile. Default of 0.4 means allocate 40%. Set to 0 to disable but it's not recommended; you need at least enough cache to hold the storefile indices. + .Default `0.4` [[hfile.block.index.cacheonwrite]] *`hfile.block.index.cacheonwrite`*:: + .Description This allows to put non-root multi-level index blocks into the block cache at the time the index is being written. + .Default `false` [[hfile.index.block.max.size]] *`hfile.index.block.max.size`*:: + .Description When the size of a leaf-level, intermediate-level, or root-level index block in a multi-level block index grows to this size, the block is written out and a new block is started. + .Default `131072` [[hbase.bucketcache.ioengine]] *`hbase.bucketcache.ioengine`*:: + .Description Where to store the contents of the bucketcache. One of: offheap, file, files, mmap or pmem. If a file or files, set it to file(s):PATH_TO_FILE. mmap means the content will be in an mmaped file. Use mmap:PATH_TO_FILE. 'pmem' is bucket cache over a file on the persistent memory device. Use pmem:PATH_TO_FILE. See https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/io/hfile/CacheConfig.html for more information. + .Default `` [[hbase.bucketcache.combinedcache.enabled]] *`hbase.bucketcache.combinedcache.enabled`*:: + .Description Whether or not the bucketcache is used in league with the LRU on-heap block cache. In this mode, indices and blooms are kept in the LRU blockcache and the data blocks are kept in the bucketcache. + .Default `true` [[hbase.bucketcache.size]] *`hbase.bucketcache.size`*:: + .Description Used along with bucket cache, this is a float that EITHER represents a percentage of total heap memory size to give to the cache (if < 1.0) OR, it is the capacity in megabytes of the cache. (After HBase-2.0, ""hbase.bucketcache.size"" cannot be between 0-1) + .Default `0` when specified as a float [[hbase.bucketcache.bucket.sizes]] *`hbase.bucketcache.bucket.sizes`*:: + .Description A comma-separated list of sizes for buckets for the bucketcache if you use multiple sizes. Should be a list of block sizes in order from smallest to largest. The sizes you use will depend on your data access patterns. + .Default `` [[hfile.format.version]] *`hfile.format.version`*:: + .Description The HFile format version to use for new files. Version 3 adds support for tags in hfiles (See https://hbase.apache.org/book.html#hbase.tags). Also see the configuration 'hbase.replication.rpc.codec'. + .Default `3` [[hfile.block.bloom.cacheonwrite]] *`hfile.block.bloom.cacheonwrite`*:: + .Description Enables cache-on-write for inline blocks of a compound Bloom filter. + .Default `false` [[io.storefile.bloom.block.size]] *`io.storefile.bloom.block.size`*:: + .Description The size in bytes of a single block (""chunk"") of a compound Bloom filter. This size is approximate, because Bloom blocks can only be inserted at data block boundaries, and the number of keys per data block varies. + .Default `131072` [[hbase.rs.cacheblocksonwrite]] *`hbase.rs.cacheblocksonwrite`*:: + .Description Whether an HFile block should be added to the block cache when the block is finished. + .Default `false` [[hbase.rpc.timeout]] *`hbase.rpc.timeout`*:: + .Description This is for the RPC layer to define how long HBase client applications take for a remote call to time out. It uses pings to check connections but will eventually throw a TimeoutException. + .Default `60000` [[hbase.rpc.shortoperation.timeout]] *`hbase.rpc.shortoperation.timeout`*:: + .Description This is another version of ""hbase.rpc.timeout"". For those RPC operations within cluster, we rely on this configuration to set a short timeout limitation for short operations. For example, short rpc timeout for region server trying to report to active master can benefit from quicker master failover process. + .Default `10000` [[hbase.ipc.client.tcpnodelay]] *`hbase.ipc.client.tcpnodelay`*:: + .Description Set no delay on rpc socket connections. See http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getTcpNoDelay-- + .Default `true` [[hbase.master.keytab.file]] *`hbase.master.keytab.file`*:: + .Description Full path to the kerberos keytab file to use for logging in the configured HMaster server principal. + .Default `` [[hbase.master.kerberos.principal]] *`hbase.master.kerberos.principal`*:: + .Description Ex. ""hbase/_HOST@EXAMPLE.COM"". The kerberos principal name that should be used to run the HMaster process. The principal name should be in the form: user/hostname@DOMAIN. If ""_HOST"" is used as the hostname portion, it will be replaced with the actual hostname of the running instance. + .Default `` [[hbase.regionserver.keytab.file]] *`hbase.regionserver.keytab.file`*:: + .Description Full path to the kerberos keytab file to use for logging in the configured HRegionServer server principal. + .Default `` [[hbase.regionserver.kerberos.principal]] *`hbase.regionserver.kerberos.principal`*:: + .Description Ex. ""hbase/_HOST@EXAMPLE.COM"". The kerberos principal name that should be used to run the HRegionServer process. The principal name should be in the form: user/hostname@DOMAIN. If ""_HOST"" is used as the hostname portion, it will be replaced with the actual hostname of the running instance. An entry for this principal must exist in the file specified in hbase.regionserver.keytab.file + .Default `` [[hadoop.policy.file]] *`hadoop.policy.file`*:: + .Description The policy configuration file used by RPC servers to make authorization decisions on client requests. Only used when HBase security is enabled. + .Default `hbase-policy.xml` [[hbase.superuser]] *`hbase.superuser`*:: + .Description List of users or groups (comma-separated), who are allowed full privileges, regardless of stored ACLs, across the cluster. Only used when HBase security is enabled. + .Default `` [[hbase.auth.key.update.interval]] *`hbase.auth.key.update.interval`*:: + .Description The update interval for master key for authentication tokens in servers in milliseconds. Only used when HBase security is enabled. + .Default `86400000` [[hbase.auth.token.max.lifetime]] *`hbase.auth.token.max.lifetime`*:: + .Description The maximum lifetime in milliseconds after which an authentication token expires. Only used when HBase security is enabled. + .Default `604800000` [[hbase.ipc.client.fallback-to-simple-auth-allowed]] *`hbase.ipc.client.fallback-to-simple-auth-allowed`*:: + .Description When a client is configured to attempt a secure connection, but attempts to connect to an insecure server, that server may instruct the client to switch to SASL SIMPLE (unsecure) authentication. This setting controls whether or not the client will accept this instruction from the server. When false (the default), the client will not allow the fallback to SIMPLE authentication, and will abort the connection. + .Default `false` [[hbase.display.keys]] *`hbase.display.keys`*:: + .Description When this is set to true the webUI and such will display all start/end keys as part of the table details, region names, etc. When this is set to false, the keys are hidden. + .Default `true` [[hbase.coprocessor.region.classes]] *`hbase.coprocessor.region.classes`*:: + .Description A comma-separated list of Coprocessors that are loaded by default on all tables. For any override coprocessor method, these classes will be called in order. After implementing your own Coprocessor, just put it in HBase's classpath and add the fully qualified class name here. A coprocessor can also be loaded on demand by setting HTableDescriptor. + .Default `` [[hbase.rest.port]] *`hbase.rest.port`*:: + .Description The port for the HBase REST server. + .Default `8080` [[hbase.rest.readonly]] *`hbase.rest.readonly`*:: + .Description Defines the mode the REST server will be started in. Possible values are: false: All HTTP methods are permitted - GET/PUT/POST/DELETE. true: Only the GET method is permitted. + .Default `false` [[hbase.rest.threads.max]] *`hbase.rest.threads.max`*:: + .Description The maximum number of threads of the REST server thread pool. Threads in the pool are reused to process REST requests. This controls the maximum number of requests processed concurrently. It may help to control the memory used by the REST server to avoid OOM issues. If the thread pool is full, incoming requests will be queued up and wait for some free threads. + .Default `100` [[hbase.rest.threads.min]] *`hbase.rest.threads.min`*:: + .Description The minimum number of threads of the REST server thread pool. The thread pool always has at least these number of threads so the REST server is ready to serve incoming requests. + .Default `2` [[hbase.rest.support.proxyuser]] *`hbase.rest.support.proxyuser`*:: + .Description Enables running the REST server to support proxy-user mode. + .Default `false` [[hbase.defaults.for.version.skip]] *`hbase.defaults.for.version.skip`*:: + .Description Set to true to skip the 'hbase.defaults.for.version' check. Setting this to true can be useful in contexts other than the other side of a maven generation; i.e. running in an ide. You'll want to set this boolean to true to avoid seeing the RuntimeException complaint: ""hbase-default.xml file seems to be for and old version of HBase (\\${hbase.version}), this version is X.X.X-SNAPSHOT"" + .Default `false` [[hbase.coprocessor.master.classes]] *`hbase.coprocessor.master.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.coprocessor.MasterObserver coprocessors that are loaded by default on the active HMaster process. For any implemented coprocessor methods, the listed classes will be called in order. After implementing your own MasterObserver, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.coprocessor.abortonerror]] *`hbase.coprocessor.abortonerror`*:: + .Description Set to true to cause the hosting server (master or regionserver) to abort if a coprocessor fails to load, fails to initialize, or throws an unexpected Throwable object. Setting this to false will allow the server to continue execution but the system wide state of the coprocessor in question will become inconsistent as it will be properly executing in only a subset of servers, so this is most useful for debugging only. + .Default `true` [[hbase.table.lock.enable]] *`hbase.table.lock.enable`*:: + .Description Set to true to enable locking the table in zookeeper for schema change operations. Table locking from master prevents concurrent schema modifications to corrupt table state. + .Default `true` [[hbase.table.max.rowsize]] *`hbase.table.max.rowsize`*:: + .Description Maximum size of single row in bytes (default is 1 Gb) for Get'ting or Scan'ning without in-row scan flag set. If row size exceeds this limit RowTooBigException is thrown to client. + .Default `1073741824` [[hbase.thrift.minWorkerThreads]] *`hbase.thrift.minWorkerThreads`*:: + .Description The ""core size"" of the thread pool. New threads are created on every connection until this many threads are created. + .Default `16` [[hbase.thrift.maxWorkerThreads]] *`hbase.thrift.maxWorkerThreads`*:: + .Description The maximum size of the thread pool. When the pending request queue overflows, new threads are created until their number reaches this number. After that, the server starts dropping connections. + .Default `1000` [[hbase.thrift.maxQueuedRequests]] *`hbase.thrift.maxQueuedRequests`*:: + .Description The maximum number of pending Thrift connections waiting in the queue. If there are no idle threads in the pool, the server queues requests. Only when the queue overflows, new threads are added, up to hbase.thrift.maxQueuedRequests threads. + .Default `1000` [[hbase.regionserver.thrift.framed]] *`hbase.regionserver.thrift.framed`*:: + .Description Use Thrift TFramedTransport on the server side. This is the recommended transport for thrift servers and requires a similar setting on the client side. Changing this to false will select the default transport, vulnerable to DoS when malformed requests are issued due to THRIFT-601. + .Default `false` [[hbase.regionserver.thrift.framed.max_frame_size_in_mb]] *`hbase.regionserver.thrift.framed.max_frame_size_in_mb`*:: + .Description Default frame size when using framed transport + .Default `2` [[hbase.regionserver.thrift.compact]] *`hbase.regionserver.thrift.compact`*:: + .Description Use Thrift TCompactProtocol binary serialization protocol. + .Default `false` [[hbase.data.umask.enable]] *`hbase.data.umask.enable`*:: + .Description Enable, if true, that file permissions should be assigned to the files written by the regionserver + .Default `false` [[hbase.data.umask]] *`hbase.data.umask`*:: + .Description File permissions that should be used to write data files when hbase.data.umask.enable is true + .Default `000` [[hbase.snapshot.enabled]] *`hbase.snapshot.enabled`*:: + .Description Set to true to allow snapshots to be taken / restored / cloned. + .Default `true` [[hbase.snapshot.restore.take.failsafe.snapshot]] *`hbase.snapshot.restore.take.failsafe.snapshot`*:: + .Description Set to true to take a snapshot before the restore operation. The snapshot taken will be used in case of failure, to restore the previous state. At the end of the restore operation this snapshot will be deleted + .Default `true` [[hbase.snapshot.restore.failsafe.name]] *`hbase.snapshot.restore.failsafe.name`*:: + .Description Name of the failsafe snapshot taken by the restore operation. You can use the {snapshot.name}, {table.name} and {restore.timestamp} variables to create a name based on what you are restoring. + .Default `hbase-failsafe-{snapshot.name}-{restore.timestamp}` [[hbase.server.compactchecker.interval.multiplier]] *`hbase.server.compactchecker.interval.multiplier`*:: + .Description The number that determines how often we scan to see if compaction is necessary. Normally, compactions are done after some events (such as memstore flush), but if region didn't receive a lot of writes for some time, or due to different compaction policies, it may be necessary to check it periodically. The interval between checks is hbase.server.compactchecker.interval.multiplier multiplied by hbase.server.thread.wakefrequency. + .Default `1000` [[hbase.lease.recovery.timeout]] *`hbase.lease.recovery.timeout`*:: + .Description How long we wait on dfs lease recovery in total before giving up. + .Default `900000` [[hbase.lease.recovery.dfs.timeout]] *`hbase.lease.recovery.dfs.timeout`*:: + .Description How long between dfs recovery lease invocations. Should be larger than the sum of the time it takes for the namenode to issue a block recovery command as part of datanode dfs.heartbeat.interval and the time it takes for the primary datanode performing block recovery to timeout on a dead datanode, usually dfs.client.socket-timeout. See the end of HBASE-8389 for more. + .Default `64000` [[hbase.column.max.version]] *`hbase.column.max.version`*:: + .Description New column family descriptors will use this value as the default number of versions to keep. + .Default `1` [[hbase.dfs.client.read.shortcircuit.buffer.size]] *`hbase.dfs.client.read.shortcircuit.buffer.size`*:: + .Description If the DFSClient configuration dfs.client.read.shortcircuit.buffer.size is unset, we will use what is configured here as the short circuit read default direct byte buffer size. DFSClient native default is 1MB; HBase keeps its HDFS files open so number of file blocks * 1MB soon starts to add up and threaten OOME because of a shortage of direct memory. So, we set it down from the default. Make it > the default hbase block size set in the HColumnDescriptor which is usually 64k. + .Default `131072` [[hbase.regionserver.checksum.verify]] *`hbase.regionserver.checksum.verify`*:: + .Description If set to true (the default), HBase verifies the checksums for hfile blocks. HBase writes checksums inline with the data when it writes out hfiles. HDFS (as of this writing) writes checksums to a separate file than the data file necessitating extra seeks. Setting this flag saves some on i/o. Checksum verification by HDFS will be internally disabled on hfile streams when this flag is set. If the hbase-checksum verification fails, we will switch back to using HDFS checksums (so do not disable HDFS checksums! And besides this feature applies to hfiles only, not to WALs). If this parameter is set to false, then hbase will not verify any checksums, instead it will depend on checksum verification being done in the HDFS client. + .Default `true` [[hbase.hstore.bytes.per.checksum]] *`hbase.hstore.bytes.per.checksum`*:: + .Description Number of bytes in a newly created checksum chunk for HBase-level checksums in hfile blocks. + .Default `16384` [[hbase.hstore.checksum.algorithm]] *`hbase.hstore.checksum.algorithm`*:: + .Description Name of an algorithm that is used to compute checksums. Possible values are NULL, CRC32, CRC32C. + .Default `CRC32` [[hbase.status.published]] *`hbase.status.published`*:: + .Description This setting activates the publication by the master of the status of the region server. When a region server dies and its recovery starts, the master will push this information to the client application, to let them cut the connection immediately instead of waiting for a timeout. + .Default `false` [[hbase.status.publisher.class]] *`hbase.status.publisher.class`*:: + .Description Implementation of the status publication with a multicast message. + .Default `org.apache.hadoop.hbase.master.ClusterStatusPublisher$MulticastPublisher` [[hbase.status.listener.class]] *`hbase.status.listener.class`*:: + .Description Implementation of the status listener with a multicast message. + .Default `org.apache.hadoop.hbase.client.ClusterStatusListener$MulticastListener` [[hbase.status.multicast.address.ip]] *`hbase.status.multicast.address.ip`*:: + .Description Multicast address to use for the status publication by multicast. + .Default `226.1.1.3` [[hbase.status.multicast.address.port]] *`hbase.status.multicast.address.port`*:: + .Description Multicast port to use for the status publication by multicast. + .Default `16100` [[hbase.dynamic.jars.dir]] *`hbase.dynamic.jars.dir`*:: + .Description The directory from which the custom filter/co-processor jars can be loaded dynamically by the region server without the need to restart. However, an already loaded filter/co-processor class would not be un-loaded. See HBASE-1936 for more details. + .Default `${hbase.rootdir}/lib` [[hbase.security.authentication]] *`hbase.security.authentication`*:: + .Description Controls whether or not secure authentication is enabled for HBase. Possible values are 'simple' (no authentication), and 'kerberos'. + .Default `simple` [[hbase.rest.filter.classes]] *`hbase.rest.filter.classes`*:: + .Description Servlet filters for REST service. + .Default `org.apache.hadoop.hbase.rest.filter.GzipFilter` [[hbase.master.loadbalancer.class]] *`hbase.master.loadbalancer.class`*:: + .Description Class used to execute the regions balancing when the period occurs. See the class comment for more on how it works https://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/master/balancer/StochasticLoadBalancer.html It replaces the DefaultLoadBalancer as the default (since renamed as the SimpleLoadBalancer). + .Default `org.apache.hadoop.hbase.master.balancer.StochasticLoadBalancer` [[hbase.security.exec.permission.checks]] *`hbase.security.exec.permission.checks`*:: + .Description If this setting is enabled and ACL based access control is active (the AccessController coprocessor is installed either as a system coprocessor or on a table as a table coprocessor) then you must grant all relevant users EXEC privilege if they require the ability to execute coprocessor endpoint calls. EXEC privilege, like any other permission, can be granted globally to a user, or to a user on a per table or per namespace basis. For more information on coprocessor endpoints, see the coprocessor section of the HBase online manual. For more information on granting or revoking permissions using the AccessController, see the security section of the HBase online manual. + .Default `false` [[hbase.procedure.regionserver.classes]] *`hbase.procedure.regionserver.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.procedure.RegionServerProcedureManager procedure managers that are loaded by default on the active HRegionServer process. The lifecycle methods (init/start/stop) will be called by the active HRegionServer process to perform the specific globally barriered procedure. After implementing your own RegionServerProcedureManager, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.procedure.master.classes]] *`hbase.procedure.master.classes`*:: + .Description A comma-separated list of org.apache.hadoop.hbase.procedure.MasterProcedureManager procedure managers that are loaded by default on the active HMaster process. A procedure is identified by its signature and users can use the signature and an instant name to trigger an execution of a globally barriered procedure. After implementing your own MasterProcedureManager, just put it in HBase's classpath and add the fully qualified class name here. + .Default `` [[hbase.regionserver.storefile.refresh.period]] *`hbase.regionserver.storefile.refresh.period`*:: + .Description The period (in milliseconds) for refreshing the store files for the secondary regions. 0 means this feature is disabled. Secondary regions sees new files (from flushes and compactions) from primary once the secondary region refreshes the list of files in the region (there is no notification mechanism). But too frequent refreshes might cause extra Namenode pressure. If the files cannot be refreshed for longer than HFile TTL (hbase.master.hfilecleaner.ttl) the requests are rejected. Configuring HFile TTL to a larger value is also recommended with this setting. + .Default `0` [[hbase.region.replica.replication.enabled]] *`hbase.region.replica.replication.enabled`*:: + .Description Whether asynchronous WAL replication to the secondary region replicas is enabled or not. If this is enabled, a replication peer named ""region_replica_replication"" will be created which will tail the logs and replicate the mutations to region replicas for tables that have region replication > 1. If this is enabled once, disabling this replication also requires disabling the replication peer using shell or Admin java class. Replication to secondary region replicas works over standard inter-cluster replication. + .Default `false` [[hbase.http.filter.initializers]] *`hbase.http.filter.initializers`*:: + .Description A comma separated list of class names. Each class in the list must extend org.apache.hadoop.hbase.http.FilterInitializer. The corresponding Filter will be initialized. Then, the Filter will be applied to all user facing jsp and servlet web pages. The ordering of the list defines the ordering of the filters. The default StaticUserWebFilter adds a user principal as defined by the hbase.http.staticuser.user property. + .Default `org.apache.hadoop.hbase.http.lib.StaticUserWebFilter` [[hbase.security.visibility.mutations.checkauths]] *`hbase.security.visibility.mutations.checkauths`*:: + .Description This property if enabled, will check whether the labels in the visibility expression are associated with the user issuing the mutation + .Default `false` [[hbase.http.max.threads]] *`hbase.http.max.threads`*:: + .Description The maximum number of threads that the HTTP Server will create in its ThreadPool. + .Default `16` [[hbase.replication.rpc.codec]] *`hbase.replication.rpc.codec`*:: + .Description The codec that is to be used when replication is enabled so that the tags are also replicated. This is used along with HFileV3 which supports tags in them. If tags are not used or if the hfile version used is HFileV2 then KeyValueCodec can be used as the replication codec. Note that using KeyValueCodecWithTags for replication when there are no tags causes no harm. + .Default `org.apache.hadoop.hbase.codec.KeyValueCodecWithTags` [[hbase.http.staticuser.user]] *`hbase.http.staticuser.user`*:: + .Description The user name to filter as on static web filters while rendering content. For example, the HDFS web UI (user to be used for browsing files). + .Default `dr.stack` [[hbase.regionserver.handler.abort.on.error.percent]] *`hbase.regionserver.handler.abort.on.error.percent`*:: + .Description The percent of region server RPC threads failed to abort RS. -1 Disable aborting; 0 Abort if even a single handler has died; 0.x Abort only when this percent of handlers have died; 1 Abort only all of the handlers have died. + .Default `0.5` [[hbase.master.cleaner.snapshot.interval]] *`hbase.master.cleaner.snapshot.interval`*:: + .Description Snapshot Cleanup chore interval in milliseconds. The cleanup thread keeps running at this interval to find all snapshots that are expired based on TTL and delete them. + .Default `1800000` [[hbase.master.snapshot.ttl]] *`hbase.master.snapshot.ttl`*:: + .Description Default Snapshot TTL to be considered when the user does not specify TTL while creating snapshot. Default value 0 indicates FOREVERE - snapshot should not be automatically deleted until it is manually deleted + .Default `0` [[hbase.master.regions.recovery.check.interval]] *`hbase.master.regions.recovery.check.interval`*:: + .Description Regions Recovery Chore interval in milliseconds. This chore keeps running at this interval to find all regions with configurable max store file ref count and reopens them. + .Default `1200000` [[hbase.regions.recovery.store.file.ref.count]] *`hbase.regions.recovery.store.file.ref.count`*:: + .Description Very large number of ref count on a compacted store file indicates that it is a ref leak on that object(compacted store file). Such files can not be removed after it is invalidated via compaction. Only way to recover in such scenario is to reopen the region which can release all resources, like the refcount, leases, etc. This config represents Store files Ref Count threshold value considered for reopening regions. Any region with compacted store files ref count > this value would be eligible for reopening by master. Here, we get the max refCount among all refCounts on all compacted away store files that belong to a particular region. Default value -1 indicates this feature is turned off. Only positive integer value should be provided to enable this feature. + .Default `-1` [[hbase.regionserver.slowlog.ringbuffer.size]] *`hbase.regionserver.slowlog.ringbuffer.size`*:: + .Description Default size of ringbuffer to be maintained by each RegionServer in order to store online slowlog responses. This is an in-memory ring buffer of requests that were judged to be too slow in addition to the responseTooSlow logging. The in-memory representation would be complete. For more details, please look into Doc Section: <> + .Default `256` [[hbase.regionserver.slowlog.buffer.enabled]] *`hbase.regionserver.slowlog.buffer.enabled`*:: + .Description Indicates whether RegionServers have ring buffer running for storing Online Slow logs in FIFO manner with limited entries. The size of the ring buffer is indicated by config: hbase.regionserver.slowlog.ringbuffer.size The default value is false, turn this on and get latest slowlog responses with complete data. For more details, please look into Doc Section: <> + .Default `false` [[hbase.regionserver.slowlog.systable.enabled]] *`hbase.regionserver.slowlog.systable.enabled`*:: + .Description Should be enabled only if hbase.regionserver.slowlog.buffer.enabled is enabled. If enabled (true), all slow/large RPC logs would be persisted to system table hbase:slowlog (in addition to in-memory ring buffer at each RegionServer). The records are stored in increasing order of time. Operators can scan the table with various combination of ColumnValueFilter and time range. More details are provided in the doc section: ""Get Slow/Large Response Logs from System table hbase:slowlog"" + .Default `false` [[hbase.master.metafixer.max.merge.count]] *`hbase.master.metafixer.max.merge.count`*:: + .Description Maximum regions to merge at a time when we fix overlaps noted in CJ consistency report, but avoid merging 100 regions in one go! + .Default `64` [[hbase.rpc.rows.size.threshold.reject]] *`hbase.rpc.rows.size.threshold.reject`*:: + .Description If value is true, RegionServer will abort batch requests of Put/Delete with number of rows in a batch operation exceeding threshold defined by value of config: hbase.rpc.rows.warning.threshold. The default value is false and hence, by default, only warning will be logged. This config should be turned on to prevent RegionServer from serving very large batch size of rows and this way we can improve CPU usages by discarding too large batch request. + .Default `false` [[hbase.master.balancer.decision.buffer.enabled]] *`hbase.master.balancer.decision.buffer.enabled`*:: + .Description Indicates whether active HMaster has ring buffer running for storing balancer decisions in FIFO manner with limited entries. The size of the ring buffer is indicated by config: hbase.master.balancer.decision.queue.size + .Default `false` [[hbase.master.balancer.rejection.buffer.enabled]] *`hbase.master.balancer.rejection.buffer.enabled`*:: + .Description Indicates whether active HMaster has ring buffer running for storing balancer rejection in FIFO manner with limited entries. The size of the ring buffer is indicated by config: hbase.master.balancer.rejection.queue.size + .Default `false` ",16330,True,3054.8299308031183,median "/** * BigInteger * * An ActionScript 3 implementation of BigInteger (light version) * Copyright (c) 2007 Henri Torgemane * * Derived from: * The jsbn library, Copyright (c) 2003-2005 Tom Wu * * See LICENSE.txt for full license information. */ package com.hurlant.math { import com.hurlant.crypto.prng.Random; import com.hurlant.util.Hex; import com.hurlant.util.Memory; import flash.utils.ByteArray; use namespace bi_internal; public class BigInteger { public static const DB:int = 30; // number of significant bits per chunk public static const DV:int = (1< 0) { if (p>p)>0) { m = true; r = d.toString(36); } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { r += d.toString(36); } } } return m?r:""0""; } public function toArray(array:ByteArray):uint { const k:int = 8; const km:int = (1<<8)-1; var d:int = 0; var i:int = t; var p:int = DB-(i*DB)%k; var m:Boolean = false; var c:int = 0; if (i-- > 0) { if (p>p)>0) { m = true; array.writeByte(d); c++; } while (i >= 0) { if (p>(p+=DB-k); } else { d = (a[i]>>(p-=k))&km; if (p<=0) { p += DB; --i; } } if (d>0) { m = true; } if (m) { array.writeByte(d); c++; } } } return c; } /** * best-effort attempt to fit into a Number. * precision can be lost if it just can't fit. */ public function valueOf():Number { if (s==-1) { return -negate().valueOf(); } var coef:Number = 1; var value:Number = 0; for (var i:uint=0;i v, - if this < v, 0 if equal */ public function compareTo(v:BigInteger):int { var r:int = s - v.s; if (r!=0) { return r; } var i:int = t; r = i-v.t; if (r!=0) { return r; } while (--i >=0) { r=a[i]-v.a[i]; if (r != 0) return r; } return 0; } /** * returns bit length of the integer x */ bi_internal function nbits(x:int):int { var r:int = 1; var t:int; if ((t=x>>>16) != 0) { x = t; r += 16; } if ((t=x>>8) != 0) { x = t; r += 8; } if ((t=x>>4) != 0) { x = t; r += 4; } if ((t=x>>2) != 0) { x = t; r += 2; } if ((t=x>>1) != 0) { x = t; r += 1; } return r; } /** * returns the number of bits in this */ public function bitLength():int { if (t<=0) return 0; return DB*(t-1)+nbits(a[t-1]^(s&DM)); } /** * * @param v * @return this % v * */ public function mod(v:BigInteger):BigInteger { var r:BigInteger = nbi(); abs().divRemTo(v,null,r); if (s<0 && r.compareTo(ZERO)>0) { v.subTo(r,r); } return r; } /** * this^e % m, 0 <= e < 2^32 */ public function modPowInt(e:int, m:BigInteger):BigInteger { var z:IReduction; if (e<256 || m.isEven()) { z = new ClassicReduction(m); } else { z = new MontgomeryReduction(m); } return exp(e, z); } /** * copy this to r */ bi_internal function copyTo(r:BigInteger):void { for (var i:int = t-1; i>=0; --i) { r.a[i] = a[i]; } r.t = t; r.s = s; } /** * set from integer value ""value"", -DV <= value < DV */ bi_internal function fromInt(value:int):void { t = 1; s = (value<0)?-1:0; if (value>0) { a[0] = value; } else if (value<-1) { a[0] = value+DV; } else { t = 0; } } /** * set from ByteArray and length, * starting a current position * If length goes beyond the array, pad with zeroes. */ bi_internal function fromArray(value:ByteArray, length:int, unsigned:Boolean = false):void { var p:int = value.position; var i:int = p+length; var sh:int = 0; const k:int = 8; t = 0; s = 0; while (--i >= p) { var x:int = i DB) { a[t-1] |= (x&((1<<(DB-sh))-1))<>(DB-sh); } else { a[t-1] |= x<= DB) sh -= DB; } if (!unsigned && (value[0]&0x80)==0x80) { s = -1; if (sh > 0) { a[t-1] |= ((1<<(DB-sh))-1)<0 && a[t-1]==c) { --t; } } /** * r = this << n*DB */ bi_internal function dlShiftTo(n:int, r:BigInteger):void { var i:int; for (i=t-1; i>=0; --i) { r.a[i+n] = a[i]; } for (i=n-1; i>=0; --i) { r.a[i] = 0; } r.t = t+n; r.s = s; } /** * r = this >> n*DB */ bi_internal function drShiftTo(n:int, r:BigInteger):void { var i:int; for (i=n; i=0; --i) { r.a[i+ds+1] = (a[i]>>cbs)|c; c = (a[i]&bm)<=0; --i) { r.a[i] = 0; } r.a[ds] = c; r.t = t+ds+1; r.s = s; r.clamp(); } /** * r = this >> n */ bi_internal function rShiftTo(n:int, r:BigInteger):void { r.s = s; var ds:int = n/DB; if (ds >= t) { r.t = 0; return; } var bs:int = n%DB; var cbs:int = DB-bs; var bm:int = (1<>bs; var i:int; for (i=ds+1; i>bs; } if (bs>0) { r.a[t-ds-1] |= (s&bm)<>= DB; } if (v.t < t) { c -= v.s; while (i< t) { c+= a[i]; r.a[i++] = c&DM; c >>= DB; } c += s; } else { c += s; while (i < v.t) { c -= v.a[i]; r.a[i++] = c&DM; c >>= DB; } c -= v.s; } r.s = (c<0)?-1:0; if (c<-1) { r.a[i++] = DV+c; } else if (c>0) { r.a[i++] = c; } r.t = i; r.clamp(); } /** * am: Compute w_j += (x*this_i), propagates carries, * c is initial carry, returns final carry. * c < 3*dvalue, x < 2*dvalue, this_i < dvalue */ bi_internal function am(i:int,x:int,w:BigInteger,j:int,c:int,n:int):int { var xl:int = x&0x7fff; var xh:int = x>>15; while(--n >= 0) { var l:int = a[i]&0x7fff; var h:int = a[i++]>>15; var m:int = xh*l + h*xl; l = xl*l + ((m&0x7fff)<<15)+w.a[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w.a[j++] = l&0x3fffffff; } return c; } /** * r = this * v, r != this,a (HAC 14.12) * ""this"" should be the larger one if appropriate */ bi_internal function multiplyTo(v:BigInteger, r:BigInteger):void { var x:BigInteger = abs(); var y:BigInteger = v.abs(); var i:int = x.t; r.t = i+y.t; while (--i >= 0) { r.a[i] = 0; } for (i=0; i=0) r.a[i] = 0; for (i=0; i= DV) { r.a[i+x.t] -= DV; r.a[i+x.t+1] = 1; } } if (r.t>0) { r.a[r.t-1] += x.am(i, x.a[i], r, 2*i, 0, 1); } r.s = 0; r.clamp(); } /** * divide this by m, quotient and remainder to q, r (HAC 14.20) * r != q, this != m. q or r may be null. */ bi_internal function divRemTo(m:BigInteger, q:BigInteger = null, r:BigInteger = null):void { var pm:BigInteger = m.abs(); if (pm.t <= 0) return; var pt:BigInteger = abs(); if (pt.t < pm.t) { if (q!=null) q.fromInt(0); if (r!=null) copyTo(r); return; } if (r==null) r = nbi(); var y:BigInteger = nbi(); var ts:int = s; var ms:int = m.s; var nsh:int = DB-nbits(pm.a[pm.t-1]); // normalize modulus if (nsh>0) { pm.lShiftTo(nsh, y); pt.lShiftTo(nsh, r); } else { pm.copyTo(y); pt.copyTo(r); } var ys:int = y.t; var y0:int = y.a[ys-1]; if (y0==0) return; var yt:Number = y0*(1<1)?y.a[ys-2]>>F2:0); var d1:Number = FV/yt; var d2:Number = (1<=0) { r.a[r.t++] = 1; r.subTo(t,r); } ONE.dlShiftTo(ys,t); t.subTo(y,y); // ""negative"" y so we can replace sub with am later. while(y.t= 0) { // Estimate quotient digit var qd:int = (r.a[--i]==y0)?DM:Number(r.a[i])*d1+(Number(r.a[i-1])+e)*d2; if ((r.a[i]+= y.am(0, qd, r, j, 0, ys))0) { r.rShiftTo(nsh, r); // Denormalize remainder } if (ts<0) { ZERO.subTo(r,r); } } /** * return ""-1/this % 2^DB""; useful for Mont. reduction * justification: * xy == 1 (mod n) * xy = 1+km * xy(2-xy) = (1+km)(1-km) * x[y(2-xy)] = 1-k^2.m^2 * x[y(2-xy)] == 1 (mod m^2) * if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 * should reduce x and y(2-xy) by m^2 at each step to keep size bounded * [XXX unit test the living shit out of this.] */ bi_internal function invDigit():int { if (t<1) return 0; var x:int = a[0]; if ((x&1)==0) return 0; var y:int = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf )*y)) &0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y)) &0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly; // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints // XXX 48 bit ints? Whaaaa? is there an implicit float conversion in here? y = (y*(2-x*y%DV))%DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y>0)?DV-y:-y; } /** * true iff this is even */ bi_internal function isEven():Boolean { return ((t>0)?(a[0]&1):s) == 0; } /** * this^e, e < 2^32, doing sqr and mul with ""r"" (HAC 14.79) */ bi_internal function exp(e:int, z:IReduction):BigInteger { if (e > 0xffffffff || e < 1) return ONE; var r:BigInteger = nbi(); var r2:BigInteger = nbi(); var g:BigInteger = z.convert(this); var i:int = nbits(e)-1; g.copyTo(r); while(--i>=0) { z.sqrTo(r, r2); if ((e&(1<0) { z.mulTo(r2,g,r); } else { var t:BigInteger = r; r = r2; r2 = t; } } return z.revert(r); } bi_internal function intAt(str:String, index:int):int { return parseInt(str.charAt(index), 36); } protected function nbi():* { return new BigInteger; } /** * return bigint initialized to value */ public static function nbv(value:int):BigInteger { var bn:BigInteger = new BigInteger; bn.fromInt(value); return bn; } // Functions above are sufficient for RSA encryption. // The stuff below is useful for decryption and key generation public static const lowprimes:Array = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; public static const lplim:int = (1<<26)/lowprimes[lowprimes.length-1]; public function clone():BigInteger { var r:BigInteger = new BigInteger; this.copyTo(r); return r; } /** * * @return value as integer * */ public function intValue():int { if (s<0) { if (t==1) { return a[0]-DV; } else if (t==0) { return -1; } } else if (t==1) { return a[0]; } else if (t==0) { return 0; } // assumes 16 < DB < 32 return ((a[1]&((1<<(32-DB))-1))<>24; } /** * * @return value as short (assumes DB>=16) * */ public function shortValue():int { return (t==0)?s:(a[0]<<16)>>16; } /** * * @param r * @return x s.t. r^x < DV * */ protected function chunkSize(r:Number):int { return Math.floor(Math.LN2*DB/Math.log(r)); } /** * * @return 0 if this ==0, 1 if this >0 * */ public function sigNum():int { if (s<0) { return -1; } else if (t<=0 || (t==1 && a[0]<=0)) { return 0; } else{ return 1; } } /** * * @param b: radix to use * @return a string representing the integer converted to the radix. * */ protected function toRadix(b:uint=10):String { if (sigNum()==0 || b<2 || b>32) return ""0""; var cs:int = chunkSize(b); var a:Number = Math.pow(b, cs); var d:BigInteger = nbv(a); var y:BigInteger = nbi(); var z:BigInteger = nbi(); var r:String = """"; divRemTo(d, y, z); while (y.sigNum()>0) { r = (a+z.intValue()).toString(b).substr(1) + r; y.divRemTo(d,y,z); } return z.intValue().toString(b) + r; } /** * * @param s a string to convert from using radix. * @param b a radix * */ protected function fromRadix(s:String, b:int = 10):void { fromInt(0); var cs:int = chunkSize(b); var d:Number = Math.pow(b, cs); var mi:Boolean = false; var j:int = 0; var w:int = 0; for (var i:int=0;i= cs) { dMultiply(d); dAddOffset(w,0); j=0; w=0; } } if (j>0) { dMultiply(Math.pow(b,j)); dAddOffset(w,0); } if (mi) { BigInteger.ZERO.subTo(this, this); } } // XXX function fromNumber not written yet. /** * * @return a byte array. * */ public function toByteArray():ByteArray { var i:int = t; var r:ByteArray = new ByteArray; r[0] = s; var p:int = DB-(i*DB)%8; var d:int; var k:int=0; if (i-- > 0) { if (p>p)!=(s&DM)>>p) { r[k++] = d|(s<<(DB-p)); } while (i>=0) { if(p<8) { d = (a[i]&((1<>(p+=DB-8); } else { d = (a[i]>>(p-=8))&0xff; if (p<=0) { p += DB; --i; } } if ((d&0x80)!=0) d|=-256; if (k==0 && (s&0x80)!=(d&0x80)) ++k; if (k>0 || d!=s) r[k++] = d; } } return r; } public function equals(a:BigInteger):Boolean { return compareTo(a)==0; } public function min(a:BigInteger):BigInteger { return (compareTo(a)<0)?this:a; } public function max(a:BigInteger):BigInteger { return (compareTo(a)>0)?this:a; } /** * * @param a a BigInteger to perform the operation with * @param op a Function implementing the operation * @param r a BigInteger to store the result of the operation * */ protected function bitwiseTo(a:BigInteger, op:Function, r:BigInteger):void { var i:int; var f:int; var m:int = Math.min(a.t, t); for (i=0; i>= 16; r += 16; } if ((x&0xff) == 0) { x>>= 8; r += 8; } if ((x&0xf) == 0) { x>>= 4; r += 4; } if ((x&0x3) == 0) { x>>= 2; r += 2; } if ((x&0x1) == 0) ++r; return r; } /** * * @return index of lowest 1-bit (or -1 if none) * */ public function getLowestSetBit():int { for (var i:int=0;i=t) { return s!=0; } return ((a[j]&(1<<(n%DB)))!=0); } /** * * @param n * @param op * @return this op (1<>=DB; } if (a.t < t) { c += a.s; while (i>= DB; } c += s; } else { c += s; while (i>= DB; } c += a.s; } r.s = (c<0)?-1:0; if (c>0) { r.a[i++] = c; } else if (c<-1) { r.a[i++] = DV+c; } r.t = i; r.clamp(); } /** * * @param a * @return this + a * */ public function add(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; addTo(a,r); return r; } /** * * @param a * @return this - a * */ public function subtract(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; subTo(a,r); return r; } /** * * @param a * @return this * a * */ public function multiply(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; multiplyTo(a,r); return r; } /** * * @param a * @return this / a * */ public function divide(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, r, null); return r; } public function remainder(a:BigInteger):BigInteger { var r:BigInteger = new BigInteger; divRemTo(a, null, r); return r; } /** * * @param a * @return [this/a, this%a] * */ public function divideAndRemainder(a:BigInteger):Array { var q:BigInteger = new BigInteger; var r:BigInteger = new BigInteger; divRemTo(a, q, r); return [q,r]; } /** * * this *= n, this >=0, 1 < n < DV * * @param n * */ bi_internal function dMultiply(n:int):void { a[t] = am(0, n-1, this, 0, 0, t); ++t; clamp(); } /** * * this += n << w words, this >= 0 * * @param n * @param w * */ bi_internal function dAddOffset(n:int, w:int):void { while (t<=w) { a[t++] = 0; } a[w] += n; while (a[w] >= DV) { a[w] -= DV; if (++w >= t) { a[t++] = 0; } ++a[w]; } } /** * * @param e * @return this^e * */ public function pow(e:int):BigInteger { return exp(e, new NullReduction); } /** * * @param a * @param n * @param r = lower n words of ""this * a"", a.t <= n * */ bi_internal function multiplyLowerTo(a:BigInteger, n:int, r:BigInteger):void { var i:int = Math.min(t+a.t, n); r.s = 0; // assumes a, this >= 0 r.t = i; while (i>0) { r.a[--i]=0; } var j:int; for (j=r.t-t;i 0 * */ bi_internal function multiplyUpperTo(a:BigInteger, n:int, r:BigInteger):void { --n; var i:int = r.t = t+a.t-n; r.s = 0; // assumes a,this >= 0 while (--i>=0) { r.a[i] = 0; } for (i=Math.max(n-t,0);i 1) { var g2:BigInteger = new BigInteger; z.sqrTo(g[1], g2); while (n<=km) { g[n] = new BigInteger; z.mulTo(g2, g[n-2], g[n]); n += 2; } } var j:int = e.t-1; var w:int; var is1:Boolean = true; var r2:BigInteger = new BigInteger; var t:BigInteger; i = nbits(e.a[j])-1; while (j>=0) { if (i>=k1) { w = (e.a[j]>>(i-k1))&km; } else { w = (e.a[j]&((1<<(i+1))-1))<<(k1-i); if (j>0) { w |= e.a[j-1]>>(DB+i-k1); } } n = k; while ((w&1)==0) { w >>= 1; --n; } if ((i -= n) <0) { i += DB; --j; } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r); is1 = false; } else { while (n>1) { z.sqrTo(r, r2); z.sqrTo(r2, r); n -= 2; } if (n>0) { z.sqrTo(r, r2); } else { t = r; r = r2; r2 = t; } z.mulTo(r2, g[w], r); } while (j>=0 && (e.a[j]&(1<0) { x.rShiftTo(g, x); y.rShiftTo(g, y); } while (x.sigNum()>0) { if ((i = x.getLowestSetBit()) >0) { x.rShiftTo(i, x); } if ((i = y.getLowestSetBit()) >0) { y.rShiftTo(i, y); } if (x.compareTo(y) >= 0) { x.subTo(y, x); x.rShiftTo(1, x); } else { y.subTo(x, y); y.rShiftTo(1, y); } } if (g>0) { y.lShiftTo(g, y); } return y; } /** * * @param n * @return this % n, n < 2^DB * */ protected function modInt(n:int):int { if (n<=0) return 0; var d:int = DV%n; var r:int = (s<0)?n-1:0; if (t>0) { if (d==0) { r = a[0]%n; } else { for (var i:int=t-1;i>=0;--i) { r = (d*r+a[i])%n; } } } return r; } /** * * @param m * @return 1/this %m (HAC 14.61) * */ public function modInverse(m:BigInteger):BigInteger { var ac:Boolean = m.isEven(); if ((isEven()&&ac) || m.sigNum()==0) { return BigInteger.ZERO; } var u:BigInteger = m.clone(); var v:BigInteger = clone(); var a:BigInteger = nbv(1); var b:BigInteger = nbv(0); var c:BigInteger = nbv(0); var d:BigInteger = nbv(1); while (u.sigNum()!=0) { while (u.isEven()) { u.rShiftTo(1,u); if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } a.rShiftTo(1,a); } else if (!b.isEven()) { b.subTo(m,b); } b.rShiftTo(1,b); } while (v.isEven()) { v.rShiftTo(1,v); if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } c.rShiftTo(1,c); } else if (!d.isEven()) { d.subTo(m,d); } d.rShiftTo(1,d); } if (u.compareTo(v)>=0) { u.subTo(v,u); if (ac) { a.subTo(c,a); } b.subTo(d,b); } else { v.subTo(u,v); if (ac) { c.subTo(a,c); } d.subTo(b,d); } } if (v.compareTo(BigInteger.ONE) != 0) { return BigInteger.ZERO; } if (d.compareTo(m) >= 0) { return d.subtract(m); } if (d.sigNum()<0) { d.addTo(m,d); } else { return d; } if (d.sigNum()<0) { return d.add(m); } else { return d; } } /** * * @param t * @return primality with certainty >= 1-.5^t * */ public function isProbablePrime(t:int):Boolean { var i:int; var x:BigInteger = abs(); if (x.t == 1 && x.a[0]<=lowprimes[lowprimes.length-1]) { for (i=0;i>1; if (t>lowprimes.length) { t = lowprimes.length; } var a:BigInteger = new BigInteger; for (var i:int=0;ibits) subTo(BigInteger.ONE.shiftLeft(bits-1),this); } } } } ",12292,True,2693.374461286954,median "/* Feathers Copyright 2012-2014 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.layout { import feathers.core.IFeathersControl; import feathers.core.IValidating; import flash.errors.IllegalOperationError; import flash.geom.Point; import starling.display.DisplayObject; import starling.events.Event; import starling.events.EventDispatcher; /** * Dispatched when a property of the layout changes, indicating that a * redraw is probably needed. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    datanull
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @eventType starling.events.Event.CHANGE */ [Event(name=""change"",type=""starling.events.Event"")] /** * Positions items from top to bottom in a single column. * * @see http://wiki.starling-framework.org/feathers/vertical-layout */ public class VerticalLayout extends EventDispatcher implements IVariableVirtualLayout, ITrimmedVirtualLayout { /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the top. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_TOP:String = ""top""; /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the middle. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_MIDDLE:String = ""middle""; /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the bottom. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_BOTTOM:String = ""bottom""; /** * The items will be aligned to the left of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_LEFT:String = ""left""; /** * The items will be aligned to the center of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_CENTER:String = ""center""; /** * The items will be aligned to the right of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_RIGHT:String = ""right""; /** * The items will fill the width of the bounds. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_JUSTIFY:String = ""justify""; /** * Constructor. */ public function VerticalLayout() { } /** * @private */ protected var _heightCache:Array = []; /** * @private */ protected var _discoveredItemsCache:Vector. = new []; /** * @private */ protected var _gap:Number = 0; /** * The space, in pixels, between items. * * @default 0 */ public function get gap():Number { return this._gap; } /** * @private */ public function set gap(value:Number):void { if(this._gap == value) { return; } this._gap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _firstGap:Number = NaN; /** * The space, in pixels, between the first and second items. If the * value of firstGap is NaN, the value of the * gap property will be used instead. * * @default NaN */ public function get firstGap():Number { return this._firstGap; } /** * @private */ public function set firstGap(value:Number):void { if(this._firstGap == value) { return; } this._firstGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _lastGap:Number = NaN; /** * The space, in pixels, between the last and second to last items. If * the value of lastGap is NaN, the value of * the gap property will be used instead. * * @default NaN */ public function get lastGap():Number { return this._lastGap; } /** * @private */ public function set lastGap(value:Number):void { if(this._lastGap == value) { return; } this._lastGap = value; this.dispatchEventWith(Event.CHANGE); } /** * Quickly sets all padding properties to the same value. The * padding getter always returns the value of * paddingTop, but the other padding values may be * different. * * @default 0 * * @see #paddingTop * @see #paddingRight * @see #paddingBottom * @see #paddingLeft */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The space, in pixels, that appears on top, before the first item. * * @default 0 */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingRight:Number = 0; /** * The minimum space, in pixels, to the right of the items. * * @default 0 */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The space, in pixels, that appears on the bottom, after the last * item. * * @default 0 */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The minimum space, in pixels, to the left of the items. * * @default 0 */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalAlign:String = VERTICAL_ALIGN_TOP; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * If the total item height is less than the bounds, the positions of * the items can be aligned vertically. * * @default VerticalLayout.VERTICAL_ALIGN_TOP * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get verticalAlign():String { return this._verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this._verticalAlign == value) { return; } this._verticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _horizontalAlign:String = HORIZONTAL_ALIGN_LEFT; [Inspectable(type=""String"",enumeration=""left,center,right,justify"")] /** * The alignment of the items horizontally, on the x-axis. * * @default VerticalLayout.HORIZONTAL_ALIGN_LEFT * * @see #HORIZONTAL_ALIGN_LEFT * @see #HORIZONTAL_ALIGN_CENTER * @see #HORIZONTAL_ALIGN_RIGHT * @see #HORIZONTAL_ALIGN_JUSTIFY */ public function get horizontalAlign():String { return this._horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if(this._horizontalAlign == value) { return; } this._horizontalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _useVirtualLayout:Boolean = true; /** * @inheritDoc * * @default true */ public function get useVirtualLayout():Boolean { return this._useVirtualLayout; } /** * @private */ public function set useVirtualLayout(value:Boolean):void { if(this._useVirtualLayout == value) { return; } this._useVirtualLayout = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _hasVariableItemDimensions:Boolean = false; /** * When the layout is virtualized, and this value is true, the items may * have variable width values. If false, the items will all share the * same width value with the typical item. * * @default false */ public function get hasVariableItemDimensions():Boolean { return this._hasVariableItemDimensions; } /** * @private */ public function set hasVariableItemDimensions(value:Boolean):void { if(this._hasVariableItemDimensions == value) { return; } this._hasVariableItemDimensions = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _distributeHeights:Boolean = false; /** * Distributes the height of the view port equally to each item. If the * view port height needs to be measured, the largest item's height will * be used for all items, subject to any specified minimum and maximum * height values. * * @default false */ public function get distributeHeights():Boolean { return this._distributeHeights; } /** * @private */ public function set distributeHeights(value:Boolean):void { if(this._distributeHeights == value) { return; } this._distributeHeights = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _manageVisibility:Boolean = false; /** * Determines if items will be set invisible if they are outside the * view port. Can improve performance, especially for non-virtual * layouts. If true, you will not be able to manually * change the visible property of any items in the layout. * * @default false */ public function get manageVisibility():Boolean { return this._manageVisibility; } /** * @private */ public function set manageVisibility(value:Boolean):void { if(this._manageVisibility == value) { return; } this._manageVisibility = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _beforeVirtualizedItemCount:int = 0; /** * @inheritDoc */ public function get beforeVirtualizedItemCount():int { return this._beforeVirtualizedItemCount; } /** * @private */ public function set beforeVirtualizedItemCount(value:int):void { if(this._beforeVirtualizedItemCount == value) { return; } this._beforeVirtualizedItemCount = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _afterVirtualizedItemCount:int = 0; /** * @inheritDoc */ public function get afterVirtualizedItemCount():int { return this._afterVirtualizedItemCount; } /** * @private */ public function set afterVirtualizedItemCount(value:int):void { if(this._afterVirtualizedItemCount == value) { return; } this._afterVirtualizedItemCount = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItem:DisplayObject; /** * @inheritDoc * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemWidth * @see #typicalItemHeight */ public function get typicalItem():DisplayObject { return this._typicalItem; } /** * @private */ public function set typicalItem(value:DisplayObject):void { if(this._typicalItem == value) { return; } this._typicalItem = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _resetTypicalItemDimensionsOnMeasure:Boolean = false; /** * If set to true, the width and height of the * typicalItem will be reset to typicalItemWidth * and typicalItemHeight, respectively, whenever the * typical item needs to be measured. The measured dimensions of the * typical item are used to fill in the blanks of a virtualized layout * for virtual items that don't have their own display objects to * measure yet. * * @default false * * @see #typicalItemWidth * @see #typicalItemHeight * @see #typicalItem */ public function get resetTypicalItemDimensionsOnMeasure():Boolean { return this._resetTypicalItemDimensionsOnMeasure; } /** * @private */ public function set resetTypicalItemDimensionsOnMeasure(value:Boolean):void { if(this._resetTypicalItemDimensionsOnMeasure == value) { return; } this._resetTypicalItemDimensionsOnMeasure = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItemWidth:Number = NaN; /** * Used to reset the width, in pixels, of the typicalItem * for measurement. The measured dimensions of the typical item are used * to fill in the blanks of a virtualized layout for virtual items that * don't have their own display objects to measure yet. * *

    This value is only used when resetTypicalItemDimensionsOnMeasure * is set to true. If resetTypicalItemDimensionsOnMeasure * is set to false, this value will be ignored and the * typicalItem dimensions will not be reset before * measurement.

    * *

    If typicalItemWidth is set to NaN, the * typical item will auto-size itself to its preferred width. If you * pass a valid Number value, the typical item's width will * be set to a fixed size. May be used in combination with * typicalItemHeight.

    * * @default NaN * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemHeight * @see #typicalItem */ public function get typicalItemWidth():Number { return this._typicalItemWidth; } /** * @private */ public function set typicalItemWidth(value:Number):void { if(this._typicalItemWidth == value) { return; } this._typicalItemWidth = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItemHeight:Number = NaN; /** * Used to reset the height, in pixels, of the typicalItem * for measurement. The measured dimensions of the typical item are used * to fill in the blanks of a virtualized layout for virtual items that * don't have their own display objects to measure yet. * *

    This value is only used when resetTypicalItemDimensionsOnMeasure * is set to true. If resetTypicalItemDimensionsOnMeasure * is set to false, this value will be ignored and the * typicalItem dimensions will not be reset before * measurement.

    * *

    If typicalItemHeight is set to NaN, the * typical item will auto-size itself to its preferred height. If you * pass a valid Number value, the typical item's height will * be set to a fixed size. May be used in combination with * typicalItemWidth.

    * * @default NaN * * @see #resetTypicalItemDimensionsOnMeasure * @see #typicalItemWidth * @see #typicalItem */ public function get typicalItemHeight():Number { return this._typicalItemHeight; } /** * @private */ public function set typicalItemHeight(value:Number):void { if(this._typicalItemHeight == value) { return; } this._typicalItemHeight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _scrollPositionVerticalAlign:String = VERTICAL_ALIGN_MIDDLE; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * When the scroll position is calculated for an item, an attempt will * be made to align the item to this position. * * @default VerticalLayout.VERTICAL_ALIGN_MIDDLE * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get scrollPositionVerticalAlign():String { return this._scrollPositionVerticalAlign; } /** * @private */ public function set scrollPositionVerticalAlign(value:String):void { this._scrollPositionVerticalAlign = value; } /** * @inheritDoc */ public function get requiresLayoutOnScroll():Boolean { return this._manageVisibility || this._useVirtualLayout; } /** * @inheritDoc */ public function layout(items:Vector., viewPortBounds:ViewPortBounds = null, result:LayoutBoundsResult = null):LayoutBoundsResult { var scrollX:Number = viewPortBounds ? viewPortBounds.scrollX : 0; var scrollY:Number = viewPortBounds ? viewPortBounds.scrollY : 0; var boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; var boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; if(this._useVirtualLayout) { this.prepareTypicalItem(explicitWidth - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } if(!this._useVirtualLayout || this._hasVariableItemDimensions || this._distributeHeights || this._horizontalAlign != HORIZONTAL_ALIGN_JUSTIFY || explicitWidth != explicitWidth) //isNaN { this.validateItems(items, explicitWidth - this._paddingLeft - this._paddingRight, explicitHeight); } if(!this._useVirtualLayout) { this.applyPercentHeights(items, explicitHeight, minHeight, maxHeight); } var distributedHeight:Number; if(this._distributeHeights) { distributedHeight = this.calculateDistributedHeight(items, explicitHeight, minHeight, maxHeight); } var hasDistributedHeight:Boolean = distributedHeight == distributedHeight; //!isNaN this._discoveredItemsCache.length = 0; var hasFirstGap:Boolean = this._firstGap == this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap == this._lastGap; //!isNaN var maxItemWidth:Number = this._useVirtualLayout ? calculatedTypicalItemWidth : 0; var positionY:Number = boundsY + this._paddingTop; var indexOffset:int = 0; var itemCount:int = items.length; var totalItemCount:int = itemCount; if(this._useVirtualLayout && !this._hasVariableItemDimensions) { totalItemCount += this._beforeVirtualizedItemCount + this._afterVirtualizedItemCount; indexOffset = this._beforeVirtualizedItemCount; positionY += (this._beforeVirtualizedItemCount * (calculatedTypicalItemHeight + this._gap)); if(hasFirstGap && this._beforeVirtualizedItemCount > 0) { positionY = positionY - this._gap + this._firstGap; } } var secondToLastIndex:int = totalItemCount - 2; var discoveredItemsCacheLastIndex:int = 0; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; var iNormalized:int = i + indexOffset; var gap:Number = this._gap; if(hasFirstGap && iNormalized == 0) { gap = this._firstGap; } else if(hasLastGap && iNormalized > 0 && iNormalized == secondToLastIndex) { gap = this._lastGap; } if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedHeight:Number = this._heightCache[iNormalized]; } if(this._useVirtualLayout && !item) { if(!this._hasVariableItemDimensions || cachedHeight != cachedHeight) //isNaN { positionY += calculatedTypicalItemHeight + gap; } else { positionY += cachedHeight + gap; } } else { if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.y = positionY; var itemWidth:Number = item.width; var itemHeight:Number; if(hasDistributedHeight) { item.height = itemHeight = distributedHeight; } else { itemHeight = item.height; } if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { if(cachedHeight != itemHeight) { this._heightCache[iNormalized] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else if(calculatedTypicalItemHeight >= 0) { item.height = itemHeight = calculatedTypicalItemHeight; } } positionY += itemHeight + gap; if(itemWidth > maxItemWidth) { maxItemWidth = itemWidth; } if(this._useVirtualLayout) { this._discoveredItemsCache[discoveredItemsCacheLastIndex] = item; discoveredItemsCacheLastIndex++; } } } if(this._useVirtualLayout && !this._hasVariableItemDimensions) { positionY += (this._afterVirtualizedItemCount * (calculatedTypicalItemHeight + this._gap)); if(hasLastGap && this._afterVirtualizedItemCount > 0) { positionY = positionY - this._gap + this._lastGap; } } var discoveredItems:Vector. = this._useVirtualLayout ? this._discoveredItemsCache : items; var totalWidth:Number = maxItemWidth + this._paddingLeft + this._paddingRight; var availableWidth:Number = explicitWidth; if(availableWidth != availableWidth) //isNaN { availableWidth = totalWidth; if(availableWidth < minWidth) { availableWidth = minWidth; } else if(availableWidth > maxWidth) { availableWidth = maxWidth; } } var discoveredItemCount:int = discoveredItems.length; var totalHeight:Number = positionY - this._gap + this._paddingBottom - boundsY; var availableHeight:Number = explicitHeight; if(availableHeight != availableHeight) //isNaN { availableHeight = totalHeight; if(availableHeight < minHeight) { availableHeight = minHeight; } else if(availableHeight > maxHeight) { availableHeight = maxHeight; } } if(totalHeight < availableHeight) { var verticalAlignOffsetY:Number = 0; if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { verticalAlignOffsetY = availableHeight - totalHeight; } else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE) { verticalAlignOffsetY = (availableHeight - totalHeight) / 2; } if(verticalAlignOffsetY != 0) { for(i = 0; i < discoveredItemCount; i++) { item = discoveredItems[i]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.y += verticalAlignOffsetY; } } } for(i = 0; i < discoveredItemCount; i++) { item = discoveredItems[i]; var layoutItem:ILayoutDisplayObject = item as ILayoutDisplayObject; if(layoutItem && !layoutItem.includeInLayout) { continue; } if(this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY) { item.x = boundsX + this._paddingLeft; item.width = availableWidth - this._paddingLeft - this._paddingRight; } else { if(layoutItem) { var layoutData:VerticalLayoutData = layoutItem.layoutData as VerticalLayoutData; if(layoutData) { var percentWidth:Number = layoutData.percentWidth; if(percentWidth == percentWidth) //!isNaN { if(percentWidth < 0) { percentWidth = 0; } if(percentWidth > 100) { percentWidth = 100; } itemWidth = percentWidth * (availableWidth - this._paddingLeft - this._paddingRight) / 100; if(item is IFeathersControl) { var feathersItem:IFeathersControl = IFeathersControl(item); var itemMinWidth:Number = feathersItem.minWidth; if(itemWidth < itemMinWidth) { itemWidth = itemMinWidth; } else { var itemMaxWidth:Number = feathersItem.maxWidth; if(itemWidth > itemMaxWidth) { itemWidth = itemMaxWidth; } } } item.width = itemWidth; } } } switch(this._horizontalAlign) { case HORIZONTAL_ALIGN_RIGHT: { item.x = boundsX + availableWidth - this._paddingRight - item.width; break; } case HORIZONTAL_ALIGN_CENTER: { item.x = boundsX + this._paddingLeft + (availableWidth - this._paddingLeft - this._paddingRight - item.width) / 2; break; } default: //left { item.x = boundsX + this._paddingLeft; } } } if(this.manageVisibility) { item.visible = ((item.y + item.height) >= (boundsY + scrollY)) && (item.y < (scrollY + availableHeight)); } } this._discoveredItemsCache.length = 0; if(!result) { result = new LayoutBoundsResult(); } result.contentWidth = this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY ? availableWidth : totalWidth; result.contentHeight = totalHeight; result.viewPortWidth = availableWidth; result.viewPortHeight = availableHeight; return result; } /** * @inheritDoc */ public function measureViewPort(itemCount:int, viewPortBounds:ViewPortBounds = null, result:Point = null):Point { if(!result) { result = new Point(); } if(!this._useVirtualLayout) { throw new IllegalOperationError(""measureViewPort() may be called only if useVirtualLayout is true."") } var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; var needsWidth:Boolean = explicitWidth != explicitWidth; //isNaN var needsHeight:Boolean = explicitHeight != explicitHeight; //isNaN if(!needsWidth && !needsHeight) { result.x = explicitWidth; result.y = explicitHeight; return result; } var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; this.prepareTypicalItem(explicitWidth - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var hasFirstGap:Boolean = this._firstGap == this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap == this._lastGap; //!isNaN var positionY:Number; if(this._distributeHeights) { positionY = (calculatedTypicalItemHeight + this._gap) * itemCount; } else { positionY = 0; var maxItemWidth:Number = calculatedTypicalItemWidth; if(!this._hasVariableItemDimensions) { positionY += ((calculatedTypicalItemHeight + this._gap) * itemCount); } else { for(var i:int = 0; i < itemCount; i++) { var cachedHeight:Number = this._heightCache[i]; if(cachedHeight != cachedHeight) //isNaN { positionY += calculatedTypicalItemHeight + this._gap; } else { positionY += cachedHeight + this._gap; } } } } positionY -= this._gap; if(hasFirstGap && itemCount > 1) { positionY = positionY - this._gap + this._firstGap; } if(hasLastGap && itemCount > 2) { positionY = positionY - this._gap + this._lastGap; } if(needsWidth) { var resultWidth:Number = maxItemWidth + this._paddingLeft + this._paddingRight; if(resultWidth < minWidth) { resultWidth = minWidth; } else if(resultWidth > maxWidth) { resultWidth = maxWidth; } result.x = resultWidth; } else { result.x = explicitWidth; } if(needsHeight) { var resultHeight:Number = positionY + this._paddingTop + this._paddingBottom; if(resultHeight < minHeight) { resultHeight = minHeight; } else if(resultHeight > maxHeight) { resultHeight = maxHeight; } result.y = resultHeight; } else { result.y = explicitHeight; } return result; } /** * @inheritDoc */ public function resetVariableVirtualCache():void { this._heightCache.length = 0; } /** * @inheritDoc */ public function resetVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { delete this._heightCache[index]; if(item) { this._heightCache[index] = item.height; this.dispatchEventWith(Event.CHANGE); } } /** * @inheritDoc */ public function addToVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { var heightValue:* = item ? item.height : undefined; this._heightCache.splice(index, 0, heightValue); } /** * @inheritDoc */ public function removeFromVariableVirtualCacheAtIndex(index:int):void { this._heightCache.splice(index, 1); } /** * @inheritDoc */ public function getVisibleIndicesAtScrollPosition(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector. = null):Vector. { if(result) { result.length = 0; } else { result = new []; } if(!this._useVirtualLayout) { throw new IllegalOperationError(""getVisibleIndicesAtScrollPosition() may be called only if useVirtualLayout is true."") } this.prepareTypicalItem(width - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var hasFirstGap:Boolean = this._firstGap == this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap == this._lastGap; //!isNaN var resultLastIndex:int = 0; var visibleTypicalItemCount:int = Math.ceil(height / (calculatedTypicalItemHeight + this._gap)); if(!this._hasVariableItemDimensions) { //this case can be optimized because we know that every item has //the same height var indexOffset:int = 0; var totalItemHeight:Number = itemCount * (calculatedTypicalItemHeight + this._gap) - this._gap; if(hasFirstGap && itemCount > 1) { totalItemHeight = totalItemHeight - this._gap + this._firstGap; } if(hasLastGap && itemCount > 2) { totalItemHeight = totalItemHeight - this._gap + this._lastGap; } if(totalItemHeight < height) { if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { indexOffset = Math.ceil((height - totalItemHeight) / (calculatedTypicalItemHeight + this._gap)); } else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE) { indexOffset = Math.ceil(((height - totalItemHeight) / (calculatedTypicalItemHeight + this._gap)) / 2); } } var minimum:int = (scrollY - this._paddingTop) / (calculatedTypicalItemHeight + this._gap); if(minimum < 0) { minimum = 0; } minimum -= indexOffset; //if we're scrolling beyond the final item, we should keep the //indices consistent so that items aren't destroyed and //recreated unnecessarily var maximum:int = minimum + visibleTypicalItemCount; if(maximum >= itemCount) { maximum = itemCount - 1; } minimum = maximum - visibleTypicalItemCount; if(minimum < 0) { minimum = 0; } for(var i:int = minimum; i <= maximum; i++) { result[resultLastIndex] = i; resultLastIndex++; } return result; } var secondToLastIndex:int = itemCount - 2; var maxPositionY:Number = scrollY + height; var positionY:Number = this._paddingTop; for(i = 0; i < itemCount; i++) { var gap:Number = this._gap; if(hasFirstGap && i == 0) { gap = this._firstGap; } else if(hasLastGap && i > 0 && i == secondToLastIndex) { gap = this._lastGap; } var cachedHeight:Number = this._heightCache[i]; if(cachedHeight != cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } var oldPositionY:Number = positionY; positionY += itemHeight + gap; if(positionY > scrollY && oldPositionY < maxPositionY) { result[resultLastIndex] = i; resultLastIndex++; } if(positionY >= maxPositionY) { break; } } //similar to above, in order to avoid costly destruction and //creation of item renderers, we're going to fill in some extra //indices var resultLength:int = result.length; var visibleItemCountDifference:int = visibleTypicalItemCount - resultLength; if(visibleItemCountDifference > 0 && resultLength > 0) { //add extra items before the first index var firstExistingIndex:int = result[0]; var lastIndexToAdd:int = firstExistingIndex - visibleItemCountDifference; if(lastIndexToAdd < 0) { lastIndexToAdd = 0; } for(i = firstExistingIndex - 1; i >= lastIndexToAdd; i--) { result.unshift(i); } } resultLength = result.length; visibleItemCountDifference = visibleTypicalItemCount - resultLength; resultLastIndex = resultLength; if(visibleItemCountDifference > 0) { //add extra items after the last index var startIndex:int = (resultLength > 0) ? (result[resultLength - 1] + 1) : 0; var endIndex:int = startIndex + visibleItemCountDifference; if(endIndex > itemCount) { endIndex = itemCount; } for(i = startIndex; i < endIndex; i++) { result[resultLastIndex] = i; resultLastIndex++; } } return result; } /** * @inheritDoc */ public function getScrollPositionForIndex(index:int, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { if(!result) { result = new Point(); } if(this._useVirtualLayout) { this.prepareTypicalItem(width - this._paddingLeft - this._paddingRight); var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var hasFirstGap:Boolean = this._firstGap == this._firstGap; //!isNaN var hasLastGap:Boolean = this._lastGap == this._lastGap; //!isNaN var positionY:Number = y + this._paddingTop; var lastHeight:Number = 0; var gap:Number = this._gap; var startIndexOffset:int = 0; var endIndexOffset:Number = 0; var itemCount:int = items.length; var totalItemCount:int = itemCount; if(this._useVirtualLayout && !this._hasVariableItemDimensions) { totalItemCount += this._beforeVirtualizedItemCount + this._afterVirtualizedItemCount; if(index < this._beforeVirtualizedItemCount) { //this makes it skip the loop below startIndexOffset = index + 1; lastHeight = calculatedTypicalItemHeight; gap = this._gap; } else { startIndexOffset = this._beforeVirtualizedItemCount; endIndexOffset = index - items.length - this._beforeVirtualizedItemCount + 1; if(endIndexOffset < 0) { endIndexOffset = 0; } positionY += (endIndexOffset * (calculatedTypicalItemHeight + this._gap)); } positionY += (startIndexOffset * (calculatedTypicalItemHeight + this._gap)); } index -= (startIndexOffset + endIndexOffset); var secondToLastIndex:int = totalItemCount - 2; for(var i:int = 0; i <= index; i++) { var item:DisplayObject = items[i]; var iNormalized:int = i + startIndexOffset; if(hasFirstGap && iNormalized == 0) { gap = this._firstGap; } else if(hasLastGap && iNormalized > 0 && iNormalized == secondToLastIndex) { gap = this._lastGap; } else { gap = this._gap; } if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedHeight:Number = this._heightCache[iNormalized]; } if(this._useVirtualLayout && !item) { if(!this._hasVariableItemDimensions || cachedHeight != cachedHeight) //isNaN { lastHeight = calculatedTypicalItemHeight; } else { lastHeight = cachedHeight; } } else { var itemHeight:Number = item.height; if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { if(itemHeight != cachedHeight) { this._heightCache[iNormalized] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else if(calculatedTypicalItemHeight >= 0) { item.height = itemHeight = calculatedTypicalItemHeight; } } lastHeight = itemHeight; } positionY += lastHeight + gap; } positionY -= (lastHeight + gap); if(this._scrollPositionVerticalAlign == VERTICAL_ALIGN_MIDDLE) { positionY -= (height - lastHeight) / 2; } else if(this._scrollPositionVerticalAlign == VERTICAL_ALIGN_BOTTOM) { positionY -= (height - lastHeight); } result.x = 0; result.y = positionY; return result; } /** * @private */ protected function validateItems(items:Vector., justifyWidth:Number, distributedHeight:Number):void { //if the alignment is justified, then we want to set the width of //each item before validating because setting one dimension may //cause the other dimension to change, and that will invalidate the //layout if it happens after validation, causing more invalidation var mustSetJustifyWidth:Boolean = this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY && justifyWidth == justifyWidth; //!isNaN var itemCount:int = items.length; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(!item || (item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout)) { continue; } if(mustSetJustifyWidth) { item.width = justifyWidth; } if(this._distributeHeights) { item.height = distributedHeight; } if(item is IValidating) { IValidating(item).validate() } } } /** * @private */ protected function prepareTypicalItem(justifyWidth:Number):void { if(!this._typicalItem) { return; } if(this._horizontalAlign == HORIZONTAL_ALIGN_JUSTIFY && justifyWidth == justifyWidth) //!isNaN { this._typicalItem.width = justifyWidth; } else if(this._resetTypicalItemDimensionsOnMeasure) { this._typicalItem.width = this._typicalItemWidth; } if(this._resetTypicalItemDimensionsOnMeasure) { this._typicalItem.height = this._typicalItemHeight; } if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } } /** * @private */ protected function calculateDistributedHeight(items:Vector., explicitHeight:Number, minHeight:Number, maxHeight:Number):Number { var itemCount:int = items.length; if(explicitHeight != explicitHeight) //isNaN { var maxItemHeight:Number = 0; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; var itemHeight:Number = item.height; if(itemHeight > maxItemHeight) { maxItemHeight = itemHeight; } } explicitHeight = maxItemHeight * itemCount + this._paddingTop + this._paddingBottom + this._gap * (itemCount - 1); var needsRecalculation:Boolean = false; if(explicitHeight > maxHeight) { explicitHeight = maxHeight; needsRecalculation = true; } else if(explicitHeight < minHeight) { explicitHeight = minHeight; needsRecalculation = true; } if(!needsRecalculation) { return maxItemHeight; } } var availableSpace:Number = explicitHeight - this._paddingTop - this._paddingBottom - this._gap * (itemCount - 1); if(itemCount > 1 && this._firstGap == this._firstGap) //!isNaN { availableSpace += this._gap - this._firstGap; } if(itemCount > 2 && this._lastGap == this._lastGap) //!isNaN { availableSpace += this._gap - this._lastGap; } return availableSpace / itemCount; } /** * @private */ protected function applyPercentHeights(items:Vector., explicitHeight:Number, minHeight:Number, maxHeight:Number):void { var remainingHeight:Number = explicitHeight; this._discoveredItemsCache.length = 0; var totalExplicitHeight:Number = 0; var totalMinHeight:Number = 0; var totalPercentHeight:Number = 0; var itemCount:int = items.length; var pushIndex:int = 0; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(item is ILayoutDisplayObject) { var layoutItem:ILayoutDisplayObject = ILayoutDisplayObject(item); if(!layoutItem.includeInLayout) { continue; } var layoutData:VerticalLayoutData = layoutItem.layoutData as VerticalLayoutData; if(layoutData) { var percentHeight:Number = layoutData.percentHeight; if(percentHeight === percentHeight) //!isNaN { if(layoutItem is IFeathersControl) { var feathersItem:IFeathersControl = IFeathersControl(layoutItem); totalMinHeight += feathersItem.minHeight; } totalPercentHeight += percentHeight; this._discoveredItemsCache[pushIndex] = item; pushIndex++; continue; } } } totalExplicitHeight += item.height; } totalExplicitHeight += this._gap * (itemCount - 1); if(this._firstGap === this._firstGap && itemCount > 1) { totalExplicitHeight += (this._firstGap - this._gap); } else if(this._lastGap === this._lastGap && itemCount > 2) { totalExplicitHeight += (this._lastGap - this._gap); } totalExplicitHeight += this._paddingTop + this._paddingBottom; if(totalPercentHeight < 100) { totalPercentHeight = 100; } if(remainingHeight != remainingHeight) //isNaN { remainingHeight = totalExplicitHeight + totalMinHeight; if(remainingHeight < minHeight) { remainingHeight = minHeight; } else if(remainingHeight > maxHeight) { remainingHeight = maxHeight; } } remainingHeight -= totalExplicitHeight; if(remainingHeight < 0) { remainingHeight = 0; } do { var needsAnotherPass:Boolean = false; var percentToPixels:Number = remainingHeight / totalPercentHeight; for(i = 0; i < pushIndex; i++) { layoutItem = ILayoutDisplayObject(this._discoveredItemsCache[i]); if(!layoutItem) { continue; } layoutData = VerticalLayoutData(layoutItem.layoutData); percentHeight = layoutData.percentHeight; var itemHeight:Number = percentToPixels * percentHeight; if(layoutItem is IFeathersControl) { feathersItem = IFeathersControl(layoutItem); var itemMinHeight:Number = feathersItem.minHeight; if(itemHeight < itemMinHeight) { itemHeight = itemMinHeight; remainingHeight -= itemHeight; totalPercentHeight -= percentHeight; this._discoveredItemsCache[i] = null; needsAnotherPass = true; } else { var itemMaxHeight:Number = feathersItem.maxHeight; if(itemHeight > itemMaxHeight) { itemHeight = itemMaxHeight; remainingHeight -= itemHeight; totalPercentHeight -= percentHeight; this._discoveredItemsCache[i] = null; needsAnotherPass = true; } } } layoutItem.height = itemHeight; } } while(needsAnotherPass) this._discoveredItemsCache.length = 0; } } } ",12234,False,2312.3852536139025,median "[id=""deploymentconfig-apps-openshift-io-v1""] = DeploymentConfig [apps.openshift.io/v1] ifdef::product-title[] include::modules/common-attributes.adoc[] endif::[] toc::[] Description:: Deployment Configs define the template for a pod and manages deploying new images or configuration changes. A single deployment configuration is usually analogous to a single micro-service. Can support many different deployment patterns, including full restart, customizable rolling updates, and fully custom behaviors, as well as pre- and post- deployment hooks. Each individual deployment is represented as a replication controller. A deployment is ""triggered"" when its configuration is changed or a tag in an Image Stream is changed. Triggers can be disabled to allow manual control over a deployment. The ""strategy"" determines how the deployment is carried out and may be changed at any time. The `latestVersion` field is updated when a new deployment is triggered by any means. Type:: `object` Required:: - `spec` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `metadata` | xref:../objects/index.adoc#objectmeta-meta-v1[`ObjectMeta meta/v1`] | | `spec` | `object` | DeploymentConfigSpec represents the desired state of the deployment. | `status` | `object` | DeploymentConfigStatus represents the current deployment state. |=== ..spec Description:: DeploymentConfigSpec represents the desired state of the deployment. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `minReadySeconds` | `integer` | MinReadySeconds is the minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready) | `paused` | `boolean` | Paused indicates that the deployment config is paused resulting in no new deployments on template changes or changes in the template caused by other triggers. | `replicas` | `integer` | Replicas is the number of desired replicas. | `revisionHistoryLimit` | `integer` | RevisionHistoryLimit is the number of old ReplicationControllers to retain to allow for rollbacks. This field is a pointer to allow for differentiation between an explicit zero and not specified. Defaults to 10. (This only applies to DeploymentConfigs created via the new group API resource, not the legacy resource.) | `selector` | `object (string)` | Selector is a label query over pods that should match the Replicas count. | `strategy` | `object` | DeploymentStrategy describes how to perform a deployment. | `template` | xref:../objects/index.adoc#podtemplatespec-core-v1[`PodTemplateSpec core/v1`] | Template is the object that describes the pod that will be created if insufficient replicas are detected. | `test` | `boolean` | Test ensures that this deployment config will have zero replicas except while a deployment is running. This allows the deployment config to be used as a continuous deployment test - triggering on images, running the deployment, and then succeeding or failing. Post strategy hooks and After actions can be used to integrate successful deployment with an action. | `triggers` | `array` | Triggers determine how updates to a DeploymentConfig result in new deployments. If no triggers are defined, a new deployment can only occur as a result of an explicit client update to the DeploymentConfig with a new LatestVersion. If null, defaults to having a config change trigger. | `triggers[]` | `object` | DeploymentTriggerPolicy describes a policy for a single trigger that results in a new deployment. |=== ..spec.strategy Description:: DeploymentStrategy describes how to perform a deployment. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `activeDeadlineSeconds` | `integer` | ActiveDeadlineSeconds is the duration in seconds that the deployer pods for this deployment config may be active on a node before the system actively tries to terminate them. | `annotations` | `object (string)` | Annotations is a set of key, value pairs added to custom deployer and lifecycle pre/post hook pods. | `customParams` | `object` | CustomDeploymentStrategyParams are the input to the Custom deployment strategy. | `labels` | `object (string)` | Labels is a set of key, value pairs added to custom deployer and lifecycle pre/post hook pods. | `recreateParams` | `object` | RecreateDeploymentStrategyParams are the input to the Recreate deployment strategy. | `resources` | xref:../objects/index.adoc#resourcerequirements-core-v1[`ResourceRequirements core/v1`] | Resources contains resource requirements to execute the deployment and any hooks. | `rollingParams` | `object` | RollingDeploymentStrategyParams are the input to the Rolling deployment strategy. | `type` | `string` | Type is the name of a deployment strategy. |=== ..spec.strategy.customParams Description:: CustomDeploymentStrategyParams are the input to the Custom deployment strategy. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is optional and overrides CMD in the container Image. | `environment` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Environment holds the environment which will be given to the container for Image. | `image` | `string` | Image specifies a container image which can carry out a deployment. |=== ..spec.strategy.recreateParams Description:: RecreateDeploymentStrategyParams are the input to the Recreate deployment strategy. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `mid` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `post` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `pre` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `timeoutSeconds` | `integer` | TimeoutSeconds is the time to wait for updates before giving up. If the value is nil, a default will be used. |=== ..spec.strategy.recreateParams.mid Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.recreateParams.mid.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.recreateParams.mid.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.recreateParams.mid.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.strategy.recreateParams.post Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.recreateParams.post.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.recreateParams.post.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.recreateParams.post.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.strategy.recreateParams.pre Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.recreateParams.pre.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.recreateParams.pre.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.recreateParams.pre.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.strategy.rollingParams Description:: RollingDeploymentStrategyParams are the input to the Rolling deployment strategy. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `intervalSeconds` | `integer` | IntervalSeconds is the time to wait between polling deployment status after update. If the value is nil, a default will be used. | `maxSurge` | xref:../objects/index.adoc#intorstring-util-intstr[`IntOrString util/intstr`] | MaxSurge is the maximum number of pods that can be scheduled above the original number of pods. Value can be an absolute number (ex: 5) or a percentage of total pods at the start of the update (ex: 10%). Absolute number is calculated from percentage by rounding up. This cannot be 0 if MaxUnavailable is 0. By default, 25% is used. Example: when this is set to 30%, the new RC can be scaled up by 30% immediately when the rolling update starts. Once old pods have been killed, new RC can be scaled up further, ensuring that total number of pods running at any time during the update is atmost 130% of original pods. | `maxUnavailable` | xref:../objects/index.adoc#intorstring-util-intstr[`IntOrString util/intstr`] | MaxUnavailable is the maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of total pods at the start of update (ex: 10%). Absolute number is calculated from percentage by rounding down. This cannot be 0 if MaxSurge is 0. By default, 25% is used. Example: when this is set to 30%, the old RC can be scaled down by 30% immediately when the rolling update starts. Once new pods are ready, old RC can be scaled down further, followed by scaling up the new RC, ensuring that at least 70% of original number of pods are available at all times during the update. | `post` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `pre` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `timeoutSeconds` | `integer` | TimeoutSeconds is the time to wait for updates before giving up. If the value is nil, a default will be used. | `updatePeriodSeconds` | `integer` | UpdatePeriodSeconds is the time to wait between individual pod updates. If the value is nil, a default will be used. |=== ..spec.strategy.rollingParams.post Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.rollingParams.post.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.rollingParams.post.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.rollingParams.post.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.strategy.rollingParams.pre Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.rollingParams.pre.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.rollingParams.pre.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.rollingParams.pre.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.triggers Description:: Triggers determine how updates to a DeploymentConfig result in new deployments. If no triggers are defined, a new deployment can only occur as a result of an explicit client update to the DeploymentConfig with a new LatestVersion. If null, defaults to having a config change trigger. Type:: `array` ..spec.triggers[] Description:: DeploymentTriggerPolicy describes a policy for a single trigger that results in a new deployment. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `imageChangeParams` | `object` | DeploymentTriggerImageChangeParams represents the parameters to the ImageChange trigger. | `type` | `string` | Type of the trigger |=== ..spec.triggers[].imageChangeParams Description:: DeploymentTriggerImageChangeParams represents the parameters to the ImageChange trigger. Type:: `object` Required:: - `from` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `automatic` | `boolean` | Automatic means that the detection of a new tag value should result in an image update inside the pod template. | `containerNames` | `array (string)` | ContainerNames is used to restrict tag updates to the specified set of container names in a pod. If multiple triggers point to the same containers, the resulting behavior is undefined. Future API versions will make this a validation error. If ContainerNames does not point to a valid container, the trigger will be ignored. Future API versions will make this a validation error. | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | From is a reference to an image stream tag to watch for changes. From.Name is the only required subfield - if From.Namespace is blank, the namespace of the current deployment trigger will be used. | `lastTriggeredImage` | `string` | LastTriggeredImage is the last image to be triggered. |=== ..status Description:: DeploymentConfigStatus represents the current deployment state. Type:: `object` Required:: - `latestVersion` - `observedGeneration` - `replicas` - `updatedReplicas` - `availableReplicas` - `unavailableReplicas` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `availableReplicas` | `integer` | AvailableReplicas is the total number of available pods targeted by this deployment config. | `conditions` | `array` | Conditions represents the latest available observations of a deployment config's current state. | `conditions[]` | `object` | DeploymentCondition describes the state of a deployment config at a certain point. | `details` | `object` | DeploymentDetails captures information about the causes of a deployment. | `latestVersion` | `integer` | LatestVersion is used to determine whether the current deployment associated with a deployment config is out of sync. | `observedGeneration` | `integer` | ObservedGeneration is the most recent generation observed by the deployment config controller. | `readyReplicas` | `integer` | Total number of ready pods targeted by this deployment. | `replicas` | `integer` | Replicas is the total number of pods targeted by this deployment config. | `unavailableReplicas` | `integer` | UnavailableReplicas is the total number of unavailable pods targeted by this deployment config. | `updatedReplicas` | `integer` | UpdatedReplicas is the total number of non-terminated pods targeted by this deployment config that have the desired template spec. |=== ..status.conditions Description:: Conditions represents the latest available observations of a deployment config's current state. Type:: `array` ..status.conditions[] Description:: DeploymentCondition describes the state of a deployment config at a certain point. Type:: `object` Required:: - `type` - `status` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `lastTransitionTime` | xref:../objects/index.adoc#time-meta-v1[`Time meta/v1`] | The last time the condition transitioned from one status to another. | `lastUpdateTime` | xref:../objects/index.adoc#time-meta-v1[`Time meta/v1`] | The last time this condition was updated. | `message` | `string` | A human readable message indicating details about the transition. | `reason` | `string` | The reason for the condition's last transition. | `status` | `string` | Status of the condition, one of True, False, Unknown. | `type` | `string` | Type of deployment condition. |=== ..status.details Description:: DeploymentDetails captures information about the causes of a deployment. Type:: `object` Required:: - `causes` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `causes` | `array` | Causes are extended data associated with all the causes for creating a new deployment | `causes[]` | `object` | DeploymentCause captures information about a particular cause of a deployment. | `message` | `string` | Message is the user specified change message, if this deployment was triggered manually by the user |=== ..status.details.causes Description:: Causes are extended data associated with all the causes for creating a new deployment Type:: `array` ..status.details.causes[] Description:: DeploymentCause captures information about a particular cause of a deployment. Type:: `object` Required:: - `type` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `imageTrigger` | `object` | DeploymentCauseImageTrigger represents details about the cause of a deployment originating from an image change trigger | `type` | `string` | Type of the trigger that resulted in the creation of a new deployment |=== ..status.details.causes[].imageTrigger Description:: DeploymentCauseImageTrigger represents details about the cause of a deployment originating from an image change trigger Type:: `object` Required:: - `from` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | From is a reference to the changed object which triggered a deployment. The field may have the kinds DockerImage, ImageStreamTag, or ImageStreamImage. |=== == API endpoints The following API endpoints are available: * `/apis/apps.openshift.io/v1/deploymentconfigs` - `GET`: list or watch objects of kind DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs` - `DELETE`: delete collection of DeploymentConfig - `GET`: list or watch objects of kind DeploymentConfig - `POST`: create a DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}` - `DELETE`: delete a DeploymentConfig - `GET`: read the specified DeploymentConfig - `PATCH`: partially update the specified DeploymentConfig - `PUT`: replace the specified DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/log` - `GET`: read log of the specified DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/scale` - `GET`: read scale of the specified DeploymentConfig - `PATCH`: partially update scale of the specified DeploymentConfig - `PUT`: replace scale of the specified DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/status` - `GET`: read status of the specified DeploymentConfig - `PATCH`: partially update status of the specified DeploymentConfig - `PUT`: replace status of the specified DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/rollback` - `POST`: create rollback of a DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/instantiate` - `POST`: create instantiate of a DeploymentConfig === /apis/apps.openshift.io/v1/deploymentconfigs .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: list or watch objects of kind DeploymentConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentconfiglist-apps-openshift-io-v1[`DeploymentConfigList apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deleteoptions-meta-v1[`DeleteOptions meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list or watch objects of kind DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentconfiglist-apps-openshift-io-v1[`DeploymentConfigList apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 201 - Created | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 202 - Accepted | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentConfig | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deleteoptions-meta-v1[`DeleteOptions meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 202 - Accepted | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `exact` | `boolean` | Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. | `export` | `boolean` | Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 201 - Created | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/log .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentLog | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `container` | `string` | The container for which to stream logs. Defaults to only container if there is one container in the pod. | `follow` | `boolean` | Follow if true indicates that the build log should be streamed until the build terminates. | `limitBytes` | `integer` | If set, the number of bytes to read from the server before terminating the log output. This may not display a complete final line of logging, and may return slightly more or slightly less than the specified limit. | `nowait` | `boolean` | NoWait if true causes the call to return immediately even if the deployment is not available yet. Otherwise the server will wait until the deployment has started. | `pretty` | `string` | If 'true', then the output is pretty printed. | `previous` | `boolean` | Return previous deployment logs. Defaults to false. | `sinceSeconds` | `integer` | A relative time in seconds before the current time from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified. | `tailLines` | `integer` | If set, the number of lines from the end of the logs to show. If not specified, logs are shown from the creation of the container or sinceSeconds or sinceTime | `timestamps` | `boolean` | If true, add an RFC3339 or RFC3339Nano timestamp at the beginning of every line of log output. Defaults to false. | `version` | `integer` | Version of the deployment for which to view logs. |=== HTTP method:: `GET` Description:: read log of the specified DeploymentConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentlog-apps-openshift-io-v1[`DeploymentLog apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/scale .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Scale | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read scale of the specified DeploymentConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update scale of the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace scale of the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | 201 - Created | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentConfig | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified DeploymentConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 201 - Created | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/rollback .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentConfigRollback | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `POST` Description:: create rollback of a DeploymentConfig .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deploymentconfigrollback-apps-openshift-io-v1[`DeploymentConfigRollback apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentconfigrollback-apps-openshift-io-v1[`DeploymentConfigRollback apps.openshift.io/v1`] | 201 - Created | xref:../objects/index.adoc#deploymentconfigrollback-apps-openshift-io-v1[`DeploymentConfigRollback apps.openshift.io/v1`] | 202 - Accepted | xref:../objects/index.adoc#deploymentconfigrollback-apps-openshift-io-v1[`DeploymentConfigRollback apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/instantiate .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentRequest | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `POST` Description:: create instantiate of a DeploymentConfig .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deploymentrequest-apps-openshift-io-v1[`DeploymentRequest apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentrequest-apps-openshift-io-v1[`DeploymentRequest apps.openshift.io/v1`] | 201 - Created | xref:../objects/index.adoc#deploymentrequest-apps-openshift-io-v1[`DeploymentRequest apps.openshift.io/v1`] | 202 - Accepted | xref:../objects/index.adoc#deploymentrequest-apps-openshift-io-v1[`DeploymentRequest apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== ",16345,True,3231.8624909234622,median "//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2003-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package mx.containers { import flash.display.DisplayObject; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import mx.containers.dividedBoxClasses.BoxDivider; import mx.core.EdgeMetrics; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.IInvalidating; import mx.core.IUIComponent; import mx.core.UIComponent; import mx.core.mx_internal; import mx.events.ChildExistenceChangedEvent; import mx.events.DividerEvent; import mx.managers.CursorManager; import mx.managers.CursorManagerPriority; import mx.styles.IStyleManager2; import mx.styles.StyleManager; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched multiple times as the user drags any divider. * * The dividerDrag event is dispatched * after the dividerPress event * and before the dividerRelease event. * * @eventType mx.events.DividerEvent.DIVIDER_DRAG * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerDrag"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user presses any divider in this container. * * The dividerPress event is dispatched * before any dividerDrag events are dispatched. * * @eventType mx.events.DividerEvent.DIVIDER_PRESS * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerPress"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user releases a divider. * * The dividerRelease event is dispatched * after the dividerDrag events, * but before the container's children are resized. * The divider's x and y properties are not updated until * after this event is triggered. As a result, a call to * hDividerBox.getDividerAt(0).x will return * the value of the original x position of the first divider. If you want the * position of the divider after the move, you can access it when the * DividerBox's updateComplete event has been triggered. * * @eventType mx.events.DividerEvent.DIVIDER_RELEASE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerRelease"", type=""mx.events.DividerEvent"")] //-------------------------------------- // Styles //-------------------------------------- /** * Thickness in pixels of the area where the user can click to drag a * divider. * This area is centered in the gaps between the container's children, * which are determined by the horizontalGap or * verticalGap style property. * The affordance cannot be set to a value larger than the gap size. * A resize cursor appears when the mouse is over this area. * * @default 6 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerAffordance"", type=""Number"", format=""Length"", inherit=""no"")] /** * The alpha value that determines the transparency of the dividers. * A value of 0.0 means completely transparent * and a value of 1.0 means completely opaque. * * @default 0.75 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerAlpha"", type=""Number"", inherit=""no"")] /** * Color of the dividers when the user presses or drags the dividers * if the liveDragging property is set to false. * If the liveDragging property is set to true, * only the divider's knob is shown. * * @default 0x6F7777 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerColor"", type=""uint"", format=""Color"", inherit=""yes"")] /** * The divider skin. * * The default value is the ""mx.skin.BoxDividerSkin"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerSkin"", type=""Class"", inherit=""no"")] /** * Thickness in pixels of the dividers when the user presses or drags the * dividers, if the liveDragging property is set to false. * (If the liveDragging property is set to true, * only the divider's knob is shown.) * The visible thickness cannot be set to a value larger than the affordance. * * @default 3 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""dividerThickness"", type=""Number"", format=""Length"", inherit=""no"")] /** * The cursor skin for a horizontal DividedBox. * * The default value is the ""mx.skins.cursor.HBoxDivider"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""horizontalDividerCursor"", type=""Class"", inherit=""no"")] /** * The cursor skin for a vertical DividedBox. * * The default value is the ""mx.skins.cursor.VBoxDivider"" symbol in the Assets.swf file. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""verticalDividerCursor"", type=""Class"", inherit=""no"")] //-------------------------------------- // Excluded APIs //-------------------------------------- [Exclude(name=""focusIn"", kind=""event"")] [Exclude(name=""focusOut"", kind=""event"")] [Exclude(name=""focusBlendMode"", kind=""style"")] [Exclude(name=""focusSkin"", kind=""style"")] [Exclude(name=""focusThickness"", kind=""style"")] [Exclude(name=""focusInEffect"", kind=""effect"")] [Exclude(name=""focusOutEffect"", kind=""effect"")] //-------------------------------------- // Other metadata //-------------------------------------- [IconFile(""DividedBox.png"")] /** * A DividedBox container measures and lays out its children * horizontally or vertically in exactly the same way as a * Box container, but it inserts * draggable dividers in the gaps between the children. * Users can drag any divider to resize the children on each side. * *

    The DividedBox class is the base class for the more commonly used * HDividedBox and VDividedBox classes.

    * *

    The direction property of a DividedBox container, inherited * from Box container, determines whether it has horizontal * or vertical layout.

    * *

    A DividedBox, HDividedBox, or VDividedBox container has the following default sizing characteristics:

    * * * * * * * * * * * * * * * * * *
    CharacteristicDescription
    Default sizeVertical DividedBox Height is large enough to hold all of its children at the default or explicit * heights of the children, plus any vertical gap between the children, plus the top and bottom padding of the * container. The width is the default or explicit width of the widest child, plus the left and right padding of * the container. *
    Horizontal DividedBox Width is large enough to hold all of its children at the * default or explicit widths of the children, plus any horizontal gap between the children, plus the left and * right padding of the container. Height is the default or explicit height of the tallest child * plus the top and bottom padding of the container.
    Default padding0 pixels for the top, bottom, left, and right values.
    Default gap10 pixels for the horizontal and vertical gaps.
    * * @mxml * *

    The <mx:DividedBox> tag inherits all of the tag * attributes of its superclass, and adds the following tag attributes:

    * *
     *  <mx:DividedBox
     *    Properties
     *    liveDragging=""false|true""
     *    resizeToContent=""false|true""
     *  
     *    Styles
     *    dividerAffordance=""6""
     *    dividerAlpha=""0.75""
     *    dividerColor=""0x6F7777""
     *    dividerSkin=""'mx.skins.BoxDividerSkin' symbol in Assets.swf""
     *    dividerThickness=""3""
     *    horizontalDividerCursor=""'mx.skins.cursor.HBoxDivider' symbol in Assets.swf""
     *    verticalDividerCursor=""'mx.skins.cursor.VBoxDivider' symbol in Assets.swf""
     * 
     *    Events
     *    dividerPress=""No default""
     *    dividerDrag=""No default""
     *    dividerRelease=""No default""
     *    >
     *      ...
     *      child tags
     *      ...
     *  </mx:DividedBox>
     *  
    * * @see mx.containers.HDividedBox * @see mx.containers.VDividedBox * * @includeExample examples/DividedBoxExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DividedBox extends Box { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static const PROXY_DIVIDER_INDEX:int = 999; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function DividedBox() { super(); addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler); addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, childRemoveHandler); // make divided box visible in automation by default because // users interact with the dividers showInAutomationHierarchy = true; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Container for holding divider objects. */ private var dividerLayer:UIComponent = null; /** * @private */ mx_internal var activeDivider:BoxDivider; /** * @private */ private var activeDividerIndex:int = -1; /** * @private */ private var activeDividerStartPosition:Number; /** * @private */ private var dragStartPosition:Number; /** * @private */ private var dragDelta:Number; /** * @private */ private var oldChildSizes:Array /* of ChildSizeInfo */; /** * @private */ private var minDelta:Number; /** * @private */ private var maxDelta:Number; /** * @private * Only allow a single divider to move at a time. */ private var dontCoalesceDividers:Boolean; /** * @private */ private var cursorID:int = CursorManager.NO_CURSOR; /** * @private * We'll measure ourselves once and then store the results here * for the lifetime of the DividedBox. */ private var dbMinWidth:Number; private var dbMinHeight:Number; private var dbPreferredWidth:Number; private var dbPreferredHeight:Number; /** * @private */ private var layoutStyleChanged:Boolean = false; /** * @private */ private var _resizeToContent:Boolean = false; /** * @private * Number of children with their includeInLayout set to true. The rest of * the children don't count. */ private var numLayoutChildren:int = 0; //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- /** * @private */ override public function set moduleFactory(moduleFactory:IFlexModuleFactory):void { super.moduleFactory = moduleFactory; styleManager.registerSizeInvalidatingStyle(""dividerAffordance""); styleManager.registerSizeInvalidatingStyle(""dividerThickness""); } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // direction //---------------------------------- /** * @private */ override public function set direction(value:String):void { if (super.direction != value) { super.direction = value; // Need to invalidate all our dividers if (dividerLayer) { for (var i:int = 0; i < dividerLayer.numChildren; i++) getDividerAt(i).invalidateDisplayList(); } } } //---------------------------------- // dividerClass //---------------------------------- /** * The class for the divider between the children. * * @default mx.containers.dividedBoxClasses.BoxDivider * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var dividerClass:Class = BoxDivider; //---------------------------------- // liveDragging //---------------------------------- [Inspectable(category=""General"")] /** * If true, the children adjacent to a divider * are continuously resized while the user drags it. * If false, they are not resized * until the user releases the divider. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var liveDragging:Boolean = false; //---------------------------------- // numDividers //---------------------------------- /** * The number of dividers. * The count is always numChildren - 1. * * @return The number of dividers. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get numDividers():int { if (dividerLayer) if (!liveDragging && activeDivider) return dividerLayer.numChildren-1; else return dividerLayer.numChildren; else return 0; } //---------------------------------- // resizeToContent //---------------------------------- /** * If true, the DividedBox automatically resizes to the size * of its children. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get resizeToContent():Boolean { return _resizeToContent; } /** * @private */ public function set resizeToContent(value:Boolean):void { if (value != _resizeToContent) { _resizeToContent = value; if (value) invalidateSize(); } } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private * Override of the measure method of Box. * *

    This function is almost identical to the Box version except * that more extensive testing of the min, max * boundary conditions is performed. This is because the DividedBox allows * default values to be less than the min value of a control.

    */ override protected function measure():void { super.measure(); // We only measure ourselves once, since as we change the // size of children, they in turn change the preferred sizes // // We need to copy the cached values into the measured fields // again to handle the case where scaleX or scaleY is not 1.0. // When the ViewStack is zoomed, code in UIComponent.measureSizes // scales the measuredWidth/Height values every time that // measureSizes is called. (Bug 100749) if (!isNaN(dbPreferredWidth) && !_resizeToContent && !layoutStyleChanged) { measuredMinWidth = dbMinWidth; measuredMinHeight = dbMinHeight; measuredWidth = dbPreferredWidth; measuredHeight = dbPreferredHeight; return; } layoutStyleChanged = false; var isVertical:Boolean = this.isVertical(); var minWidth:Number = 0; var minHeight:Number = 0; var preferredWidth:Number = 0; var preferredHeight:Number = 0; var n:int = numChildren; for (var i:int = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; var prefW:Number = child.getExplicitOrMeasuredWidth(); var prefH:Number = child.getExplicitOrMeasuredHeight(); var minW:Number = child.minWidth; var minH:Number = child.minHeight; var wFlex:Boolean = !isNaN(child.percentWidth); var hFlex:Boolean = !isNaN(child.percentHeight); // Make sure we take the lowest of the low, since pref < min. var smallestMinW:Number = Math.min(prefW, minW); var smallestMinH:Number = Math.min(prefH, minH); if (isVertical) { minWidth = Math.max(wFlex ? minW : prefW, minWidth); preferredWidth = Math.max(prefW, preferredWidth); minHeight += hFlex ? smallestMinH : prefH; preferredHeight += prefH; } else { minWidth += wFlex ? smallestMinW : prefW; preferredWidth += prefW; minHeight = Math.max(hFlex ? minH : prefH, minHeight); preferredHeight = Math.max(prefH, preferredHeight); } } var wPadding:Number = layoutObject.widthPadding(numLayoutChildren); var hPadding:Number = layoutObject.heightPadding(numLayoutChildren); measuredMinWidth = dbMinWidth = minWidth + wPadding; measuredMinHeight = dbMinHeight = minHeight + hPadding; measuredWidth = dbPreferredWidth = preferredWidth + wPadding; measuredHeight = dbPreferredHeight = preferredHeight + hPadding; } /** * @private */ override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { var n:int; var i:int; // This method gets called while dragging a divider, // but we don't want to do anything then. if (!liveDragging && activeDivider) { n = numChildren; for (i = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; // Clear out measured min/max // so super.layout() doesn't use them. child.measuredMinWidth = 0; child.measuredMinHeight = 0; } return; } // Before we allow layout, let's clear out any measured min // values of our children so that they don't restrict us. // We only honour explicitly set mins/maxs. // We also try to remove any excess space, but tweaking // the % values on the flexible components. preLayoutAdjustment(); // Let Box lay out the children. super.updateDisplayList(unscaledWidth, unscaledHeight); postLayoutAdjustment(); // Lay out the dividers. if (!dividerLayer) return; var vm:EdgeMetrics = viewMetrics; dividerLayer.x = vm.left; dividerLayer.y = vm.top; var prevChild:IUIComponent = null; var dividerIndex:int = 0; n = numChildren; for (i = 0; i < n; i++) { child = UIComponent(getChildAt(i)); if (child.includeInLayout) { if (prevChild) { layoutDivider(dividerIndex, unscaledWidth, unscaledHeight, prevChild, child); dividerIndex++; } prevChild = child; } } } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); // Need to invalidate all our dividers if (dividerLayer) { var n:int = dividerLayer.numChildren; for (var i:int = 0; i < n; i++) { getDividerAt(i).styleChanged(styleProp); } } if (styleManager.isSizeInvalidatingStyle(styleProp)) { layoutStyleChanged = true; } } /** * @private */ override protected function scrollChildren():void { super.scrollChildren(); // Scroll divider layer. if (contentPane && dividerLayer) dividerLayer.scrollRect = contentPane.scrollRect; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Returns a reference to the specified BoxDivider object * in this DividedBox container. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @return A BoxDivider object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getDividerAt(i:int):BoxDivider { return BoxDivider(dividerLayer.getChildAt(i)); } /** * Move a specific divider a given number of pixels. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @param amt The number of pixels to move the divider. * A negative number can be specified in order to move * a divider up or left. The divider movement is * constrained in the same manner as if a user * had moved it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function moveDivider(i:int, amt:Number):void { // Check whether this is a valid divider index. if (i < 0 || i >= numDividers) return; // Make sure the user is not currently dragging. if (activeDividerIndex >= 0) return; // We have to first hit the children if we haven't // yet done so since the first movement . // Mimic a divider moving. activeDividerIndex = i; // Store away child sizes, // then determine the limits on our movement. cacheChildSizes(); computeMinAndMaxDelta(); dragDelta = limitDelta(amt); // Now update the children sizes accordingly. adjustChildSizes(); invalidateSize(); invalidateDisplayList(); // Reset the divider tracking stuff. resetDividerTracking(); } /** * @private */ private function createDivider(i:int):BoxDivider { // Create separate layer for holding divider objects. if (!dividerLayer) { dividerLayer = UIComponent(rawChildren.addChild(new UIComponent())); } var divider:BoxDivider = BoxDivider(new dividerClass()); dividerLayer.addChild(divider); // if we are creating the active divider bring the divider layer // to the top most so that users can see the divider line over // the other children if (i == PROXY_DIVIDER_INDEX) { rawChildren.setChildIndex(dividerLayer, rawChildren.numChildren-1); } // Tell BoxDivider to use DividedBox's styles, // unless we are sliding the divider; in that case, // use the styles of the divider we are sliding. var basedOn:IFlexDisplayObject = (i == PROXY_DIVIDER_INDEX) ? getDividerAt(activeDividerIndex) : this; divider.styleName = basedOn; divider.owner = this; return divider; } /** * @private */ private function layoutDivider(i:int, unscaledWidth:Number, unscaledHeight:Number, prevChild:IUIComponent, nextChild:IUIComponent):void { // The mouse-over thickness of the divider is normally determined // by the dividerAffordance style, and the visible thickness is // normally determined by the dividerThickness style, assuming that // the relationship thickness <= affordance <= gap applies. But if // one of the other five orderings applies, here is a table of what // happens: // // divider divider horizontalGap/ dividerWidth/ visible width/ // Thickness Affordance verticalGap dividerHeight visible height // // 4 6 8 6 4 // 4 8 6 6 4 // 6 4 8 6 6 // 6 8 4 4 4 // 8 4 6 6 6 // 8 6 4 4 4 var divider:BoxDivider = BoxDivider(getDividerAt(i)); var vm:EdgeMetrics = viewMetrics; var verticalGap:Number = getStyle(""verticalGap""); var horizontalGap:Number = getStyle(""horizontalGap""); var thickness:Number = divider.getStyle(""dividerThickness""); var affordance:Number = divider.getStyle(""dividerAffordance""); if (isVertical()) { var dividerHeight:Number = affordance; // dividerHeight is the mouse-over height, // not necessarily the visible height. // The specified affordance should be greater than the thickness. // But if it isn't, use the thickness instead to determine the // divider height. if (dividerHeight < thickness) dividerHeight = thickness; // Don't let the divider overlap the children. if (dividerHeight > verticalGap) dividerHeight = verticalGap; divider.setActualSize(unscaledWidth - vm.left - vm.right, dividerHeight); divider.move(vm.left, Math.round((prevChild.y + prevChild.height + nextChild.y - dividerHeight) / 2)); } else { var dividerWidth:Number = affordance; // dividerWidth is the mouse-over width, // not necessarily the visible width. // The specified affordance should be greater than the thickness. // But if it isn't, use the thickness instead to determine the // divider width. if (dividerWidth < thickness) dividerWidth = thickness; // Don't let the divider overlap the children. if (dividerWidth > horizontalGap) dividerWidth = horizontalGap; divider.setActualSize(dividerWidth, unscaledHeight - vm.top - vm.bottom); divider.move(Math.round((prevChild.x + prevChild.width + nextChild.x - dividerWidth) / 2), vm.top); } divider.invalidateDisplayList(); } /** * @private */ mx_internal function changeCursor(divider:BoxDivider):void { if (cursorID == CursorManager.NO_CURSOR) { // If a cursor skin has been set for the specified BoxDivider, // use it. Otherwise, use the cursor skin for the DividedBox. var cursorClass:Class = isVertical() ? getStyle(""verticalDividerCursor"") as Class : getStyle(""horizontalDividerCursor"") as Class; cursorID = cursorManager.setCursor(cursorClass, CursorManagerPriority.HIGH, 0, 0); } } /** * @private */ mx_internal function restoreCursor():void { if (cursorID != CursorManager.NO_CURSOR) { cursorManager.removeCursor(cursorID); cursorID = CursorManager.NO_CURSOR; } } /** * @private */ mx_internal function getDividerIndex(divider:BoxDivider):int { var n:int = numChildren; for (var i:int = 0; i < n - 1; i++) { if (getDividerAt(i) == divider) return i; } return -1; } /** * @private */ private function getMousePosition(event:MouseEvent):Number { var point:Point = new Point(event.stageX, event.stageY); point = globalToLocal(point); return isVertical() ? point.y : point.x; } /** * @private */ mx_internal function startDividerDrag(divider:BoxDivider, trigger:MouseEvent):void { // Make sure the user is not currently dragging. if (activeDividerIndex >= 0) return; activeDividerIndex = getDividerIndex(divider); var event:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_PRESS); event.dividerIndex = activeDividerIndex; dispatchEvent(event); if (liveDragging) activeDivider = divider; else { activeDivider = createDivider(PROXY_DIVIDER_INDEX); activeDivider.visible = false; activeDivider.state = DividerState.DOWN; activeDivider.setActualSize(divider.width, divider.height); activeDivider.move(divider.x, divider.y); activeDivider.visible = true; divider.state = DividerState.UP; } if (isVertical()) activeDividerStartPosition = activeDivider.y; else activeDividerStartPosition = activeDivider.x; dragStartPosition = getMousePosition(trigger); dragDelta = 0; cacheChildSizes(); adjustChildSizes(); computeMinAndMaxDelta(); systemManager.getSandboxRoot().addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); systemManager.deployMouseShields(true); } /** * @private * Store away some important information about * each child for us to use while we move the divider. */ private function cacheSizes():void { oldChildSizes = []; // empty array var vertical:Boolean = isVertical(); var smallest:Number = Number.MAX_VALUE; // use a big number var n:int = numChildren; for (var i:int = 0; i < n; i++) { var child:IUIComponent = getLayoutChildAt(i); if (!child.includeInLayout) continue; var sz:Number = vertical ? child.height : child.width; var mx:Number = vertical ? child.maxHeight : child.maxWidth; var umn:Number = vertical ? child.explicitMinHeight : child.explicitMinWidth; // avoid measured values // A NaN min means 0. var mn:Number = (isNaN(umn)) ? 0 : umn; // Compute these for later use. var dMin:Number = Math.max(0, sz - mn); var dMax:Number = Math.max(0, mx - sz); if (sz > 0 && sz < smallest) smallest = sz; oldChildSizes.push(new ChildSizeInfo(sz, mn, mx, dMin, dMax)); } // Remember the smallest child size we saw. oldChildSizes.push(new ChildSizeInfo((smallest == Number.MAX_VALUE) ? 1 : smallest)); } /** * @private */ private function cacheChildSizes():void { oldChildSizes = []; // clear or store cacheSizes(); } /** * @private */ private function mouseMoveHandler(event:MouseEvent):void { dragDelta = limitDelta(getMousePosition(event) - dragStartPosition); var dividerEvent:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_DRAG); dividerEvent.dividerIndex = activeDividerIndex; dividerEvent.delta = dragDelta; dispatchEvent(dividerEvent); if (liveDragging) { adjustChildSizes(); invalidateDisplayList(); updateDisplayList(unscaledWidth, unscaledHeight); } else { if (isVertical()) activeDivider.move(0, activeDividerStartPosition + dragDelta); else activeDivider.move(activeDividerStartPosition + dragDelta, 0); } } /** * @private * * @param trigger May be null if the event is not a MouseEvent but * a mouse event from another sandbox. */ mx_internal function stopDividerDrag(divider:BoxDivider, trigger:MouseEvent):void { if (trigger) dragDelta = limitDelta(getMousePosition(trigger) - dragStartPosition); var event:DividerEvent = new DividerEvent(DividerEvent.DIVIDER_RELEASE); event.dividerIndex = activeDividerIndex; event.delta = dragDelta; dispatchEvent(event); if (!liveDragging) { if (dragDelta == 0) getDividerAt(activeDividerIndex).state = DividerState.OVER; if (activeDivider) dividerLayer.removeChild(activeDivider); activeDivider = null; adjustChildSizes(); invalidateSize(); invalidateDisplayList(); } resetDividerTracking(); systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); systemManager.deployMouseShields(false); } /** * @private */ private function resetDividerTracking():void { activeDivider = null; activeDividerIndex = -1; activeDividerStartPosition = NaN; dragStartPosition = NaN; dragDelta = NaN; oldChildSizes = null; minDelta = NaN; maxDelta = NaN; } /** * @private * Determine the maximum amount of movement that * a divider, i, can move both up and down. * * We base this calculation on the amount of * travel that each divider supports, assuming * that as one divider reaches its limits, the next * divider will move. In this way dividers will * cascade. */ private function computeAllowableMovement(at:int):void { // We break the computation into two loops, // so that we can calc min and max travel // independently as one would move the divider // either up or down. var deltaMinAbove:Number = 0; var deltaMaxAbove:Number = 0; var deltaMinBelow:Number = 0; var deltaMaxBelow:Number = 0; var n:int = numLayoutChildren; var i:int; var child:ChildSizeInfo; if (at < 0) return; for (i = at; i >= 0; i--) { child = ChildSizeInfo(oldChildSizes[i]); deltaMinAbove += (dontCoalesceDividers && deltaMinAbove) ? 0 : child.deltaMin; deltaMaxAbove += (dontCoalesceDividers && deltaMaxAbove) ? 0 : child.deltaMax; } for (i = at + 1; i < n; i++) { child = ChildSizeInfo(oldChildSizes[i]); deltaMinBelow += (dontCoalesceDividers && deltaMinBelow) ? 0 : child.deltaMin; deltaMaxBelow += (dontCoalesceDividers && deltaMaxBelow) ? 0 : child.deltaMax; } // Now the maximum movement we can have if // the divider is moved up is equal to the // smaller of how much we can shrink all // components above our divider or the // maximum of how much the components below // our divider can grow. Similarly for the // divider moving in the opposite direction. var deltaUp:Number = Math.min(deltaMinAbove, deltaMaxBelow); var deltaDn:Number = Math.min(deltaMinBelow, deltaMaxAbove); // deltaUp needs to be in -ve in order for our // update logic to work minDelta = -deltaUp; maxDelta = deltaDn; } /** * @private */ private function computeMinAndMaxDelta():void { computeAllowableMovement(activeDividerIndex); } /** * @private */ private function limitDelta(delta:Number):Number { if (delta < minDelta) delta = minDelta; else if (delta > maxDelta) delta = maxDelta; // Make sure it is not fractional, // otherwise we lose pixels. (Bug 87339) delta = Math.round(delta); return delta; } /** * @private * We distribute the delta space in the same * fashion that we calculated it. That is we * start at the divider and give out space * until we hit a limit on the component or * we run out of space to distribute. * We need to do this in both directions since * in one direction we are shrinking and * in the other we are growing. */ private function distributeDelta():void { // if there is no movement of divider we need not // do any child resizing. if (!dragDelta) return; var vertical:Boolean = isVertical(); var n:int = numLayoutChildren; var k:int = activeDividerIndex; var smallest:Number = oldChildSizes[n].size - Math.abs(dragDelta); // smallest possible child size if (smallest <= 0 || isNaN(smallest)) smallest = 1; var i:int; var size:ChildSizeInfo; var move:Number; var newSize:Number; var child:IUIComponent; var childSize:Number; // Find the index of the child before the active divider var activeDividerChildIndex:int = -1; var dividerIndex:int = -1; while (dividerIndex < activeDividerIndex) { if (UIComponent(getChildAt(++activeDividerChildIndex)).includeInLayout) ++dividerIndex; } // Distribute space starting from the center and // moving upwards. var curChildIndex:int = activeDividerChildIndex; var amt:Number = dragDelta; for (i = k; i >= 0; i--) { // If dragDelta -ve => shrink upper components // otherwise grow them. size = ChildSizeInfo(oldChildSizes[i]); move = (amt < 0) ? -Math.min(-amt, size.deltaMin) : Math.min(amt, size.deltaMax); // Adjust the component and reduce the remaining delta newSize = size.size + move; amt -= move; // Find the previous child included in the layout do { child = IUIComponent(getChildAt(curChildIndex--)); } while (!child.includeInLayout); // Adjust the child size. childSize = (newSize / smallest) * 100; if (vertical) child.percentHeight = childSize; else child.percentWidth = childSize; // Force a re-measure. if (child is IInvalidating) IInvalidating(child).invalidateSize(); } // assert(amt == 0) // Now do the same distribution but moving downwards. curChildIndex = activeDividerChildIndex + 1; amt = dragDelta; for (i = k + 1; i < n; i++) { // If dragDelta -ve => grow lower components // otherwise shrink them. size = ChildSizeInfo(oldChildSizes[i]); move = (amt < 0) ? Math.min(-amt, size.deltaMax) : -Math.min(amt, size.deltaMin); // Adjust the component and reduce the remaining delta. newSize = size.size + move; amt += move; // Find the next child included in the layout do { child = IUIComponent(getChildAt(curChildIndex++)); } while (!child.includeInLayout); childSize = (newSize / smallest) * 100; if (vertical) child.percentHeight = childSize; else child.percentWidth = childSize; // Force a re-measure. if (child is IInvalidating) IInvalidating(child).invalidateSize(); } } /** * @private * For 1.5 we normalize all children to the smallest one * So that we can remove n-1 children and still guarantee * one child can consume 100%. * Also we support the concept of fixed sized children, * which allows us to have one or more children be rigid * in the DividedBox in this case, the dividers above * and below the fixed component move in unison. */ private function adjustChildSizes():void { distributeDelta(); } /** * @private * Algorithm employed pre-layout to ensure that * we don't leave any dangling space and to ensure * that only explicit min/max values are honored. * * We first compute the sum of %'s across all * children to ensure that we have at least 100%. * If so, we are done. If not, then we attempt * to attach the remaining amount to the last * component, if not, then we distribute the * percentages evenly across all % components. * */ private function preLayoutAdjustment():void { // Calculate the total % var vertical:Boolean = isVertical(); var totalPerc:Number = 0; var percCount:Number = 0; var n:int = numChildren; var i:int; var child:IUIComponent; var perc:Number; for (i = 0; i < n; i++) { child = getLayoutChildAt(i); if (!child.includeInLayout) continue; // Clear out measured min/max // so super.layout() doesn't use them. child.measuredMinWidth = 0; child.measuredMinHeight = 0; perc = vertical ? child.percentHeight : child.percentWidth; if (!isNaN(perc)) { totalPerc += perc; percCount++; } } // during preLayoutAdjustment, we make some changes to the children's // widths and heights. We keep track of the original values in postLayoutChanges // so we can later go back and reset them so another layout pass is working // with the correct values rather than these modified values. postLayoutChanges = []; var changeObject:Object; // No flexible children, so we make the last one 100%. if (totalPerc == 0 && percCount == 0) { // Everyone is fixed and we can give 100% to the last // included in layout one without concern. for (i = n-1; i >= 0; i--) { child = UIComponent(getChildAt(i)); if (child.includeInLayout) { // create a changeObject to keep track of the original values // that this child had for width and height changeObject = {child: child}; if (vertical) { // we know there's no percentHeight originally if (child.explicitHeight) changeObject.explicitHeight = child.explicitHeight; else changeObject.percentHeight = NaN; child.percentHeight = 100; } else { // we know there's no percentWidth originally if (child.explicitWidth) changeObject.explicitWidth = child.explicitWidth; else if (child.percentWidth) changeObject.percentWidth = NaN; child.percentWidth = 100; } postLayoutChanges.push(changeObject); break; } } } else if (totalPerc < 100) { // We have some %s but they don't total to 100, so lets // distribute the delta across all of them and in the // meantime normalize all %s to unscaledHeight/Width. // The normalization takes care of the case where any one // of the components hits a min/max limit on their size, // which could result in the others filling less than 100%. var delta:Number = Math.ceil((100 - totalPerc) / percCount); for (i = 0; i < n; i++) { child = getLayoutChildAt(i); if (!child.includeInLayout) continue; changeObject = {child: child}; if (vertical) { perc = child.percentHeight; if (!isNaN(perc)) { changeObject.percentHeight = child.percentHeight; postLayoutChanges.push(changeObject); child.percentHeight = (perc + delta) * unscaledHeight; } } else { perc = child.percentWidth; if (!isNaN(perc)) { changeObject.percentWidth = child.percentWidth; postLayoutChanges.push(changeObject); child.percentWidth = (perc + delta) * unscaledWidth; } } } } // OK after all this magic we still can't guarantee that the space is // entirely filled. For example, all percent components hit their max // values. In this case, the layout will include empty space at the end, // and once the divider is touched, the non-percent based components // will be converted into percent based ones and fill the remaining // space. It seems to me that this scenario is highly unlikely. // Thus I've choosen the route of stretching the percent based // components and not touching the explicitly sized or default // sized ones. // // Another option would be to stretch the default sized components // either in addition to the percent based ones or instead of. // This seemed a little odd to me as the user never indicated // that these components are to be stretched initially, so in the end // I choose to tweak the components that the user has indicated // as being stretchable. } /** * @private * During preLayoutAdjustment, we make some changes to the children's * widths and heights. We keep track of the original values in postLayoutChanges * so we can later go back and reset them so another layout pass is working * with the correct values rather than these modified values. */ private var postLayoutChanges:Array; /** * @private * Post layout work. In preLayoutAdjustment() * sometimes we set a child's percentWidth/percentHeight. * postLayoutAdjustment() will reset the child's width or height * back to what it was. */ private function postLayoutAdjustment():void { // each object has a child property and may have a set of width/height // properties that it would like to be set var len:int = postLayoutChanges.length; for (var i:int = 0; i < len; i++) { var changeObject:Object = postLayoutChanges[i]; if (changeObject.percentWidth !== undefined) changeObject.child.percentWidth = changeObject.percentWidth; if (changeObject.percentHeight !== undefined) changeObject.child.percentHeight = changeObject.percentHeight; if (changeObject.explicitWidth !== undefined) changeObject.child.explicitWidth = changeObject.explicitWidth; if (changeObject.explicitHeight !== undefined) changeObject.child.explicitHeight = changeObject.explicitHeight; } postLayoutChanges = null; } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ private function childAddHandler(event:ChildExistenceChangedEvent):void { var child:DisplayObject = event.relatedObject; child.addEventListener(""includeInLayoutChanged"", child_includeInLayoutChangedHandler); if (!IUIComponent(child).includeInLayout) return; numLayoutChildren++; if (numLayoutChildren > 1) createDivider(numLayoutChildren - 2); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; } /** * @private */ private function childRemoveHandler(event:ChildExistenceChangedEvent):void { var child:DisplayObject = event.relatedObject; child.removeEventListener(""includeInLayoutChanged"", child_includeInLayoutChangedHandler); if (!IUIComponent(child).includeInLayout) return; numLayoutChildren--; if (numLayoutChildren > 0) dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; invalidateSize(); } /** * @private * When a child's includeInLayout changes, we either remove or add a * divider. */ private function child_includeInLayoutChangedHandler(event:Event):void { var child:UIComponent = UIComponent(event.target); if (child.includeInLayout && ++numLayoutChildren > 1) createDivider(numLayoutChildren - 2); else if (!child.includeInLayout && --numLayoutChildren > 0) dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // Clear the cached values so that we do another // measurement pass. dbMinWidth = NaN; dbMinHeight = NaN; dbPreferredWidth = NaN; dbPreferredHeight = NaN; invalidateSize(); } } } //////////////////////////////////////////////////////////////////////////////// // // Helper class: ChildSizeInfo // //////////////////////////////////////////////////////////////////////////////// /** * @private */ class ChildSizeInfo { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * @private */ public function ChildSizeInfo(size:Number, min:Number = 0, max:Number = 0, deltaMin:Number = 0, deltaMax:Number = 0) { super(); this.size = size; this.min = min; this.max = max; this.deltaMin = deltaMin; this.deltaMax = deltaMax; } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // deltaMin //---------------------------------- /** * @private */ public var deltaMin:Number; //---------------------------------- // deltaMax //---------------------------------- /** * @private */ public var deltaMax:Number; //---------------------------------- // min //---------------------------------- /** * @private */ public var min:Number; //---------------------------------- // max //---------------------------------- /** * @private */ public var max:Number; //---------------------------------- // size //---------------------------------- /** * @private */ public var size:Number; } ",12354,False,2151.338440372047,median "--- title: ""FreeBSD/powerpc 6.3-RELEASE Hardware Notes"" sidenav: download --- ++++

    The FreeBSD Documentation Project

    Copyright © 2000, 2001, 2002, 2003, 2004, 2005, 2006 The FreeBSD Documentation Project


    This is a preliminary document. It is incomplete, and in need of additional content.


    1 Introduction

    This document contains the hardware compatibility notes for FreeBSD 6.3-RELEASE on the PowerPC hardware platform (also referred to as FreeBSD/powerpc 6.3-RELEASE). It lists devices known to work on this platform, as well as some notes on boot-time kernel customization that may be useful when attempting to configure support for new devices.

    Note: This document includes information specific to the PowerPC hardware platform. Versions of the hardware compatibility notes for other architectures will differ in some details.


    2 Supported Processors and Motherboards

    The information for this paragraph has yet to be compiled.


    3 Supported Devices

    $FreeBSD: src/release/doc/en_US.ISO8859-1/hardware/common/dev.sgml,v 1.282.2.17 2007/09/13 16:25:43 brueffer Exp $

    This section describes the devices currently known to be supported by with FreeBSD on the PowerPC platform. Other configurations may also work, but simply have not been tested yet. Feedback, updates, and corrections to this list are encouraged.

    Where possible, the drivers applicable to each device or class of devices is listed. If the driver in question has a manual page in the FreeBSD base distribution (most should), it is referenced here. Information on specific models of supported devices, controllers, etc. can be found in the manual pages.

    Note: The device lists in this document are being generated automatically from FreeBSD manual pages. This means that some devices, which are supported by multiple drivers, may appear multiple times.


    3.1 Disk Controllers

    The ahc(4) driver supports the following SCSI host adapter chips and SCSI controller cards:

    • Adaptec AIC7770 host adapter chip

    • Adaptec AIC7850 host adapter chip

    • Adaptec AIC7860 host adapter chip

    • Adaptec AIC7870 host adapter chip

    • Adaptec AIC7880 host adapter chip

    • Adaptec AIC7890 host adapter chip

    • Adaptec AIC7891 host adapter chip

    • Adaptec AIC7892 host adapter chip

    • Adaptec AIC7895 host adapter chip

    • Adaptec AIC7896 host adapter chip

    • Adaptec AIC7897 host adapter chip

    • Adaptec AIC7899 host adapter chip

    • Adaptec 274X(W)

    • Adaptec 274X(T)

    • Adaptec 284X

    • Adaptec 2910

    • Adaptec 2915

    • Adaptec 2920

    • Adaptec 2930C

    • Adaptec 2930U2

    • Adaptec 2940

    • Adaptec 2940J

    • Adaptec 2940N

    • Adaptec 2940U

    • Adaptec 2940AU

    • Adaptec 2940UW

    • Adaptec 2940UW Dual

    • Adaptec 2940UW Pro

    • Adaptec 2940U2W

    • Adaptec 2940U2B

    • Adaptec 2950U2W

    • Adaptec 2950U2B

    • Adaptec 19160B

    • Adaptec 29160B

    • Adaptec 29160N

    • Adaptec 3940

    • Adaptec 3940U

    • Adaptec 3940AU

    • Adaptec 3940UW

    • Adaptec 3940AUW

    • Adaptec 3940U2W

    • Adaptec 3950U2

    • Adaptec 3960

    • Adaptec 39160

    • Adaptec 3985

    • Adaptec 4944UW

    • NEC PC-9821Xt13 (PC-98)

    • NEC RvII26 (PC-98)

    • NEC PC-9821X-B02L/B09 (PC-98)

    • NEC SV-98/2-B03 (PC-98)

    • Many motherboards with on-board SCSI support

    Controllers supported by the amr(4) driver include:

    • MegaRAID SATA 150-4

    • MegaRAID SATA 150-6

    • MegaRAID SATA 300-4X

    • MegaRAID SATA 300-8X

    • MegaRAID SCSI 320-1E

    • MegaRAID SCSI 320-2E

    • MegaRAID SCSI 320-4E

    • MegaRAID SCSI 320-0X

    • MegaRAID SCSI 320-2X

    • MegaRAID SCSI 320-4X

    • MegaRAID SCSI 320-0

    • MegaRAID SCSI 320-1

    • MegaRAID SCSI 320-2

    • MegaRAID SCSI 320-4

    • MegaRAID Series 418

    • MegaRAID i4 133 RAID

    • MegaRAID Elite 1500 (Series 467)

    • MegaRAID Elite 1600 (Series 493)

    • MegaRAID Elite 1650 (Series 4xx)

    • MegaRAID Enterprise 1200 (Series 428)

    • MegaRAID Enterprise 1300 (Series 434)

    • MegaRAID Enterprise 1400 (Series 438)

    • MegaRAID Enterprise 1500 (Series 467)

    • MegaRAID Enterprise 1600 (Series 471)

    • MegaRAID Express 100 (Series 466WS)

    • MegaRAID Express 200 (Series 466)

    • MegaRAID Express 300 (Series 490)

    • MegaRAID Express 500 (Series 475)

    • Dell PERC

    • Dell PERC 2/SC

    • Dell PERC 2/DC

    • Dell PERC 3/DCL

    • Dell PERC 3/QC

    • Dell PERC 4/DC

    • Dell PERC 4/IM

    • Dell PERC 4/SC

    • Dell PERC 4/Di

    • Dell PERC 4e/DC

    • Dell PERC 4e/Di

    • Dell PERC 4e/Si

    • Dell PERC 4ei

    • HP NetRAID-1/Si

    • HP NetRAID-3/Si (D4943A)

    • HP Embedded NetRAID

    • Intel RAID Controller SRCS16

    • Intel RAID Controller SRCU42X

    Cards supported by the isp(4) driver include:

    • ISP1000

    • ISP1020

    • ISP1040

    • Qlogic 1240

    • Qlogic 1020

    • Qlogic 1040

    • Qlogic 1080

    • Qlogic 1280

    • Qlogic 12160

    • Qlogic 210X

    • Qlogic 220X

    • Qlogic 2300

    • Qlogic 2312

    • Qlogic 234X

    • Qlogic 2322

    • Qlogic 200

    • Qlogic 2422

    • Qlogic 2432

    The following controllers are supported by the mpt(4) driver:

    • LSI Logic 53c1030, LSI Logic LSI2x320-X (Single and Dual Ultra320 SCSI)

    • LSI Logic AS1064, LSI Logic AS1068

    • LSI Logic FC909 (1Gb/s Fibre Channel)

    • LSI Logic FC909A (Dual 1Gb/s Fibre Channel)

    • LSI Logic FC919, LSI Logic 7102XP-LC (Single 2Gb/s Fibre Channel)

    • LSI Logic FC929, LSI Logic FC929X, LSI Logic 7202XP-LC (Dual 2Gb/s Fibre Channel)

    • LSI Logic FC949X (Dual 4Gb/s Fibre Channel)

    • LSI Logic FC949ES (Dual 4Gb/s Fibre Channel PCI-Express)

    The Ultra 320 SCSI controller chips supported by the mpt(4) driver can be found onboard on many systems including:

    • Dell PowerEdge 1750 thru 2850

    • IBM eServer xSeries 335

    These systems also contain Integrated Raid Mirroring and Integrated Raid Mirroring Enhanced which this driver also supports. The SAS controller chips are also present on many new AMD/Opteron based systems, like the Sun 4100. Note that this controller can drive both SAS and SATA drives or a mix of them at the same time. The Integrated Raid Mirroring available for these controllers is poorly supported at best. The Fibre Channel controller chipset are supported by a broad variety of speeds and systems. The Apple Fibre Channel HBA is in fact the FC949ES card. This driver also supports target mode for Fibre Channel cards. This support may be enabled by setting the desired role of the core via the LSI Logic firmware utility that establishes what roles the card can take on - no separate compilation is required.

    The sym(4) driver provides support for the following Symbios/LSI Logic PCI SCSI controllers:

    • 53C810

    • 53C810A

    • 53C815

    • 53C825

    • 53C825A

    • 53C860

    • 53C875

    • 53C876

    • 53C895

    • 53C895A

    • 53C896

    • 53C897

    • 53C1000

    • 53C1000R

    • 53C1010-33

    • 53C1010-66

    • 53C1510D

    The SCSI controllers supported by sym(4) can be either embedded on a motherboard, or on one of the following add-on boards:

    • ASUS SC-200, SC-896

    • Data Technology DTC3130 (all variants)

    • DawiControl DC2976UW

    • Diamond FirePort (all)

    • I-O DATA SC-UPCI (PC-98)

    • Logitec LHA-521UA (PC-98)

    • NCR cards (all)

    • Symbios cards (all)

    • Tekram DC390W, 390U, 390F, 390U2B, 390U2W, 390U3D, and 390U3W

    • Tyan S1365

    With all supported SCSI controllers, full support is provided for SCSI-I, SCSI-II, and SCSI-III peripherals, including hard disks, optical disks, tape drives (including DAT, 8mm Exabyte, Mammoth, and DLT), medium changers, processor target devices and CD-ROM drives. WORM devices that support CD-ROM commands are supported for read-only access by the CD-ROM drivers (such as cd(4)). WORM/CD-R/CD-RW writing support is provided by cdrecord(1), which is a part of the sysutils/cdrtools port in the Ports Collection.

    The following CD-ROM type systems are supported at this time:

    • SCSI interface (also includes ProAudio Spectrum and SoundBlaster SCSI) (cd(4))

    • ATAPI IDE interface ( acd(4))




    3.2 Ethernet Interfaces

    Adapters supported by the aue(4) driver include:

    • Abocom UFE1000, DSB650TX_NA

    • Accton USB320-EC, SpeedStream

    • ADMtek AN986, AN8511

    • Billionton USB100, USB100LP, USB100EL, USBE100

    • Corega Ether FEther USB-T, FEther USB-TX, FEther USB-TXS

    • D-Link DSB-650, DSB-650TX, DSB-650TX-PNA

    • Elecom LD-USBL/TX

    • Elsa Microlink USB2Ethernet

    • HP hn210e

    • I-O Data USB ETTX

    • Kingston KNU101TX

    • LinkSys USB10T adapters that contain the AN986 Pegasus chipset, USB10TA, USB10TX, USB100TX, USB100H1

    • MELCO LUA-TX, LUA2-TX

    • Netgear FA101

    • Planex UE-200TX

    • Sandberg USB to Network Link (model number 133-06)

    • Siemens Speedstream

    • SmartBridges smartNIC

    • SMC 2202USB

    • SOHOware NUB100

    The axe(4) driver supports ASIX Electronics AX88172 based USB Ethernet adapters including:

    • Buffalo (Melco Inc.) LUA-U2-KTX

    • D-Link DUB-E100, revision A

    • LinkSys USB200M

    • Netgear FA120

    • Sitecom LN-029

    • System TALKS Inc. SGC-X2UL

    The cue(4) driver supports CATC USB-EL1210A based USB Ethernet adapters including:

    • Belkin F5U011/F5U111

    • CATC Netmate

    • CATC Netmate II

    • SmartBridges SmartLink

    The dc(4) driver provides support for the following chipsets:

    • DEC/Intel 21143

    • ADMtek AL981 Comet, AN985 Centaur, ADM9511 Centaur II and ADM9513 Centaur II

    • ASIX Electronics AX88140A and AX88141

    • Conexant LANfinity RS7112 (miniPCI)

    • Davicom DM9009, DM9100, DM9102 and DM9102A

    • Lite-On 82c168 and 82c169 PNIC

    • Lite-On/Macronix 82c115 PNIC II

    • Macronix 98713, 98713A, 98715, 98715A, 98715AEC-C, 98725, 98727 and 98732

    • Xircom X3201 (cardbus only)

    The following NICs are known to work with the dc(4) driver at this time:

    • 3Com OfficeConnect 10/100B (ADMtek AN985 Centaur-P)

    • Abocom FE2500

    • Accton EN1217 (98715A)

    • Accton EN2242 MiniPCI

    • Adico AE310TX (98715A)

    • Alfa Inc GFC2204 (ASIX AX88140A)

    • Built in 10Mbps only Ethernet on Compaq Presario 7900 series desktops (21143, non-MII)

    • Built in DE500-BA on DEC Alpha workstations (21143, non-MII)

    • Built in Sun DMFE 10/100 Mbps Ethernet on Sun Netra X1 and Sun Fire V100 (DM9102A, MII)

    • Built in Ethernet on LinkSys EtherFast 10/100 Instant GigaDrive (DM9102, MII)

    • CNet Pro110B (ASIX AX88140A)

    • CNet Pro120A (98715A or 98713A) and CNet Pro120B (98715)

    • Compex RL100-TX (98713 or 98713A)

    • D-Link DFE-570TX (21143, MII, quad port)

    • Digital DE500-BA 10/100 (21143, non-MII)

    • ELECOM Laneed LD-CBL/TXA (ADMtek AN985)

    • Hawking CB102 CardBus

    • IBM EtherJet Cardbus Adapter

    • Intel PRO/100 Mobile Cardbus (versions that use the X3201 chipset)

    • Jaton XpressNet (Davicom DM9102)

    • Kingston KNE100TX (21143, MII)

    • Kingston KNE110TX (PNIC 82c169)

    • LinkSys LNE100TX (PNIC 82c168, 82c169)

    • LinkSys LNE100TX v2.0 (PNIC II 82c115)

    • LinkSys LNE100TX v4.0/4.1 (ADMtek AN985 Centaur-P)

    • Matrox FastNIC 10/100 (PNIC 82c168, 82c169)

    • Melco LGY-PCI-TXL

    • Microsoft MN-120 10/100 CardBus (ADMTek Centaur-C)

    • Microsoft MN-130 10/100 PCI (ADMTek Centaur-P)

    • NDC SOHOware SFA110A (98713A)

    • NDC SOHOware SFA110A Rev B4 (98715AEC-C)

    • NetGear FA310-TX Rev. D1, D2 or D3 (PNIC 82c169)

    • Netgear FA511

    • PlaneX FNW-3602-T (ADMtek AN985)

    • SMC EZ Card 10/100 1233A-TX (ADMtek AN985)

    • SVEC PN102-TX (98713)

    • Xircom Cardbus Realport

    • Xircom Cardbus Ethernet 10/100

    • Xircom Cardbus Ethernet II 10/100

    Adapters supported by the fxp(4) driver include:

    • Intel EtherExpress PRO/10

    • Intel InBusiness 10/100

    • Intel PRO/100B / EtherExpressPRO/100 B PCI Adapter

    • Intel PRO/100+ Management Adapter

    • Intel PRO/100 VE Desktop Adapter

    • Intel PRO/100 M Desktop Adapter

    • Intel PRO/100 S Desktop, Server and Dual-Port Server Adapters

    • Contec C-NET(PI)-100TX (PC-98)

    • NEC PC-9821Ra20, Rv20, Xv13, Xv20 internal 100Base-TX (PC-98)

    • NEC PC-9821X-B06 (PC-98)

    • Many on-board network interfaces on Intel motherboards

    Chips supported by the gem(4) driver include:

    • Apple GMAC

    • Sun ERI 10/100 Mbps Ethernet

    • Sun GEM Gigabit Ethernet

    The hme(4) driver supports the on-board Ethernet interfaces of many Sun UltraSPARC workstation and server models. Cards supported by the hme(4) driver include:

    • Sun PCI SunSwift Adapter

    • Sun SBus SunSwift Adapter “( hme” and “SUNW,hme”)

    • Sun PCI Sun100BaseT Adapter 2.0

    • Sun SBus Sun100BaseT 2.0

    • Sun PCI Quad FastEthernet Controller

    • Sun SBus Quad FastEthernet Controller

    The kue(4) driver supports Kawasaki LSI KL5KLUSB101B based USB Ethernet adapters including:

    • 3Com 3c19250

    • 3Com 3c460 HomeConnect Ethernet USB Adapter

    • ADS Technologies USB-10BT

    • AOX USB101

    • ATen UC10T

    • Abocom URE 450

    • Corega USB-T

    • D-Link DSB-650C

    • Entrega NET-USB-E45, NET-HUB-3U1E

    • I/O Data USB ETT

    • Kawasaki DU-H3E

    • LinkSys USB10T

    • Netgear EA101

    • Peracom USB Ethernet Adapter

    • Psion Gold Port USB Ethernet adapter

    • SMC 2102USB, 2104USB

    The re(4) driver supports RealTek RTL8139C+, RTL8169, RTL816xS, RTL811xS, and RTL8101E based Fast Ethernet and Gigabit Ethernet adapters including:

    • Alloy Computer Products EtherGOLD 1439E 10/100 (8139C+)

    • Compaq Evo N1015v Integrated Ethernet (8139C+)

    • Corega CG-LAPCIGT Gigabit Ethernet (8169S)

    • D-Link DGE-528(T) Gigabit Ethernet (8169S)

    • Gigabyte 7N400 Pro2 Integrated Gigabit Ethernet (8110S)

    • LevelOne GNC-0105T (8169S)

    • LinkSys EG1032 (32-bit PCI)

    • PLANEX COMMUNICATIONS Inc. GN-1200TC (8169S)

    • Xterasys XN-152 10/100/1000 NIC (8169)

    Adapters supported by the rl(4) driver include:

    • Accton “Cheetah” EN1207D (MPX 5030/5038; RealTek 8139 clone)

    • Allied Telesyn AT2550

    • Allied Telesyn AT2500TX

    • Belkin F5D5000

    • BUFFALO (Melco INC.) LPC-CB-CLX (CardBus)

    • Compaq HNE-300

    • CompUSA no-name 10/100 PCI Ethernet NIC

    • Corega FEther CB-TXD

    • Corega FEtherII CB-TXD

    • D-Link DFE-528TX

    • D-Link DFE-530TX+

    • D-Link DFE-538TX

    • D-Link DFE-690TXD

    • Edimax EP-4103DL CardBus

    • Encore ENL832-TX 10/100 M PCI

    • Farallon NetLINE 10/100 PCI

    • Genius GF100TXR

    • GigaFast Ethernet EE100-AXP

    • KTX-9130TX 10/100 Fast Ethernet

    • LevelOne FPC-0106TX

    • Longshine LCS-8038TX-R

    • NDC Communications NE100TX-E

    • Netronix Inc. EA-1210 NetEther 10/100

    • Nortel Networks 10/100BaseTX

    • OvisLink LEF-8129TX

    • OvisLink LEF-8139TX

    • Peppercon AG ROL-F

    • Planex FNW-3603-TX

    • Planex FNW-3800-TX

    • SMC EZ Card 10/100 PCI 1211-TX

    • SOHO (PRAGMATIC) UE-1211C

    The xl(4) driver supports the following hardware:

    • 3Com 3c900-TPO

    • 3Com 3c900-COMBO

    • 3Com 3c905-TX

    • 3Com 3c905-T4

    • 3Com 3c900B-TPO

    • 3Com 3c900B-TPC

    • 3Com 3c900B-FL

    • 3Com 3c900B-COMBO

    • 3Com 3c905B-T4

    • 3Com 3c905B-TX

    • 3Com 3c905B-FX

    • 3Com 3c905B-COMBO

    • 3Com 3c905C-TX

    • 3Com 3c980, 3c980B, and 3c980C server adapters

    • 3Com 3cSOHO100-TX OfficeConnect adapters

    • 3Com 3c450 HomeConnect adapters

    • 3Com 3c555, 3c556 and 3c556B mini-PCI adapters

    • 3Com 3C3SH573BT, 3C575TX, 3CCFE575BT, 3CXFE575BT, 3CCFE575CT, 3CXFE575CT, 3CCFEM656, 3CCFEM656B, and 3CCFEM656C, 3CXFEM656, 3CXFEM656B, and 3CXFEM656C CardBus adapters

    • 3Com 3c905-TX, 3c905B-TX 3c905C-TX, 3c920B-EMB, and 3c920B-EMB-WNM embedded adapters

    Both the 3C656 family of CardBus cards and the 3C556 family of MiniPCI cards have a built-in proprietary modem. Neither the xl(4) driver nor any other driver supports this modem.


    3.6 Wireless Network Interfaces

    [i386, amd64] Intel PRO/Wireless 2100 MiniPCI network adapter ( ipw(4) driver)

    [i386, amd64] Intel PRO/Wireless 2200BG/2915ABG MiniPCI and 2225BG PCI network adapters ( iwi(4) driver)


    3.12 USB Devices

    The ohci(4) driver supports all OHCI v1.0 compliant controllers including:

    • AcerLabs M5237 (Aladdin-V)

    • AMD-756

    • OPTi 82C861 (FireLink)

    • NEC uPD 9210

    • CMD Tech 670 (USB0670)

    • CMD Tech 673 (USB0673)

    • NVIDIA nForce3

    • Sun PCIO-2 (RIO USB)

    The uhci(4) driver supports all UHCI v1.1 compliant controllers including:

    • Intel 82371AB/EB (PIIX4)

    • Intel 82371SB (PIIX3)

    • VIA 83C572

    The following devices are supported by the urio(4) driver:

    • Diamond MultiMedia Rio 500

    • Diamond MultiMedia Rio 600

    • Diamond MultiMedia Rio 800

    The ulpt(4) driver provides support for USB printers and parallel printer conversion cables, including the following:

    • ATen parallel printer adapter

    • Belkin F5U002 parallel printer adapter

    • Canon BJ F850, S600

    • Canon LBP-1310, 350

    • Entrega USB-to-parallel printer adapter

    • Hewlett-Packard HP Deskjet 3420 (P/N: C8947A #ABJ)

    • Oki Data MICROLINE ML660PS

    • Seiko Epson PM-900C, 880C, 820C, 730C

    The umct(4) driver supports the following adapters:

    • Belkin F5U109

    • Belkin F5U409

    • D-Link DU-H3SP USB BAY Hub

    • Magic Control Technology USB-232

    • Sitecom USB-232

    Because there is no standard device class for USB scanners, this driver will only recognise devices whose USB IDs are explicitly listed in the table in the driver itself. The following devices are supported to date:

    • Acer Acerscan: 320U, 620U, 640U, 640BT, 1240U, C310U;

    • AGFA SnapScan: 1212U, 1236U, e20, e25, e26, e40, e50, e52, SnapScan Touch;

    • Avision 1200U

    • Canon CanoScan: D660U, N656U, N676U, N1220U, LIDE 20, LIDE 25, LIDE 30;

    • Epson Perfection: 610, 636U / 636Photo, 640U, 1200U / 1200Photo, 1240U / 1240Photo, 1250, 1260, 1270, 1600, 1640SU, 1650, 1660, 1670, 2480, 3200, 3500, 3590, 4200, 4990;

    • Epson: GT-8400UF, GT-9300UF, GT-9700F;

    • Epson Stylus: Photo RX425, CX3650, DX-5000, DX-5050, DX-6000, DX-6050 (and possibly more in the CX-5000 and DX-3800..DX-7000 family);

    • Hewlett Packard: Photosmart S20

    • Hewlett Packard Scanjet: 2200C, 3300C, 3400CSE, 4100C, 4200C, 4300C, 5200C, 5300C, 5400C, 6200C, 6300C, 8200C, 8250C, 8290C;

    • KYE ColorPage Vivid-Pro

    • Microtek Phantom: 336CX, C6;

    • Microtek ScanMaker: V6UL V6USL, X6U;

    • Minolta 5400

    • Mustek: 600 CU, 1200 CU, 1200 UB, 1200 USB;

    • Mustek BearPaw: 1200F, 1200TA;

    • NatSemi BearPaw 1200

    • Nikon CoolScan LS40 ED

    • Primax 6200

    • Primax Colorado: 1200u, 600u, USB 19200, USB 9600;

    • Primax: G2-200, G2-300, G2-600, G2600, G2E-300, G2E-3002, G2E-600, G2E600, G2X-300, G600, ReadyScan 636i;

    • Ultima 1200 UB Plus

    • UMAX Astra: 1220U, 1236U, 2000U, 2100U, 2200U, 3400;

    • Visioneer OneTouch: 3000, 5300, 7600, 6100, 6200, 8100, 8600;

    The umass(4) driver supports USB Mass Storage devices, including:

    • ADTEC Stick Drive AD-UST32M, 64M, 128M, 256M

    • Denno FireWire/USB2 Removable 2.5-inch HDD Case MIFU-25CB20

    • FujiFilm Zip USB Drive ZDR100 USB A

    • GREEN HOUSE USB Flash Memory ""PicoDrive"" GH-UFD32M, 64M, 128M

    • IBM 32MB USB Memory Key (P/N 22P5296)

    • IBM 256MB USB Drive (MSYSTEM DiskOnKey2)

    • IBM ThinkPad USB Portable CD-ROM Drive (P/N 33L5151)

    • I-O DATA USB CD/CD-R/CD-RW/DVD-R/DVD-RW/DVD-RAM/DVD-ROM Drive DVR-iUH2 (CDROM, DVD-RAM only)

    • I-O DATA USB x6 CD-RW Drive CDRW-i64/USB (CDROM only)

    • I-O DATA USB/IEEE1394 Portable HD Drive HDP-i30P/CI, HDP-i40P/CI

    • Iomega USB Zip 100/250 drive

    • Iomega Zip750 USB2.0 drive

    • Keian USB1.1/2.0 3.5-inch HDD Case KU350A

    • Kurouto Shikou USB 2.5-inch HDD Case GAWAP2.5PS-USB2.0

    • LaCie P3 HardDrive USB 200GB

    • Logitec LDR-H443U2 DVD-RAM/-R/+R/-RW/+RW drive

    • Logitec Mobile USB Memory LMC-256UD

    • Logitec USB1.1/2.0 HDD Unit SHD-E60U2

    • Logitec USB Double-Speed Floppy Drive LFD-31U2

    • Logitec USB/IEEE1394 DVD-RAM/R/RW Unit LDR-N21FU2 (CDROM only)

    • MELCO USB Flash Disk ""ClipDrive"", RUF-C32M, -C64M, -C128M, -C256M, -C512M

    • MELCO USB Flash Disk ""PetitDrive"", RUF-32M, -64M, -128M, -256Mm

    • MELCO USB2.0 Flash Disk ""PetitDrive2"", RUF-256M/U2, -512M/U2

    • MELCO USB2.0 MO Drive MO-CH640U2

    • Matshita CF-VFDU03 floppy drive

    • Merlin SM300 MP3/WMA Player (256Mb)

    • Microtech International, Inc. USB-SCSI-HD 50 USB to SCSI cable

    • Motorola E398 Mobile Phone (TransFlash memory card)

    • NOVAC USB2.0 2.5/3.5-inch HDD Case NV-HD351U

    • PNY Attache Flash Drive

    • Panasonic (""Matshita FDD CF-VFDU03"")

    • Panasonic KXL-CB20AN Portable DVD-ROM/CD-R/RW

    • Panasonic KXL-CB35AN (DVD-ROM & CD-R/RW)

    • Panasonic USB2.0 Portable CD-RW Drive KXL-RW40AN (CDROM only)

    • Panasonic floppy drive

    • Qware BeatZkey! Pro

    • RATOC Systems USB2.0 Removable HDD Case U2-MDK1, U2-MDK1B

    • SanDisk SDDR-31 (Compact Flash)

    • SanDisk SDDR-75 (only Compact Flash port works)

    • Sitecom CN-300 MultiFlash (MMC/SD, SmartMedia, CF, MemoryStick)

    • Sony Portable CD-R/RW Drive CRX10U (CDROM only)

    • TEAC Portable USB CD-ROM Unit CD-110PU/210PU

    • Time DPA20B MP3 Player (1Gb)

    • Trek Thumbdrive 8MB

    • VAIO floppy drive (includes Y-E Data Flashbuster-U)

    • Y-E Data floppy drive (720/1.44/2.88Mb)

    Among the supported digital cameras are:

    • Asahi Optical (PENTAX) Optio 230 & 330


    3.13 IEEE 1394 (Firewire) Devices

    The fwohci(4) driver provides support for PCI/CardBus FireWire interface cards. The driver supports the following IEEE 1394 OHCI chipsets:

    • Adaptec AHA-894x/AIC-5800

    • Apple Pangea

    • Apple UniNorth

    • Intel 82372FB

    • IOGEAR GUF320

    • Lucent / Agere FW322/323

    • NEC uPD72861

    • NEC uPD72870

    • NEC uPD72871/2

    • NEC uPD72873

    • NEC uPD72874

    • National Semiconductor CS4210

    • Ricoh R5C551

    • Ricoh R5C552

    • Sony CX3022

    • Sony i.LINK (CXD1947)

    • Sony i.LINK (CXD3222)

    • Sun PCIO-2 (RIO 1394)

    • Texas Instruments PCI4410A

    • Texas Instruments PCI4450

    • Texas Instruments PCI4451

    • Texas Instruments TSB12LV22

    • Texas Instruments TSB12LV23

    • Texas Instruments TSB12LV26

    • Texas Instruments TSB43AA22

    • Texas Instruments TSB43AB21/A/AI/A-EP

    • Texas Instruments TSB43AB22/A

    • Texas Instruments TSB43AB23

    • Texas Instruments TSB82AA2

    • VIA Fire II (VT6306)


    This file, and other release-related documents, can be downloaded from ftp://ftp.FreeBSD.org/.

    For questions about FreeBSD, read the documentation before contacting <questions@FreeBSD.org>.

    For questions about this documentation, e-mail <doc@FreeBSD.org>.

    ++++ ",16369,True,3578.756611203416,median "/* Feathers Copyright 2012-2021 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.media { import feathers.controls.AutoSizeMode; import feathers.controls.LayoutGroup; import feathers.core.PopUpManager; import feathers.events.FeathersEventType; import feathers.events.MediaPlayerEventType; import feathers.skins.IStyleProvider; import flash.display.Stage; import flash.display.StageDisplayState; import flash.errors.IllegalOperationError; import flash.events.FullScreenEvent; import flash.events.IOErrorEvent; import flash.events.NetStatusEvent; import flash.media.SoundTransform; import flash.net.NetConnection; import flash.net.NetStream; import starling.core.Starling; import starling.display.DisplayObject; import starling.events.Event; import starling.rendering.Painter; import starling.textures.Texture; /** * Dispatched when the original native width or height of the video content * is calculated. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    datanull
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see #nativeWidth * @see #nativeHeight * * @eventType feathers.events.MediaPlayerEventType.DIMENSIONS_CHANGE */ [Event(name=""dimensionsChange"",type=""starling.events.Event"")] /** * Dispatched when the media player changes to the full-screen display mode * or back to the normal display mode. The value of the * isFullScreen property indicates if the media player is * displayed in full screen mode or normally. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    datanull
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see #isFullScreen * @see #toggleFullScreen() * * @eventType feathers.events.MediaPlayerEventType.DISPLAY_STATE_CHANGE */ [Event(name=""displayStateChange"",type=""starling.events.Event"")] /** * Dispatched when the media player's sound transform changes. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    datanull
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see #soundTransform * * @eventType feathers.events.MediaPlayerEventType.SOUND_TRANSFORM_CHANGE */ [Event(name=""soundTransformChange"",type=""starling.events.Event"")] /** * Dispatched when the video metadata becomes available with the * onMetaData callback from the NetStream instance. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    dataThe metadata object passed with the * onMetaData callback from the NetStream.
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#event:onMetaData flash.net.NetStream onMetaData callback * * @eventType feathers.events.MediaPlayerEventType.METADATA_RECEIVED */ [Event(name=""metadataReceived"",type=""starling.events.Event"")] /** * Dispatched when a cue point is reached with the onCuePoint * callback from the NetStream instance. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    dataThe cue point object passed with the * onCuePoint callback from the NetStream.
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#event:onCuePoint flash.net.NetStream onCuePoint callback * * @eventType feathers.events.MediaPlayerEventType.CUE_POINT */ [Event(name=""metadataReceived"",type=""starling.events.Event"")] /** * Dispatched when the video texture is ready to be rendered. Indicates that * the texture property will return a * starling.textures.Texture that may be displayed in an * ImageLoader or another component. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    datanull
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see #texture * * @eventType starling.events.Event.READY */ [Event(name=""ready"",type=""starling.events.Event"")] /** * Dispatched when the video texture is no longer valid. Indicates that * the texture property will return a null value, * and that that the previous texture has been disposed and should not be * rendered any more. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    datanull
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see #texture * * @eventType feathers.events.FeathersEventType.CLEAR */ [Event(name=""clear"",type=""starling.events.Event"")] /** * Dispatched periodically when a media player's content is loading to * indicate the current progress. The bytesLoaded and * bytesTotal properties may be accessed to determine the * exact number of bytes loaded. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    dataA numeric value between 0 * and 1 that indicates how much of the media has loaded so far.
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see #bytesLoaded * @see #bytesTotal * * @eventType feathers.events.MediaPlayerEventType.LOAD_PROGRESS */ [Event(name=""loadProgress"",type=""starling.events.Event"")] /** * Dispatched when the flash.net.NetStream object dispatches * flash.events.IOErrorEvent.IO_ERROR. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    dataThe flash.events.IOErrorEvent * dispatched by the flash.net.NetStream.
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#event:ioError flash.net.NetStream: flash.events.IOErrorEvent.IO_ERROR * * @eventType starling.events.Event.IO_ERROR */ [Event(name=""ioError"",type=""starling.events.Event"")] /** * Dispatched when the flash.net.NetStream object dispatches * flash.events.NetStatusEvent.NET_STATUS with certain error * codes. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    dataThe code from the event.
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @eventType feathers.events.FeathersEventType.ERROR */ [Event(name=""error"",type=""starling.events.Event"")] /** * Controls playback of video with a flash.net.NetStream object. * * @see ../../../help/video-player.html How to use the Feathers VideoPlayer component * * @productversion Feathers 2.2.0 */ public class VideoPlayer extends BaseTimedMediaPlayer implements IVideoPlayer, IProgressiveMediaPlayer { /** * @private */ protected static const NET_STATUS_CODE_NETCONNECTION_CONNECT_SUCCESS:String = ""NetConnection.Connect.Success""; /** * @private */ protected static const NET_STATUS_CODE_NETSTREAM_PLAY_START:String = ""NetStream.Play.Start""; /** * @private */ protected static const NET_STATUS_CODE_NETSTREAM_PLAY_STOP:String = ""NetStream.Play.Stop""; /** * @private */ protected static const NET_STATUS_CODE_NETSTREAM_PLAY_STREAMNOTFOUND:String = ""NetStream.Play.StreamNotFound""; /** * @private */ protected static const NET_STATUS_CODE_NETSTREAM_PLAY_NOSUPPORTEDTRACKFOUND:String = ""NetStream.Play.NoSupportedTrackFound""; /** * @private */ protected static const NO_VIDEO_SOURCE_PLAY_ERROR:String = ""Cannot play media when videoSource property has not been set.""; /** * @private */ protected static const NO_VIDEO_SOURCE_PAUSE_ERROR:String = ""Cannot pause media when videoSource property has not been set.""; /** * @private */ protected static const NO_VIDEO_SOURCE_SEEK_ERROR:String = ""Cannot seek media when videoSource property has not been set.""; /** * The default IStyleProvider for all * VideoPlayer components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * @private */ protected static function defaultNetConnectionFactory():NetConnection { var connection:NetConnection = new NetConnection(); connection.connect(null); return connection; } /** * @private */ protected static function defaultNetStreamFactory(netConnection:NetConnection):NetStream { return new NetStream(netConnection); } /** * Constructor. */ public function VideoPlayer() { super(); } /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return VideoPlayer.globalStyleProvider; } /** * @private */ protected var _fullScreenContainer:LayoutGroup; /** * @private */ protected var _ignoreDisplayListEvents:Boolean = false; /** * @private */ protected var _soundTransform:SoundTransform; /** * @inheritDoc * *

    In the following example, the audio is muted:

    * * * videoPlayer.soundTransform = new SoundTransform(0); * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/SoundTransform.html flash.media.SoundTransform * @see #event:soundTransformChange feathers.events.MediaPlayerEventType.SOUND_TRANSFORM_CHANGE */ public function get soundTransform():SoundTransform { if(!this._soundTransform) { this._soundTransform = new SoundTransform(); } return this._soundTransform; } /** * @private */ public function set soundTransform(value:SoundTransform):void { this._soundTransform = value; if(this._netStream) { this._netStream.soundTransform = this._soundTransform; } this.dispatchEventWith(MediaPlayerEventType.SOUND_TRANSFORM_CHANGE); } /** * @private */ protected var _isWaitingForTextureReady:Boolean = false; /** * @private */ protected var _texture:Texture; /** * The texture used to display the video. This texture is not * automatically rendered by the VideoPlayer component. A * component like an ImageLoader should be added as a child * of the VideoPlayer to display the texture when it is * ready. * *

    The texture property will initially return * null. Listen for Event.READY to know when * a valid texture is available to render.

    * *

    In the following example, a listener is added for * Event.READY, and the texture is displayed by an * ImageLoader component:

    * * * function videoPlayer_readyHandler( event:Event ):void * { * var view:ImageLoader = new ImageLoader(); * view.source = videoPlayer.texture; * videoPlayer.addChildAt(view, 0); * } * * videoPlayer.addEventListener( Event.READY, videoPlayer_readyHandler ); * * @see #event:ready starling.events.Event.READY * @see feathers.controls.ImageLoader */ public function get texture():Texture { //there can be runtime errors if the texture is rendered before it //is ready, so we must return null until we're sure it's safe if(this._isWaitingForTextureReady) { return null; } return this._texture; } /** * @inheritDoc * * @see #event:dimensionsChange feathers.events.MediaPlayerEventType.DIMENSIONS_CHANGE */ public function get nativeWidth():Number { if(this._texture) { return this._texture.nativeWidth; } return 0; } /** * @inheritDoc * * @see #event:dimensionsChange feathers.events.MediaPlayerEventType.DIMENSIONS_CHANGE */ public function get nativeHeight():Number { if(this._texture) { return this._texture.nativeHeight; } return 0; } /** * @private */ protected var _netConnection:NetConnection; /** * @private */ protected var _netStream:NetStream; /** * The flash.net.NetStream object used to play the video. * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html flash.net.NetStream */ public function get netStream():NetStream { return this._netStream; } /** * @private */ protected var _hasPlayedToEnd:Boolean = false; /** * @private */ protected var _videoSource:String; /** * A string representing the video URL or any other accepted value that * may be passed to the play() function of a * NetStream object. * *

    In the following example, a video file URL is passed in:

    * * * videoPlayer.videoSource = ""http://example.com/video.m4v""; * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#play() Full description of flash.net.NetStream.play() in Adobe's Flash Platform API Reference */ public function get videoSource():String { return this._videoSource; } /** * @private */ public function set videoSource(value:String):void { if(this._videoSource === value) { return; } if(this._isPlaying) { this.stop(); } this.disposeNetStream(); if(!value) { this.disposeNetConnection(); } if(this._texture !== null) { this._texture.dispose(); this._texture = null; this.dispatchEventWith(FeathersEventType.CLEAR); } this._videoSource = value; //reset the current and total time if we were playing a different //video previously if(this._currentTime != 0) { this._currentTime = 0; this.dispatchEventWith(MediaPlayerEventType.CURRENT_TIME_CHANGE); } if(this._totalTime != 0) { this._totalTime = 0; this.dispatchEventWith(MediaPlayerEventType.TOTAL_TIME_CHANGE); } //same with the bytes loaded and total this._bytesLoaded = 0; this._bytesTotal = 0; if(this._autoPlay && this._videoSource) { this.play(); } } /** * @private */ protected var _autoPlay:Boolean = true; /** * Determines if the video starts playing immediately when the * videoSource property is set. * *

    In the following example, automatic playback is disabled:

    * * * videoPlayer.autoPlay = false; * * @see #videoSource */ public function get autoPlay():Boolean { return this._autoPlay; } /** * @private */ public function set autoPlay(value:Boolean):void { this._autoPlay = value; } /** * @private */ protected var _isFullScreen:Boolean = false; /** * Indicates if the video player is currently full screen or not. When * the player is full screen, it will be displayed as a modal pop-up * that fills the entire Starling stage. Depending on the value of * fullScreenDisplayState, it may also change the value of * the native stage's displayState property. * * @see #toggleFullScreen() * @see #event:displayStateChange feathers.events.MediaPlayerEventType.DISPLAY_STATE_CHANGE */ public function get isFullScreen():Boolean { return this._isFullScreen; } /** * @private */ protected var _normalDisplayState:String = StageDisplayState.NORMAL; [Inspectable(type=""String"",enumeration=""fullScreenInteractive,fullScreen,normal"")] /** * When the video player is displayed normally (in other words, when it * isn't full-screen), determines the value of the native stage's * displayState property. * *

    Using this property, it is possible to set the native stage's * displayState property to * StageDisplayState.FULL_SCREEN_INTERACTIVE or * StageDisplayState.FULL_SCREEN when the video player * is not in full screen mode. This might be useful for mobile apps that * should always display in full screen, while allowing a video player * to toggle between filling the entire stage and displaying at a * smaller size within its parent's layout.

    * *

    In the following example, the display state for normal mode * is changed:

    * * * videoPlayer.fullScreenDisplayState = StageDisplayState.FULL_SCREEN_INTERACTIVE; * * @default StageDisplayState.NORMAL * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/StageDisplayState.html#FULL_SCREEN_INTERACTIVE StageDisplayState.FULL_SCREEN_INTERACTIVE * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/StageDisplayState.html#FULL_SCREEN StageDisplayState.FULL_SCREEN * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/StageDisplayState.html#NORMAL StageDisplayState.NORMAL * @see #fullScreenDisplayState */ public function get normalDisplayState():String { return this._normalDisplayState; } /** * @private */ public function set normalDisplayState(value:String):void { if(this._normalDisplayState == value) { return; } this._normalDisplayState = value; if(!this._isFullScreen && this.stage) { var starling:Starling = this.stage.starling; var nativeStage:Stage = starling.nativeStage; nativeStage.displayState = this._normalDisplayState; } } /** * @private */ protected var _fullScreenDisplayState:String = StageDisplayState.FULL_SCREEN_INTERACTIVE; [Inspectable(type=""String"",enumeration=""fullScreenInteractive,fullScreen,normal"")] /** * When the video player is displayed full-screen, determines the value * of the native stage's displayState property. * *

    Using this property, it is possible to set the native stage's * displayState property to * StageDisplayState.NORMAL when the video player is in * full screen mode. The video player will still be displayed as a modal * pop-up that fills the entire Starling stage, in this situation.

    * *

    In the following example, the display state for full-screen mode * is changed:

    * * * videoPlayer.fullScreenDisplayState = StageDisplayState.FULL_SCREEN; * * @default StageDisplayState.FULL_SCREEN_INTERACTIVE * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/StageDisplayState.html#FULL_SCREEN_INTERACTIVE StageDisplayState.FULL_SCREEN_INTERACTIVE * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/StageDisplayState.html#FULL_SCREEN StageDisplayState.FULL_SCREEN * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/StageDisplayState.html#NORMAL StageDisplayState.NORMAL * @see #normalDisplayState */ public function get fullScreenDisplayState():String { return this._fullScreenDisplayState; } /** * @private */ public function set fullScreenDisplayState(value:String):void { if(this._fullScreenDisplayState == value) { return; } this._fullScreenDisplayState = value; if(this._isFullScreen && this.stage) { var starling:Starling = this.stage.starling; var nativeStage:Stage = starling.nativeStage; nativeStage.displayState = this._fullScreenDisplayState; } } /** * @private */ protected var _hideRootWhenFullScreen:Boolean = true; /** * Determines if the Starling root display object is hidden when the * video player switches to full screen mode. By hiding the root display * object, rendering performance is optimized because Starling skips a * portion of the display list that is obscured by the video player. * *

    In the following example, the root display object isn't hidden * when the video player is displayed in full screen:

    * * * videoPlayer.hideRootWhenFullScreen = false; * * @default true */ public function get hideRootWhenFullScreen():Boolean { return this._hideRootWhenFullScreen; } /** * @private */ public function set hideRootWhenFullScreen(value:Boolean):void { this._hideRootWhenFullScreen = value; } /** * @private */ protected var _netConnectionFactory:Function = defaultNetConnectionFactory; /** * Creates the flash.net.NetConnection object used to play * the video, and calls the connect() method. By default, a * value of null is passed to the connect() * method. To pass different parameters, you may use a custom * netConnectionFactory. * *

    The function is expected to have the following signature:

    *
    function():NetConnection
    * *

    In the following example, a custom factory for the * NetConnection is passed to the video player:

    * * * videoPlayer.netConnectionFactory = function():NetConnection * { * var connection:NetConnection = new NetConnection(); * connection.connect( command ); * return connection; * }; * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetConnection.html flash.net.NetConnection * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetConnection.html#connect() flash.net.NetConnection.connect() */ public function get netConnectionFactory():Function { return this._netConnectionFactory; } /** * @private */ public function set netConnectionFactory(value:Function):void { if(this._netConnectionFactory === value) { return; } this._netConnectionFactory = value; this.stop(); this.disposeNetStream(); this.disposeNetConnection(); } /** * @private */ protected var _netStreamFactory:Function = defaultNetStreamFactory; /** * Creates the flash.net.NetStream object used to play * the video. * *

    The function is expected to have the following signature:

    *
    function(netConnection:NetConnection):NetStream
    * *

    In the following example, a custom factory for the * NetStream is passed to the video player:

    * * * videoPlayer.netConnectionFactory = function(netConnection:NetConnection):NetStream * { * var stream:NetStream = new NetStream(netConnection); * //change properties here * return stream; * }; * * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html flash.net.NetStream */ public function get netStreamFactory():Function { return this._netStreamFactory; } /** * @private */ public function set netStreamFactory(value:Function):void { if(this._netStreamFactory === value) { return; } this._netStreamFactory = value; this.stop(); this.disposeNetStream(); this.disposeNetConnection(); } /** * @private */ protected var _bytesLoaded:uint = 0; /** * @copy feathers.media.IProgressiveMediaPlayer#bytesLoaded * * @see #bytesTotal * @see #event:loadProgress feathers.events.MediaPlayerEventType.LOAD_PROGRESS */ public function get bytesLoaded():uint { return this._bytesLoaded; } /** * @private */ protected var _bytesTotal:uint = 0; /** * @copy feathers.media.IProgressiveMediaPlayer#bytesTotal * * @see #bytesLoaded * @see #event:loadProgress feathers.events.MediaPlayerEventType.LOAD_PROGRESS */ public function get bytesTotal():uint { return this._bytesTotal; } /** * @private */ override public function dispose():void { this.videoSource = null; super.dispose(); } /** * @private */ override public function play():void { if(this._videoSource === null) { return; } super.play(); } /** * @private */ override public function stop():void { if(this._videoSource === null) { return; } super.stop(); } /** * @private */ override public function render(painter:Painter):void { if(this._isFullScreen) { return; } super.render(painter); } /** * Goes to full screen or returns to normal display. * *

    When the player is full screen, it will be displayed as a modal * pop-up that fills the entire Starling stage. Depending on the value * of fullScreenDisplayState, it may also change the value * of the native stage's displayState property.

    * *

    When the player is displaying normally (in other words, when it is * not full screen), it will be displayed in its parent's layout like * any other Feathers component.

    * * @see #isFullScreen * @see #fullScreenDisplayState * @see #normalDisplayState * @see #event:displayStateChange feathers.events.MediaPlayerEventType.DISPLAY_STATE_CHANGE */ public function toggleFullScreen():void { if(!this.stage) { throw new IllegalOperationError(""Cannot enter full screen mode if the video player does not have access to the Starling stage."") } var starling:Starling = this.stage.starling; var nativeStage:Stage = starling.nativeStage; var oldIgnoreDisplayListEvents:Boolean = this._ignoreDisplayListEvents; this._ignoreDisplayListEvents = true; if(this._isFullScreen) { this.root.visible = true; PopUpManager.removePopUp(this._fullScreenContainer, false); var childCount:int = this._fullScreenContainer.numChildren; for(var i:int = 0; i < childCount; i++) { var child:DisplayObject = this._fullScreenContainer.getChildAt(0); this.addChild(child); } nativeStage.removeEventListener(FullScreenEvent.FULL_SCREEN, nativeStage_fullScreenHandler); nativeStage.displayState = this._normalDisplayState; } else { if(this._hideRootWhenFullScreen) { this.root.visible = false; } nativeStage.displayState = this._fullScreenDisplayState; if(!this._fullScreenContainer) { this._fullScreenContainer = new LayoutGroup(); this._fullScreenContainer.autoSizeMode = AutoSizeMode.STAGE; } this._fullScreenContainer.layout = this._layout; childCount = this.numChildren; for(i = 0; i < childCount; i++) { child = this.getChildAt(0); this._fullScreenContainer.addChild(child); } PopUpManager.addPopUp(this._fullScreenContainer, true, false); nativeStage.addEventListener(FullScreenEvent.FULL_SCREEN, nativeStage_fullScreenHandler, false, 0, true); } this._ignoreDisplayListEvents = oldIgnoreDisplayListEvents; this._isFullScreen = !this._isFullScreen; this.dispatchEventWith(MediaPlayerEventType.DISPLAY_STATE_CHANGE); } /** * @private */ override protected function playMedia():void { if(!this._videoSource) { throw new IllegalOperationError(NO_VIDEO_SOURCE_PLAY_ERROR); } if(this._netConnection === null) { var netConnectionFactory:Function = this._netConnectionFactory !== null ? this._netConnectionFactory : defaultNetConnectionFactory; this._netConnection = NetConnection(netConnectionFactory()); } if(this._netStream === null) { if(!this._netConnection.connected) { //wait for the NetConnection to connect before trying to //create the NetStream. we'll call playMedia later. this._netConnection.addEventListener(NetStatusEvent.NET_STATUS, netConnection_netStatusHandler); return; } var netStreamFactory:Function = this._netStreamFactory !== null ? this._netStreamFactory : defaultNetStreamFactory; this._netStream = NetStream(netStreamFactory(this._netConnection)); this._netStream.client = new VideoPlayerNetStreamClient( this.netStream_onMetaData, this.netStream_onCuePoint, this.netStream_onXMPData); this._netStream.addEventListener(NetStatusEvent.NET_STATUS, netStream_netStatusHandler); this._netStream.addEventListener(IOErrorEvent.IO_ERROR, netStream_ioErrorHandler); } if(this._soundTransform === null) { this._soundTransform = new SoundTransform(); } this._netStream.soundTransform = this._soundTransform; var onCompleteCallback:Function = videoTexture_onComplete; if(this._texture !== null) { if(this._hasPlayedToEnd) { //after playing the media until the end, if we restart from the //beginning, the audio plays, but we cannot see the video. //however, we can ask the NetStream to play the video source //again from the beginning, and the video displays. if we need //to restore the time, we can do it after the NetStream //dispatches NetStream.Play.Start this._netStream.play(this._videoSource); } else { //this case happens if the video is paused and resumed without //reaching the end. //NetStream.Play.Start will not be dispatched after calling //resume(), so we need to manually add the ENTER_FRAME listener. //there's no need to seek. we're resuming from where the video //was paused. this.addEventListener(Event.ENTER_FRAME, videoPlayer_enterFrameHandler); this._netStream.resume(); } } else { //in the final case, the texture hasn't been created yet. this._isWaitingForTextureReady = true; var starling:Starling = this.stage !== null ? this.stage.starling : Starling.current; this._texture = Texture.fromNetStream(this._netStream, starling.contentScaleFactor, onCompleteCallback); this._texture.root.onRestore = videoTexture_onRestore; //don't call play() until after Texture.fromNetStream() because //the texture needs to be created first. //however, we need to call play() even though a video texture //isn't ready to be rendered yet. this._netStream.play(this._videoSource); } this._hasPlayedToEnd = false; } /** * @private */ override protected function pauseMedia():void { if(!this._videoSource) { throw new IllegalOperationError(NO_VIDEO_SOURCE_PAUSE_ERROR); } this.removeEventListener(Event.ENTER_FRAME, videoPlayer_enterFrameHandler); this._netStream.pause(); } /** * @private */ override protected function seekMedia(seconds:Number):void { if(!this._videoSource) { throw new IllegalOperationError(NO_VIDEO_SOURCE_SEEK_ERROR); } this._currentTime = seconds; if(this._hasPlayedToEnd) { //the video played until the end, which means that the current //texture cannot seek properly without reloading the media. this.playMedia(); return; } this._netStream.seek(seconds); } /** * @private */ protected function disposeNetConnection():void { if(this._netConnection === null) { return; } this._netConnection.removeEventListener(NetStatusEvent.NET_STATUS, netConnection_netStatusHandler); this._netConnection.close(); this._netConnection = null; } /** * @private */ protected function disposeNetStream():void { if(this._netStream === null) { return; } this.removeEventListener(Event.ENTER_FRAME, videoPlayer_progress_enterFrameHandler); this._netStream.removeEventListener(NetStatusEvent.NET_STATUS, netStream_netStatusHandler); this._netStream.removeEventListener(IOErrorEvent.IO_ERROR, netStream_ioErrorHandler); this._netStream.close(); this._netStream = null; } /** * @private */ protected function videoPlayer_enterFrameHandler(event:Event):void { this.setRequiresRedraw(); this._currentTime = this._netStream.time; this.dispatchEventWith(MediaPlayerEventType.CURRENT_TIME_CHANGE); } /** * @private */ protected function videoPlayer_progress_enterFrameHandler(event:Event):void { var newBytesTotal:Number = this._netStream.bytesTotal; if(newBytesTotal > 0) { var needsDispatch:Boolean = false; var newBytesLoaded:Number = this._netStream.bytesLoaded; if(this._bytesTotal != newBytesTotal) { this._bytesTotal = newBytesTotal; needsDispatch = true; } if(this._bytesLoaded != newBytesLoaded) { this._bytesLoaded = newBytesLoaded; needsDispatch = true; } if(needsDispatch) { this.dispatchEventWith(MediaPlayerEventType.LOAD_PROGRESS, false, newBytesLoaded / newBytesTotal); } if(newBytesLoaded == newBytesTotal) { this.removeEventListener(Event.ENTER_FRAME, videoPlayer_progress_enterFrameHandler); } } } /** * @private */ protected function videoTexture_onRestore():void { this.pauseMedia(); this._isWaitingForTextureReady = true; this._texture.root.attachNetStream(this._netStream, videoTexture_onComplete); //this will start playback from the beginning again, but we can seek //back to the current time once the video texture is ready. this._netStream.play(this._videoSource); } /** * @private */ protected function videoTexture_onComplete():void { this._isWaitingForTextureReady = false; //the texture is ready to be displayed this.dispatchEventWith(Event.READY); //in many cases, the layout will be affected by the new texture //dimensions, so invalidate immediately this.invalidate(INVALIDATION_FLAG_LAYOUT); var bytesTotal:Number = this._netStream.bytesTotal; if(this._bytesTotal == 0 && bytesTotal > 0) { this._bytesLoaded = this._netStream.bytesLoaded; this._bytesTotal = bytesTotal; this.dispatchEventWith(MediaPlayerEventType.LOAD_PROGRESS, false, this._bytesLoaded / bytesTotal); if(this._bytesLoaded != this._bytesTotal) { this.addEventListener(Event.ENTER_FRAME, videoPlayer_progress_enterFrameHandler); } } } /** * @private */ protected function netConnection_netStatusHandler(event:NetStatusEvent):void { var code:String = event.info.code; switch(code) { case NET_STATUS_CODE_NETCONNECTION_CONNECT_SUCCESS: { this.playMedia(); break; } } } /** * @private */ protected function netStream_onMetaData(metadata:Object):void { this.dispatchEventWith(MediaPlayerEventType.DIMENSIONS_CHANGE); this._totalTime = metadata.duration; this.dispatchEventWith(MediaPlayerEventType.TOTAL_TIME_CHANGE); this.dispatchEventWith(MediaPlayerEventType.METADATA_RECEIVED, false, metadata); } /** * @private */ protected function netStream_onCuePoint(cuePoint:Object):void { this.dispatchEventWith(MediaPlayerEventType.CUE_POINT, false, cuePoint); } /** * @private */ protected function netStream_onXMPData(xmpData:Object):void { this.dispatchEventWith(MediaPlayerEventType.XMP_DATA, false, xmpData); } /** * @private */ protected function netStream_ioErrorHandler(event:IOErrorEvent):void { this.dispatchEventWith(event.type, false, event); } /** * @private */ protected function netStream_netStatusHandler(event:NetStatusEvent):void { var code:String = event.info.code; switch(code) { case NET_STATUS_CODE_NETSTREAM_PLAY_STREAMNOTFOUND: { this.dispatchEventWith(FeathersEventType.ERROR, false, code); break; } case NET_STATUS_CODE_NETSTREAM_PLAY_NOSUPPORTEDTRACKFOUND: { this.dispatchEventWith(FeathersEventType.ERROR, false, code); break; } case NET_STATUS_CODE_NETSTREAM_PLAY_START: { if(this._netStream.time != this._currentTime) { //if we're restoring from a lost context, or we've //restarted the video after it had reached the end, the //NetStream may have restarted from the beginning. in //that case, we can manually seek to the last known good //position. this._netStream.seek(this._currentTime); } if(this._isPlaying) { //only add the listener if a video is playing. it may be //paused when restoring lost context, but we need to //temporarily start playing the NetStream in order to //restore the video texture. this.addEventListener(Event.ENTER_FRAME, videoPlayer_enterFrameHandler); } else { //the only way to prepare the video texture is to start //playing the NetStream. the media player is not in a //playing state, though, so we should pause the //NetStream now. this.pauseMedia(); } break; } case NET_STATUS_CODE_NETSTREAM_PLAY_STOP: { if(this._hasPlayedToEnd) { //we haven't cleared this flag yet after calling play() //on the NetStream. it is safe to ignore this case. return; } //any time that the NetStream stops, we want to remove the //Event.ENTER_FRAME listener. in most cases, we don't want //a listener being called every frame for no reason. on iOS, //context loss resets the NetStream time to 0, and we need //to keep the current time so that we can seek back. this.removeEventListener(Event.ENTER_FRAME, videoPlayer_enterFrameHandler); //on iOS, when context is lost, the NetStream will stop //automatically, and the time property will be reset to 0. //on other platforms, the NetStream will continue playing on //context loss, and the time will be correct. //we need to check if the context is lost or not to decide //if we've reached the end of the video or not. if(Starling.context.driverInfo !== ""Disposed"") { this.stop(); //set this flag after calling stop() because stopping //will seek to the beginning and may check for the flag. this._hasPlayedToEnd = true; this.dispatchEventWith(Event.COMPLETE); } break; } } } /** * @private */ override protected function mediaPlayer_addedHandler(event:Event):void { if(this._ignoreDisplayListEvents) { return; } super.mediaPlayer_addedHandler(event); } /** * @private */ override protected function mediaPlayer_removedHandler(event:Event):void { if(this._ignoreDisplayListEvents) { return; } super.mediaPlayer_removedHandler(event); } /** * @private */ protected function nativeStage_fullScreenHandler(event:FullScreenEvent):void { this.toggleFullScreen(); } } } dynamic class VideoPlayerNetStreamClient { public function VideoPlayerNetStreamClient(onMetaDataCallback:Function, onCuePointCallback:Function, onXMPDataCallback:Function) { this.onMetaDataCallback = onMetaDataCallback; this.onCuePointCallback = onCuePointCallback; this.onXMPDataCallback = onXMPDataCallback; } public var onMetaDataCallback:Function; public var onCuePointCallback:Function; public function onMetaData(metadata:Object):void { this.onMetaDataCallback(metadata); } public function onCuePoint(cuePoint:Object):void { this.onCuePointCallback(cuePoint); } public function onXMPData(xmpData:Object):void { this.onXMPDataCallback(xmpData); } }",12171,False,2230.5824130605406,median "= Salesforce Component :doctitle: Salesforce :shortname: salesforce :artifactid: camel-salesforce :description: Communicate with Salesforce using Java DTOs. :since: 2.12 :supportlevel: Stable :component-header: Both producer and consumer are supported //Manually maintained attributes :camel-spring-boot-name: salesforce *Since Camel {since}* *{component-header}* This component supports producer and consumer endpoints to communicate with Salesforce using Java DTOs. There is a companion <> that generates these DTOs. [NOTE] ==== Developers wishing to contribute to the component are instructed to look at the https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-component/README.md[README.md] file on instructions on how to get started and setup your environment for running integration tests. ==== == Getting Started Follow these steps to get started with the Salesforce component. . *Create a salesforce org*. If you don't already have access to a salesforce org, you can create a https://developer.salesforce.com/signup[free developer org]. . *Create a Connected App*. In salesforce, go to Setup > Apps > App Manager, then click on *New Connected App*. Make sure to check *Enable OAuth Settings* and include relevant OAuth Scopes, including the scope called *Perform requests at any time*. Click *Save*. . *Get the Consumer Key and Consumer Secret*. You'll need these to configure salesforce authentication. View your new connected app, then copy the key and secret and save in a safe place. . *Add Maven depdendency*. + [source,xml] ---- org.apache.camel camel-salesforce ---- Spring Boot users should use the starter instead. + [source,xml] ---- org.apache.camel.springboot camel-salesforce-starter ---- . *Generate DTOs*. Optionally, generate Java DTOs to represent your salesforce objects. This step isn't a hard requirement per se, but most use cases will benefit from the type safety and auto-completion. Use the <> to generate DTOs for the salesforce objects you'll be working with. . *Configure authentication*. Using the OAuth key and secret you generated previously, configure salesforce <>. . *Create routes*. Starting creating routes that interact with salesforce! // component-configure options: START // component-configure options: END // component options: START include::partial$component-configure-options.adoc[] include::partial$component-endpoint-options.adoc[] // component options: END // endpoint options: START // endpoint options: END // component headers: START include::partial$component-endpoint-headers.adoc[] // component headers: END == Authenticating to Salesforce [[AuthenticatingToSalesforce]] The component supports three OAuth authentication flows: * https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm[OAuth 2.0 Username-Password Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_refresh_token_flow.htm[OAuth 2.0 Refresh Token Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm[OAuth 2.0 JWT Bearer Token Flow] For each of the flows, different sets of properties needs to be set: .Properties to set for each authentication flow |=== | Property | Where to find it on Salesforce | Flow | clientId | Connected App, Consumer Key | All flows | clientSecret | Connected App, Consumer Secret | Username-Password, Refresh Token | userName | Salesforce user username | Username-Password, JWT Bearer Token | password | Salesforce user password | Username-Password | refreshToken | From OAuth flow callback | Refresh Token | keystore | Connected App, Digital Certificate | JWT Bearer Token |=== The component auto determines what flow you're trying to configure. In order to be explicit, set the `authenticationType` property. [NOTE] ==== Using Username-Password Flow in production is not encouraged. ==== [NOTE] ==== The certificate used in JWT Bearer Token Flow can be a self-signed certificate. The KeyStore holding the certificate and the private key must contain only single certificate-private key entry. ==== == General Usage === URI format When used as a consumer, receiving streaming events, the URI scheme is: ---- salesforce:topic?options ---- When used as a producer, invoking the Salesforce REST APIs, the URI scheme is: ---- salesforce:operationName?options ---- As a general example on using the operations in this salesforce component, the following producer endpoint uses the upsertSObject API, with the sObjectIdName parameter specifying 'Name' as the external id field. The request message body should be an SObject DTO generated using the maven plugin. [source,java] ---- ...to(""salesforce:upsertSObject?sObjectIdName=Name"")... ---- === Passing in Salesforce headers and fetching Salesforce response headers There is support to pass https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers.htm[Salesforce headers] via inbound message headers, header names that start with `Sforce` or `x-sfdc` on the Camel message will be passed on in the request, and response headers that start with `Sforce` will be present in the outbound message headers. For example to fetch API limits you can specify: [source,java] ---- // in your Camel route set the header before Salesforce endpoint //... .setHeader(""Sforce-Limit-Info"", constant(""api-usage"")) .to(""salesforce:getGlobalObjects"") .to(myProcessor); // myProcessor will receive `Sforce-Limit-Info` header on the outbound // message class MyProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String apiLimits = in.getHeader(""Sforce-Limit-Info"", String.class); } } ---- In addition, HTTP response status code and text are available as headers `Exchange.HTTP_RESPONSE_CODE` and `Exchange.HTTP_RESPONSE_TEXT`. === Sending null values to salesforce By default, SObject fields with null values are not sent to salesforce. In order to send null values to salesforce, use the `fieldsToNull` property, as follows: [source,java] ---- accountSObject.getFieldsToNull().add(""Site""); ---- == Supported Salesforce APIs Camel supports the following Salesforce APIs: * <> * <> * <> * <> * <> * <> [[RESTAPI]] === REST API The following operations are supported: * <> - Gets supported Salesforce REST API versions. * <> - Gets available Salesforce REST Resource endpoints. * <> - Lists information about limits in your org. * <> - Gets the most recently accessed items that were viewed or referenced by the current user. * <> - Gets metadata for all available SObject types. * <> - Gets basic metadata for a specific SObject type. * <> - Gets comprehensive metadata for a specific SObject type. * <> - Gets an SObject. * <> - Gets an SObject using an External Id (user defined) field. * <> - Retrieves the specified blob field from an individual record. * <> - Creates an SObject. * <> - Updates an SObject. * <> - Deletes an SObject. * <> - Inserts or updates an SObject using an External Id. * <> - Deletes an SObject using an External Id. * <> - Runs a Salesforce SOQL query. * <> - Retrieves more results (in case of large number of results) using result link returned from the 'query' API. * <> - Runs a SOQL query. Unlike the query operation, queryAll returns records that are deleted because of a merge or delete. queryAll also returns information about archived task and event records. * <> - Runs a Salesforce SOSL query. * <> - Executes a user defined APEX REST API call. * <> - Submits a record or records (batch) for approval process. * <> - Fetches a list of all approval processes. * <> - Executes up to 25 REST API requests in a single call. You can use the output of one request as the input to a subsequent request. * <> - Creates up to 200 records with parent-child relationships (up to 5 levels) in one go. * <> - Executes up to 25 sub-requests in a single request. * <> - Retrieves one or more records of the same object type. * <> - Creates up to 200 records. * <> - Update up to 200 records. * <> - Creates or updates up to 200 records based on an External Id field. * <> - Deletes up to 200 records. Unless otherwise specified, DTO types for the following options are from `org.apache.camel.component.salesforce.api.dto` or one if its sub-packages. [[getVersions]] ==== Versions `getVersions` Lists summary information about each Salesforce version currently available, including the version, label, and a link to each version's root. *Output* Type: `List` [[getResources]] ==== Resources by Version `getResources` Lists available resources for the current API version, including resource name and URI. *Output* Type: `Map` [[limits]] ==== Limits `limits` Lists information about limits in your org. For each limit, this resource returns the maximum allocation and the remaining allocation based on usage. *Output* Type: `Limits` *Additional Usage Information* With `salesforce:limits` operation you can fetch of API limits from Salesforce and then act upon that data received. The result of `salesforce:limits` operation is mapped to `org.apache.camel.component.salesforce.api.dto.Limits` class and can be used in a custom processors or expressions. For instance, consider that you need to limit the API usage of Salesforce so that 10% of daily API requests is left for other routes. The body of output message contains an instance of `org.apache.camel.component.salesforce.api.dto.Limits` object that can be used in conjunction with Content Based Router and Content Based Router and xref:languages:spel-language.adoc[Spring Expression Language (SpEL)] to choose when to perform queries. Notice how multiplying `1.0` with the integer value held in `body.dailyApiRequests.remaining` makes the expression evaluate as with floating point arithmetic, without it - it would end up making integral division which would result with either `0` (some API limits consumed) or `1` (no API limits consumed). [source,java] ---- from(""direct:querySalesforce"") .to(""salesforce:limits"") .choice() .when(spel(""#{1.0 * body.dailyApiRequests.remaining / body.dailyApiRequests.max < 0.1}"")) .to(""salesforce:query?..."") .otherwise() .setBody(constant(""Used up Salesforce API limits, leaving 10% for critical routes"")) .endChoice() ---- [[recent]] ==== Recently Viewed Items `recent` Gets the most recently accessed items that were viewed or referenced by the current user. Salesforce stores information about record views in the interface and uses it to generate a list of recently viewed and referenced records, such as in the sidebar and for the auto-complete options in search. |=== | Parameter | Type | Description | Default | Required | `limit` | `int` | An optional limit that specifies the maximum number of records to be returned. If this parameter is not specified, the default maximum number of records returned is the maximum number of entries in RecentlyViewed, which is 200 records per object. | | |=== *Output* Type: `List` *Additional Usage Information* To fetch the recent items use `salesforce:recent` operation. This operation returns an `java.util.List` of `org.apache.camel.component.salesforce.api.dto.RecentItem` objects (`List`) that in turn contain the `Id`, `Name` and `Attributes` (with `type` and `url` properties). You can limit the number of returned items by specifying `limit` parameter set to maximum number of records to return. For example: [source,java] ---- from(""direct:fetchRecentItems"") to(""salesforce:recent"") .split().body() .log(""${body.name} at ${body.attributes.url}""); ---- [[getGlobalObjects]] ==== Describe Global `getGlobalObjects` Lists the available objects and their metadata for your organization’s data. In addition, it provides the organization encoding, as well as the maximum batch size permitted in queries. *Output* Type: `GlobalObjects` [[getBasicInfo]] ==== sObject Basic Information `getBasicInfo` Describes the individual metadata for the specified object. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Alternatively, can be supplied in Body. | | x |=== *Output* Type: `SObjectBasicInfo` [[getDescription]] ==== sObject Describe `getDescription` Completely describes the individual metadata at all levels for the specified object. For example, this can be used to retrieve the fields, URLs, and child relationships for the Account object. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Alternatively, can be supplied in Body. | | x |=== *Output* Type: `SObjectDescription` [[getSObject]] ==== Retrieve SObject `getSObject` Accesses record based on the specified object ID. This operation requires the `packages` option to be set. |=== | Parameter | Type | Description | Default | Required | `sObjectName` | `String` | Name of SObject, e.g. `Account` | | x | `sObjectId` | `String` | Id of record to retrieve. | | x | `sObjectFields` | `String` | Comma-separated list of fields to retrieve|| | Body | `AbstractSObjectBase` | Instance of SObject that is used to query salesforce. If supplied, overrides `sObjectName` and `sObjectId` parameters. | | |=== *Output* Type: Subclass of `AbstractSObjectBase` [[getSObjectWithId]] ==== Retrieve SObject by External Id `getSObjectWithId` Accesses record based on an External ID value. This operation requires the `packages` option to be set. |=== | Parameter | Type | Description | Default | Required | `sObjectIdName` | `String` | Name of External ID field | | x | `sObjectIdValue` | `String` | External ID value | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account` | | x | Body | `AbstractSObjectBase` | Instance of SObject that is used to query salesforce. If supplied, overrides `sObjectName` and `sObjectIdValue` parameters. | | |=== *Output* Type: Subclass of `AbstractSObjectBase` [[getBlobField]] ==== sObject Blob Retrieve `getBlobField` Retrieves the specified blob field from an individual record. |=== | Parameter | Type | Description | Default | Required | `sObjectBlobFieldName` | `String` | SOSL query | |x | `sObjectName` | `String` | Name of SObject, e.g. Account | | Required if SObject not supplied in body | `sObjectId` | `String` | Id of SObject | | Required if SObject not supplied in body | Body | `AbstractSObjectBase` | SObject to determine type and Id from. If not supplied, `sObjectId` and `sObjectName` parameters will be used. | | Required if `sObjectId` and `sObjectName` are not supplied |=== *Output* Type: `InputStream` [[createSObject]] ==== Create SObject `createSObject` Creates a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | Instance of SObject to create. | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== *Output* Type: `CreateSObjectResult` [[updateSObject]] ==== Update SObject `updateSObject` Updates a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | Instance of SObject to update. | | x | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` | `sObjectId` | `String` | Id of record to update. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== [[upsertSObject]] ==== Upsert SObject `upsertSObject` Upserts a record by External ID. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` or `String` | SObject to update. | | x | `sObjectIdName` | `String` | External ID field name. ||x | `sObjectIdValue` | `String` | External ID value || If Body is a `String` | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is a `String` |=== *Output* Type: `UpsertSObjectResult` [[deleteSObject]] ==== Delete SObject `deleteSObject` Deletes a record in salesforce. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` | Instance of SObject to delete. | | | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is not an `AbstractSObjectBase` instance | `sObjectId` | `String` | Id of record to delete. | | If Body is not an `AbstractSObjectBase` instance |=== [[deleteSObjectWithId]] ==== Delete SObject by External Id `deleteSObjectWithId` Deletes a record in salesforce by External ID. |=== | Parameter | Type | Description | Default | Required | Body | `AbstractSObjectBase` | Instance of SObject to delete. | | | `sObjectIdName` | `String` | Name of External ID field | | If Body is not an `AbstractSObjectBase` instance | `sObjectIdValue` | `String` | External ID value | | If Body is not an `AbstractSObjectBase` instance | `sObjectName` | `String` | Name of SObject, e.g. `Account`. Only used if Camel cannot determine from Body. | | If Body is not an `AbstractSObjectBase` instance |=== [[query]] ==== Query `query` Runs a Salesforce SOQL query |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | SOQL query | | x | streamQueryResult | `Boolean` | If true, returns a streaming `Iterator` and transparently retrieves all pages as needed. The `sObjectClass` option must reference an `AbstractQueryRecordsBase` subclass. | false | | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| | One of sObjectClass or sObjectName is required | `sObjectName` | `String` | Simple name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `QueryRecordsAccount`. Requires the `package` option be set.| |One of sObjectClass or sObjectName is required |=== *Output* Type: Instance of class supplied in `sObjectClass`, or `Iterator` if `streamQueryResult` is true. [[queryMore]] ==== Query More `queryMore` Retrieves more results (in case of large number of results) using result link returned from the `query` and `queryAll` operations. |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | `nextRecords` value. Can be found in a prior query result in the `AbstractQueryRecordsBase.nextRecordsUrl` property | | X | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| |One of sObjectClass or sObjectName is required | `sObjectName` | `String` | Simple name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `QueryRecordsAccount`. Requires the `package` option be set. | |One of sObjectClass or sObjectName is required |=== *Output* Type: Instance of class supplied in `sObjectClass` [[queryAll]] ==== Query All `queryAll` Executes the specified SOQL query. Unlike the `query` operation , `queryAll` returns records that are deleted because of a merge or delete. It also returns information about archived task and event records. |=== | Parameter | Type | Description | Default | Required | Body or `sObjectQuery` | `String` | SOQL query | | x | streamQueryResult | `Boolean` | If true, returns a streaming `Iterable` and transparently retrieves all pages as needed. The `sObjectClass` option must reference an `AbstractQueryRecordsBase` subclass. | false | | `sObjectClass` | `String` | Fully qualified name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `org.my.dto.QueryRecordsAccount`| |One of sObjectClass or sObjectName is required | `sObjectName` | `String` | Simple name of class to deserialize response to. Usually a subclass of `AbstractQueryRecordsBase`, e.g. `QueryRecordsAccount`. Requires the `package` option be set.| |One of sObjectClass or sObjectName is required |=== *Output* Type: Instance of class supplied in `sObjectClass`, or `Iterator` if `streamQueryResult` is true. [[sosl_search]] ==== Search `search` Runs a Salesforce SOSL search |=== | Parameter | Type | Description | Default | Required | Body or `sObjectSearch` | `String` | Name of field to retrieve | |x |=== *Output* Type: `SearchResult2` [[approval]] ==== Submit Approval `approval` Submit a record or records (batch) for approval process. |=== | Parameter | Type | Description | Default | Required | Body | `ApprovalRequest` or `List` | `ApprovalRequest`(s) to process | | | `Approval.` | Prefixed headers or endpoint options in lieu of passing an `ApprovalRequest` in the body. | | | |=== *Output* Type: `ApprovalResult` *Additional usage information* All the properties are named exactly the same as in the Salesforce REST API prefixed with `approval.`. You can set approval properties by setting `approval.PropertyName` of the Endpoint these will be used as template -- meaning that any property not present in either body or header will be taken from the Endpoint configuration. Or you can set the approval template on the Endpoint by assigning `approval` property to a reference onto a bean in the Registry. You can also provide header values using the same `approval.PropertyName` in the incoming message headers. And finally body can contain one `AprovalRequest` or an `Iterable` of `ApprovalRequest` objects to process as a batch. The important thing to remember is the priority of the values specified in these three mechanisms: . value in body takes precedence before any other . value in message header takes precedence before template value . value in template is set if no other value in header or body was given For example to send one record for approval using values in headers use: Given a route: [source,java] ---- from(""direct:example1"")// .setHeader(""approval.ContextId"", simple(""${body['contextId']}"")) .setHeader(""approval.NextApproverIds"", simple(""${body['nextApproverIds']}"")) .to(""salesforce:approval?""// + ""approval.actionType=Submit""// + ""&approval.comments=this is a test""// + ""&approval.processDefinitionNameOrId=Test_Account_Process""// + ""&approval.skipEntryCriteria=true""); ---- You could send a record for approval using: [source,java] ---- final Map body = new HashMap<>(); body.put(""contextId"", accountIds.iterator().next()); body.put(""nextApproverIds"", userId); final ApprovalResult result = template.requestBody(""direct:example1"", body, ApprovalResult.class); ---- [[approvals]] ==== Get Approvals `approvals` Returns a list of all approval processes. *Output* Type: `Approvals` [[composite]] ==== Composite `composite` Executes up to 25 REST API requests in a single call. You can use the output of one request as the input to a subsequent request. The response bodies and HTTP statuses of the requests are returned in a single response body. The entire series of requests counts as a single call toward your API limits. Use Salesforce Composite API to submit multiple chained requests. Individual requests and responses are linked with the provided _reference_. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectComposite` | Contains REST API sub-requests to be executed. | | x | `rawPayload` | `Boolean` | Any (un)marshaling of requests and responses are assumed to be handled by the route | false | x | `compositeMethod` | `String` | HTTP method to use for rawPayload requests. | `POST` | |=== *Output* Type: `SObjectCompositeResponse` [NOTE] ==== Composite API supports only JSON payloads. ==== [NOTE] ==== As with the batch API, the results can vary from API to API so the body of each `SObjectCompositeResult` instance is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests are made in JSON format hold some type information (i.e. it is known what values are strings and what values are numbers). ==== Lets look at an example: [source,java] ---- SObjectComposite composite = new SObjectComposite(""38.0"", true); // first insert operation via an external id final Account updateAccount = new TestAccount(); updateAccount.setName(""Salesforce""); updateAccount.setBillingStreet(""Landmark @ 1 Market Street""); updateAccount.setBillingCity(""San Francisco""); updateAccount.setBillingState(""California""); updateAccount.setIndustry(Account_IndustryEnum.TECHNOLOGY); composite.addUpdate(""Account"", ""001xx000003DIpcAAG"", updateAccount, ""UpdatedAccount""); final Contact newContact = new TestContact(); newContact.setLastName(""John Doe""); newContact.setPhone(""1234567890""); composite.addCreate(newContact, ""NewContact""); final AccountContactJunction__c junction = new AccountContactJunction__c(); junction.setAccount__c(""001xx000003DIpcAAG""); junction.setContactId__c(""@{NewContact.id}""); composite.addCreate(junction, ""JunctionRecord""); final SObjectCompositeResponse response = template.requestBody(""salesforce:composite"", composite, SObjectCompositeResponse.class); final List results = response.getCompositeResponse(); final SObjectCompositeResult accountUpdateResult = results.stream().filter(r -> ""UpdatedAccount"".equals(r.getReferenceId())).findFirst().get() final int statusCode = accountUpdateResult.getHttpStatusCode(); // should be 200 final Map accountUpdateBody = accountUpdateResult.getBody(); final SObjectCompositeResult contactCreationResult = results.stream().filter(r -> ""JunctionRecord"".equals(r.getReferenceId())).findFirst().get() ---- *Using the `rawPayload` option* It's possible to directly call Salesforce composite by preparing the Salesforce JSON request in the route thanks to the `rawPayload` option. For instance, you can have the following route: ---- from(""timer:fire?period=2000"").setBody(constant(""{\\n"" + "" \\""allOrNone\\"" : true,\\n"" + "" \\""records\\"" : [ { \\n"" + "" \\""attributes\\"" : {\\""type\\"" : \\""FOO\\""},\\n"" + "" \\""Name\\"" : \\""123456789\\"",\\n"" + "" \\""FOO\\"" : \\""XXXX\\"",\\n"" + "" \\""ACCOUNT\\"" : 2100.0\\n"" + "" \\""ExternalID\\"" : \\""EXTERNAL\\""\\n"" "" }]\\n"" + ""}"") .to(""salesforce:composite?rawPayload=true"") .log(""${body}""); ---- The route directly creates the body as JSON and directly submit to salesforce endpoint using `rawPayload=true` option. With this approach, you have the complete control on the Salesforce request. `POST` is the default HTTP method used to send raw Composite requests to salesforce. Use the `compositeMethod` option to override to the other supported value, `GET`, which returns a list of other available composite resources. [[composite-tree]] ==== Composite Tree `composite-tree` Create up to 200 records with parent-child relationships (up to 5 levels) in one go. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectTree` | Contains REST API sub-requests to be executed. | | x |=== *Output* Type: `SObjectTree` To create up to 200 records including parent-child relationships use `salesforce:composite-tree` operation. This requires an instance of `org.apache.camel.component.salesforce.api.dto.composite.SObjectTree` in the input message and returns the same tree of objects in the output message. The `org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase` instances within the tree get updated with the identifier values (`Id` property) or their corresponding `org.apache.camel.component.salesforce.api.dto.composite.SObjectNode` is populated with `errors` on failure. Note that for some records operation can succeed and for some it can fail -- so you need to manually check for errors. Easiest way to use this functionality is to use the DTOs generated by the `camel-salesforce-maven-plugin`, but you also have the option of customizing the references that identify the each object in the tree, for instance primary keys from your database. Lets look at an example: [source,java] ---- Account account = ... Contact president = ... Contact marketing = ... Account anotherAccount = ... Contact sales = ... Asset someAsset = ... // build the tree SObjectTree request = new SObjectTree(); request.addObject(account).addChildren(president, marketing); request.addObject(anotherAccount).addChild(sales).addChild(someAsset); final SObjectTree response = template.requestBody(""salesforce:composite-tree"", tree, SObjectTree.class); final Map> result = response.allNodes() .collect(Collectors.groupingBy(SObjectNode::hasErrors)); final List withErrors = result.get(true); final List succeeded = result.get(false); final String firstId = succeeded.get(0).getId(); ---- [[composite-batch]] ==== Composite Batch `composite-batch` Submit a composition of requests in batch. Executes up to 25 sub-requests in a single request. |=== | Parameter | Type | Description | Default | Required | Body | `SObjectBatch` | Contains sub-requests to be executed. | | x |=== *Output* Type: `SObjectBatchResponse` The Composite API batch operation allows you to accumulate multiple requests in a batch and then submit them in one go, saving the round trip cost of multiple individual requests. Each response is then received in a list of responses with the order preserved, so that the n-th requests response is in the n-th place of the response. [NOTE] ==== The results can vary from API to API so the result of each sub-request (`SObjectBatchResult.result`) is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests are made in JSON format and hold some type information (i.e. it is known what values are strings and what values are numbers). ==== Lets look at an example: [source,java] ---- final String acountId = ... final SObjectBatch batch = new SObjectBatch(""53.0""); final Account updates = new Account(); updates.setName(""NewName""); batch.addUpdate(""Account"", accountId, updates); final Account newAccount = new Account(); newAccount.setName(""Account created from Composite batch API""); batch.addCreate(newAccount); batch.addGet(""Account"", accountId, ""Name"", ""BillingPostalCode""); batch.addDelete(""Account"", accountId); final SObjectBatchResponse response = template.requestBody(""salesforce:composite-batch"", batch, SObjectBatchResponse.class); boolean hasErrors = response.hasErrors(); // if any of the requests has resulted in either 4xx or 5xx HTTP status final List results = response.getResults(); // results of three operations sent in batch final SObjectBatchResult updateResult = results.get(0); // update result final int updateStatus = updateResult.getStatusCode(); // probably 204 final Object updateResultData = updateResult.getResult(); // probably null final SObjectBatchResult createResult = results.get(1); // create result @SuppressWarnings(""unchecked"") final Map createData = (Map) createResult.getResult(); final String newAccountId = createData.get(""id""); // id of the new account, this is for JSON, for XML it would be createData.get(""Result"").get(""id"") final SObjectBatchResult retrieveResult = results.get(2); // retrieve result @SuppressWarnings(""unchecked"") final Map retrieveData = (Map) retrieveResult.getResult(); final String accountName = retrieveData.get(""Name""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""Name"") final String accountBillingPostalCode = retrieveData.get(""BillingPostalCode""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""BillingPostalCode"") final SObjectBatchResult deleteResult = results.get(3); // delete result final int updateStatus = deleteResult.getStatusCode(); // probably 204 final Object updateResultData = deleteResult.getResult(); // probably null ---- [[compositeRetrieveSObjectCollections]] ==== Retrieve Multiple Records with Fewer Round-Trips `compositeRetrieveSObjectCollections` Retrieve one or more records of the same object type. |=== | Parameter | Type | Description | Default | Required | ids | List of String or comma-separated string | A list of one or more IDs of the objects to return. All IDs must belong to the same object type. | | x | fields | List of String or comma-separated string | A list of fields to include in the response. The field names you specify must be valid, and you must have read-level permissions to each field. | | x | sObjectName | String | Type of SObject, e.g. `Account` | | x | sObjectClass | String | Fully-qualified class name of DTO class to use for deserializing the response. | | Required if `sObjectName` parameter does not resolve to a class that exists in the package specified by the `package` option. |=== *Output* Type: `List` of class determined by `sObjectName` or `sObjectClass` header [[compositeCreateSObjectCollections]] ==== Create SObject Collections `compositeCreateSObjectCollections` Add up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description| Default| Required | Body | List of `SObject` | A list of SObjects to create | | x | `allOrNone` | boolean | Indicates whether to roll back the entire request when the creation of any object fails (true) or to continue with the independent creation of other objects in the request. | false | |=== *Output* Type: `List` [[compositeUpdateSObjectCollections]] ==== Update SObject Collections `compositeUpdateSObjectCollections` Update up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description | Default | Required | Body | List of `SObject` | A list of SObjects to update | | x | `allOrNone` | `boolean` | Indicates whether to roll back the entire request when the update of any object fails (true) or to continue with the independent update of other objects in the request. | false | |=== *Output* Type: `List` [[compositeUpsertSObjectCollections]] ==== Upsert SObject Collections `compositeUpsertSObjectCollections` Create or update (upsert) up to 200 records based on an external ID field. Mixed SObject types is not supported. |=== | Parameter | Type | Description | Default | Required | Body | List of `SObject` | A list of SObjects to upsert | | x | `allOrNone` | `boolean` | Indicates whether to roll back the entire request when the upsert of any object fails (true) or to continue with the independent upsert of other objects in the request. | false | | `sObjectName` | `String` | Type of SObject, e.g. `Account` | | x | `sObjectIdName` | `String` | Name of External ID field | | x |=== *Output* Type: `List` [[compositeDeleteSObjectCollections]] ==== Delete SObject Collections `compositeDeleteSObjectCollections` Delete up to 200 records. Mixed SObject types is supported. |=== | Parameter | Type | Description | Default | Required | `sObjectIds` or request body | List of String or comma-separated string | A list of up to 200 IDs of objects to be deleted. | | x | `allOrNone` | boolean | Indicates whether to roll back the entire request when the deletion of any object fails (true) or to continue with the independent deletion of other objects in the request. | false | |=== *Output* Type: `List` [[ApexRESTAPI]] === Apex REST API [[apexCall]] ==== Invoke an Apex REST Web Service method `apexCall` You can https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_intro.htm[expose your Apex class and methods] so that external applications can access your code and your application through the REST architecture. The URI format for invoking Apex REST is: ---- salesforce:apexCall[/yourApexRestUrl][?options] ---- You can supply the apexUrl either in the endpoint (see above), or as the `apexUrl` option as listed in the table below. In either case the Apex URL can contain placeholders in the format of `\\{headerName}`. E.g., for the Apex URL `MyApexClass/\\{id}`, the value of the header named `id` will be used to replace the placeholder. |=== | Parameter | Type | Description| Default| Required | Body | `Map` if `GET`, otherwise `String` or `InputStream`| In the case of a `GET`, the body (`Map` instance) is transformed into query parameters. For other HTTP methods, the body is used for the HTTP body. | | | `apexUrl` | `String` | The portion of the endpoint URL after `https://instance.salesforce.com/services/apexrest/`, e.g., 'MyApexClass/' | | Yes, unless supplied in endpoint | `apexMethod` | `String` | The HTTP method (e.g. `GET`, `POST`) to use. | `GET` | | `rawPayload` | `Boolean` | If true, Camel will not serialize the request or response bodies. | false | | Header: `apexQueryParam.[paramName]` | Object | Headers that override apex parameters passed in the endpoint. | | | `sObjectName` | `String` | Name of sObject (e.g. `Merchandise__c`) used to deserialize the response | | If `rawPayload` is false and `sObjectClass` not supplied | `sObjectClass` | `String` | Fully qualified class name used to deserialize the response | | If `rawPayload` is false and `sObjectName` not supplied |=== *Output* Type: Instance of class supplied in `sObjectClass` input header. [[Bulk2API]] === Bulk 2.0 API The Bulk 2.0 API has a simplified model over the original Bulk API. Use it to quickly load a large amount of data into salesforce, or query a large amount of data out of salesforce. Data must be provided in CSV format, usually via an `InputStream` instance. PK chunking is performed automatically. The minimum API version for Bulk 2.0 is v41.0. The minimum API version for Bulk Queries is v47.0. DTO classes mentioned below are from the `org.apache.camel.component.salesforce.api.dto.bulkv2` package. The following operations are supported: * <> - Creates a bulk ingest job. * <> - Adds a batch of data to an ingest job. * <> - Closes an ingest job. * <> - Aborts an ingest job. * <> - Deletes an ingest job. * <> - Gets successful results for an ingest job. * <> - Gets failed results for an ingest job. * <> - Gets unprocessed records for an ingest job. * <> - Gets an ingest Job. * <> - Gets all ingest jobs. * <> - Creates a query job. * <> - Gets query job results. * <> - Aborts a query job. * <> - Deletes a query job. * <> - Gets a query job. * <> - Gets all query jobs. [[bulk2CreateJob]] ==== Create a Job `bulk2CreateJob` Creates a bulk ingest job. |=== | Parameter | Type | Description| Default| Required | Body | `Job` | Job to create | | x |=== *Output* Type: `Job` [[bulk2CreateBatch]] ==== Upload a Batch of Job Data `bulk2CreateBatch` Adds a batch of data to an ingest job. |=== | Parameter | Type | Description| Default| Required | Body | `InputStream` or `String` | CSV data. The first row must contain headers. | | Required if `jobId` not supplied | `jobId` | `String` | Id of Job to create batch under | | x |=== [[bulk2CloseJob]] ==== Close a Job `bulk2CloseJob` Closes an ingest job. You must close the job in order for it to be processed or aborted/deleted. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to close | | x |=== *Output* Type: `Job` [[bulk2AbortJob]] ==== Abort a Job `bulk2AbortJob` Aborts an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to abort | | x |=== *Output* Type: `Job` [[bulk2DeleteJob]] ==== Delete a Job `bulk2DeleteJob` Deletes an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to delete | | x |=== [[bulk2GetSuccessfulResults]] ==== Get Job Successful Record Results `bulk2GetSuccessfulResults` Gets successful results for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x |=== *Output* Type: `InputStream` + Contents: CSV data [[bulk2GetFailedResults]] ==== Get Job Failed Record Results `bulk2GetFailedResults` Gets failed results for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x |=== *Output* Type: `InputStream` + Contents: CSV data [[bulk2GetUnprocessedRecords]] ==== Get Job Unprocessed Record Results `bulk2GetUnprocessedRecords` Gets unprocessed records for an ingest job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get records for | | x |=== *Output* Type: `InputStream` Contents: CSV data [[bulk2GetJob]] ==== Get Job Info `bulk2GetJob` Gets an ingest Job. |=== | Parameter | Type | Description| Default| Required | Body | `Job` | Will use Id of supplied Job to retrieve Job | | Required if `jobId` not supplied | `jobId` | `String` | Id of Job to retrieve | | Required if `Job` not supplied in body |=== *Output* Type: `Job` [[bulk2GetAllJobs]] ==== Get All Jobs `bulk2GetAllJobs` Gets all ingest jobs. |=== | Parameter | Type | Description| Default| Required | `queryLocator` | `String` | Used in subsequent calls if results span multiple pages | | |=== *Output* Type: `Jobs` If the `done` property of the `Jobs` instance is false, there are additional pages to fetch, and the `nextRecordsUrl` property contains the value to be set in the `queryLocator` parameter on subsequent calls. [[bulk2CreateQueryJob]] ==== Create a Query Job `bulk2CreateQueryJob` Gets a query job. |=== | Parameter | Type | Description| Default| Required | Body | `QueryJob` | QueryJob to create | | x |=== *Output* Type: `QueryJob` [[bulk2GetQueryJobResults]] ==== Get Results for a Query Job `bulk2GetQueryJobResults` Get bulk query job results. `jobId` parameter is required. Accepts `maxRecords` and `locator` parameters. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get results for | | x | `maxRecords` | `Integer` | Id of Job to get results for | | | `locator` | `locator` | Value to use for subsequent calls | | |=== *Output* Type: `InputStream` Contents: CSV data Response message headers include `Sforce-NumberOfRecords` and `Sforce-Locator` headers. The value of `Sforce-Locator` can be passed into subsequent calls via the `locator` parameter. [[bulk2AbortQueryJob]] ==== Abort a Query Job `bulk2AbortQueryJob` Aborts a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to abort | | x |=== *Output* Type: `QueryJob` [[bulk2DeleteQueryJob]] ==== Delete a Query Job `bulk2DeleteQueryJob` Deletes a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to delete | | x |=== [[bulk2GetQueryJob]] ==== Get Information About a Query Job `bulk2GetQueryJob` Gets a query job. |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to retrieve | | x |=== *Output* Type: `QueryJob` [[bulk2GetAllQueryJobs]] ==== Get Information About All Query Jobs `bulk2GetAllQueryJobs` Gets all query jobs. |=== | Parameter | Type | Description| Default| Required | `queryLocator` | `String` | Used in subsequent calls if results span multiple pages | | |=== *Output* Type: `QueryJobs` If the `done` property of the `QueryJobs` instance is false, there are additional pages to fetch, and the `nextRecordsUrl` property contains the value to be set in the `queryLocator` parameter on subsequent calls. [[BulkAPI]] === Bulk (original) API Producer endpoints can use the following APIs. All Job data formats, i.e. xml, csv, zip/xml, and zip/csv are supported. + The request and response have to be marshalled/unmarshalled by the route. Usually the request will be some stream source like a CSV file, and the response may also be saved to a file to be correlated with the request. The following operations are supported: * <> - Creates a Salesforce Bulk Job. * <> - Gets a Job using its Salesforce Id * <> - Closes a Job * <> - Aborts a Job * <> - Submits a Batch within a Bulk Job * <> - Gets a Batch using Id * <> - Gets all Batches for a Bulk Job Id * <> - Gets Request data (XML/CSV) for a Batch * <> - Gets the results of the Batch when its complete * <> - Creates a Batch from an SOQL query * <> - Gets a list of Result Ids for a Batch Query * <> - Gets results for a Result Id [[createJob]] ==== Create a Job `createJob` Creates a Salesforce Bulk Job. PK Chunking is supported via the pkChunking* options. See an explanation https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/async_api_headers_enable_pk_chunking.htm[here]. |=== | Parameter | Type | Description| Default| Required | Body | `JobInfo` | Job to create | | x | `pkChunking` | `Boolean` | Whether to use PK Chunking | false | | `pkChunkingChunkSize` | `Integer` | | | | `pkChunkingStartRow` | `Integer` | | | | `pkChunkingParent` | `String` | | | |=== *Output* Type: `JobInfo` [[getJob]] ==== Get Job Details `getJob` Gets a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job to get | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[closeJob]] ==== Close a Job `closeJob` Closes a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[abortJob]] ==== Abort a Job `abortJob` Aborts a Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `JobInfo` [[createBatch]] ==== Add a Batch to a Job `createBatch` Submits a Batch within a Bulk Job |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | x | `contentType` | `String` | Content type of body. Can be XML, CSV, ZIP_XML or ZIP_CSV | | x | `Body` | `InputStream` or `String` | Batch data | | x |=== *Output* Type: `BatchInfo` [[getBatch]] ==== Get Information for a Batch `getBatch` Get a Batch |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `BatchInfo` [[getAllBatches]] ==== Get Information for All Batches in a Job `getAllBatches` Gets all Batches for a Bulk Job Id |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | Body | `JobInfo` | `JobInfo` instance from which Id will be used | | Required if `jobId` not supplied |=== *Output* Type: `List` [[getRequest]] ==== Get a Batch Request `getRequest` Gets Request data (XML/CSV) for a Batch |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` [[getResults]] ==== Get Batch Results `getResults` Gets the results of the Batch when it's complete |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` [[createBatchQuery]] ==== Create Bulk Query Batch `createBatchQuery` Creates a Batch from an SOQL query |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `contentType` | `String` | Content type of body. Can be XML, CSV, ZIP_XML or ZIP_CSV | | Required if `JobInfo` instance not supplied in body | `sObjectQuery` | `String` | SOQL query to be used for this batch | | Required if not supplied in body | Body | `JobInfo` or `String` | Either `JobInfo` instance from which `jobId` and `contentType` will be used, or `String` to be used as the Batch query | | Required `JobInfo` if `jobId` and `contentType` not supplied. |=== *Output* Type: `BatchInfo` [[getQueryResultIds]] ==== Get Batch Results `getQueryResultIds` Gets a list of Result Ids for a Batch Query |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | Body | `BatchInfo` | `JobInfo` instance from which `jobId` and `batchId` will be used | | Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `List` [[getQueryResult]] ==== Get Bulk Query Results `getQueryResult` Gets results for a Result Id |=== | Parameter | Type | Description| Default| Required | `jobId` | `String` | Id of Job | | Required if body not supplied | `batchId` | `String` | Id of Batch | | Required if body not supplied | `resultId` | `String` | Id of Result | | If not passed in body | Body | `BatchInfo` or `String` | `JobInfo` instance from which `jobId` and `batchId` will be used. Otherwise can be a `String` containing the `resultId` | | `BatchInfo` Required if `jobId` and `BatchId` not supplied |=== *Output* Type: `InputStream` For example, the following producer endpoint uses the createBatch API to create a Job Batch. The in message must contain a body that can be converted into an `InputStream` (usually UTF-8 CSV or XML content from a file, etc.) and header fields 'jobId' for the Job and 'contentType' for the Job content type, which can be XML, CSV, ZIP_XML or ZIP_CSV. The put message body will contain `BatchInfo` on success, or throw a `SalesforceException` on error. [source,java] ---- ...to(""salesforce:createBatch"").. ---- [[StreamingAPI]] === Streaming API The Streaming API enables streaming of events using push technology and provides a subscription mechanism for receiving events in near real time. The Streaming API subscription mechanism supports multiple types of events, including PushTopic events, generic events, platform events, and Change Data Capture events. ==== Push Topics The URI format for consuming Push Topics is: ---- salesforce:[?options] ---- To create and subscribe to a topic [source,java] ---- from(""salesforce:CamelTestTopic?notifyForFields=ALL¬ifyForOperations=ALL&sObjectName=Merchandise__c&updateTopic=true&sObjectQuery=SELECT Id, Name FROM Merchandise__c"")... ---- To subscribe to an existing topic [source,java] ---- from(""salesforce:CamelTestTopic&sObjectName=Merchandise__c"")... ---- |=== | Parameter | Type | Description| Default| Required | `sObjectName` | `String` | SObject to monitor | | x | `sObjectQuery` | `String` | SOQL query used to create Push Topic | | Required for creating new topics | `updateTopic` | `Boolean` | Whether to update an existing Push Topic if exists | false | | `notifyForFields` | `NotifyForFieldsEnum` | Specifies how the record is evaluated against the PushTopic query. | Referenced | | `notifyForOperationCreate` | `Boolean` | Whether a create operation should generate a notification. | false | | `notifyForOperationDelete` | `Boolean` | Whether a delete operation should generate a notification. | false | | `notifyForOperationUndelete` | `Boolean` | Whether an undelete operation should generate a notification. | false | | `notifyForOperationUpdate` | `Boolean` | Whether an update operation should generate a notification. | false | | `notifyForOperations` | `NotifyForOperationsEnum` | Whether an update operation should generate a notification. Only for use in API version < 29.0 | All | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: Class passed via `sObjectName` parameter ==== Platform Events To emit a platform event use the <> operation, passing an instance of a platform event, e.g. `Order_Event__e`. The URI format for consuming platform events is: ---- salesforce:event/ ---- For example, to receive platform events use for the event type `Order_Event__e`: [source,java] ---- from(""salesforce:event/Order_Event__e"") ---- |=== | Parameter | Type | Description| Default| Required | `rawPayload` | `Boolean` | If false, operation returns a `PlatformEvent`, otherwise returns the raw Bayeux Message | false | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: `PlatformEvent` or `org.cometd.bayeux.Message` ==== Change Data Capture Events Change Data Capture (CDC) allows you to receive near-real-time changes of Salesforce records, and synchronize corresponding records in an external data store. Change Data Capture publishes change events, which represent changes to Salesforce records. Changes include creation of a new record, updates to an existing record, deletion of a record, and undeletion of a record. The URI format to consume CDC events is as follows: All Selected Entities ---- salesforce:data/ChangeEvents ---- Standard Objects ---- salesforce:data/ChangeEvent ---- Custom Objects ---- salesforce:data/__ChangeEvent ---- Here are a few examples [source,java] ---- from(""salesforce:data/ChangeEvents?replayId=-1"").log(""being notified of all change events"") from(""salesforce:data/AccountChangeEvent?replayId=-1"").log(""being notified of change events for Account records"") from(""salesforce:data/Employee__ChangeEvent?replayId=-1"").log(""being notified of change events for Employee__c custom object"") ---- More details about how to use the Camel Salesforce component change data capture capabilities could be found in the https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/ChangeEventsConsumerIntegrationTest.java[ChangeEventsConsumerIntegrationTest]. The https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm[Salesforce developer guide] is a good fit to better know the subtleties of implementing a change data capture integration application. The dynamic nature of change event body fields, high level replication steps as well as security considerations could be of interest. |=== | Parameter | Type | Description| Default| Required | `rawPayload` | `Boolean` | If false, operation returns a `Map`, otherwise returns the raw Bayeux `Message` | false | | `replayId` | `int` | The replayId value to use when subscribing.| | | `defaultReplayId` | `int` | Default replayId setting if no value is found in initialReplayIdMap. | -1 | | `fallBackReplayId` | `int` | ReplayId to fall back to after an Invalid Replay Id response. | -1 | |=== *Output* Type: `Map` or `org.cometd.bayeux.Message` Headers |=== | Name | Description | `CamelSalesforceChangeType` | `CREATE`, `UPDATE`, `DELETE` or `UNDELETE` |=== [[ReportsAPI]] === Reports API * <> - Gets up to 200 of the reports you most recently viewed. * <> - Retrieves report description. * <> - Runs a report synchronously. * <> - Runs a report asynchronously. * <> - Returns a list of instances for a report that you requested to be run asynchronously. * <> - Retrieves results for an instance of a report run asynchronously. [[getRecentReports]] ==== Report List `getRecentReports` Gets up to 200 of the reports you most recently viewed. *Output* Type: `List` [[getReportDescription]] ==== Describe Report `getReportDescription` Retrieves the report, report type, and related metadata for a report, either in a tabular or summary or matrix format. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | Body | `String` | Id of Report | | Required if not supplied in `reportId` parameter |=== *Output* Type: `ReportDescription` [[executeSyncReport]] ==== Execute Sync `executeSyncReport` Runs a report synchronously with or without changing filters and returns the latest summary data. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `includeDetails` | `Boolean` | Whether to include details | false| | `reportMetadata` | `ReportMetadata` | Optionally, pass ReportMetadata here instead of body | | | Body | `ReportMetadata` | If supplied, will use instead of `reportId` | | Required if not supplied in `reportId` parameter |=== *Output* Type: `AbstractReportResultsBase` [[executeAsyncReport]] ==== Execute Async `executeAsyncReport` Runs an instance of a report asynchronously with or without filters and returns the summary data with or without details. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `includeDetails` | `Boolean` | Whether to include details | false| | `reportMetadata` | `ReportMetadata` | Optionally, pass ReportMetadata here instead of body | | | Body | `ReportMetadata` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `ReportInstance` [[getReportInstances]] ==== Instances List `getReportInstances` Returns a list of instances for a report that you requested to be run asynchronously. Each item in the list is treated as a separate instance of the report. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | Body | `String` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `List` [[getReportResults]] ==== Instance Results `getReportResults` Contains the results of running a report. |=== | Parameter | Type | Description| Default| Required | `reportId` | `String` | Id of Report | | Required if not supplied in body | `instanceId` | `String` | Id of Report instance | | x | Body | `String` | If supplied, will use instead of `reportId` parameter | | Required if not supplied in `reportId` parameter |=== *Output* Type: `AbstractReportResultsBase` == Miscellaneous Operations * <> - Send requests to salesforce and have full, raw control over endpoint, parameters, body, etc. [[raw]] === Raw `raw` Sends HTTP requests to salesforce with full, raw control of all aspects of the call. Any serialization or deserialization of request and response bodies must be performed in the route. The `Content-Type` HTTP header will be automatically set based on the `format` option, but this can be overridden with the `rawHttpHeaders` option. |=== | Parameter | Type | Description| Default| Required | Body | `String` or `InputStream` | Body of the HTTP request | | | `rawPath` | `String` | The portion of the endpoint URL after the domain name, e.g., '/services/data/v51.0/sobjects/Account/' | | x | `rawMethod` | `String` | The HTTP method | | x | `rawQueryParameters` | `String` | Comma separated list of message headers to include as query parameters. Do not url-encode values as this will be done automatically. | | | `rawHttpHeaders` | `String` | Comma separated list of message headers to include as HTTP headers | | |=== *Output* Type: `InputStream` ==== Query example In this example we'll send a query to the REST API. The query must be passed in a URL parameter called ""q"", so we'll create a message header called q and tell the raw operation to include that message header as a URL parameter: ---- from(""direct:queryExample"") .setHeader(""q"", ""SELECT Id, LastName FROM Contact"") .to(""salesforce:raw?format=JSON&rawMethod=GET&rawQueryParameters=q&rawPath=/services/data/v51.0/query"") // deserialize JSON results or handle in some other way ---- ==== SObject example In this example, we'll pass a Contact the REST API in a `create` operation. Since the `raw` operation does not perform any serialization, we make sure to pass XML in the message body ---- from(""direct:createAContact"") .setBody(constant(""TestLast"")) .to(""salesforce:raw?format=XML&rawMethod=POST&rawPath=/services/data/v51.0/sobjects/Contact"") ---- The response is: ---- 0034x00000RnV6zAAF true ---- == Uploading a document to a ContentWorkspace Create the ContentVersion in Java, using a Processor instance: [source,java] ---- public class ContentProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); ContentVersion cv = new ContentVersion(); ContentWorkspace cw = getWorkspace(exchange); cv.setFirstPublishLocationId(cw.getId()); cv.setTitle(""test document""); cv.setPathOnClient(""test_doc.html""); byte[] document = message.getBody(byte[].class); ObjectMapper mapper = new ObjectMapper(); String enc = mapper.convertValue(document, String.class); cv.setVersionDataUrl(enc); message.setBody(cv); } protected ContentWorkspace getWorkSpace(Exchange exchange) { // Look up the content workspace somehow, maybe use enrich() to add it to a // header that can be extracted here .... } } ---- Give the output from the processor to the Salesforce component: [source,java] ---- from(""file:///home/camel/library"") .to(new ContentProcessor()) // convert bytes from the file into a ContentVersion SObject // for the salesforce component .to(""salesforce:createSObject""); ---- == Generating SOQL query strings `org.apache.camel.component.salesforce.api.utils.QueryHelper` contains helper methods to generate SOQL queries. For instance to fetch all custom fields from _Account_ SObject you can simply generate the SOQL SELECT by invoking: [source,java] ---- String allCustomFieldsQuery = QueryHelper.queryToFetchFilteredFieldsOf(new Account(), SObjectField::isCustom); ---- [[MavenPlugin]] == Camel Salesforce Maven Plugin The Maven plugin generates Java DTOs to represent salesforce objects. Please refer to https://github.com/apache/camel/tree/main/components/camel-salesforce/camel-salesforce-maven-plugin[README.md] for details on how to use the plugin. include::spring-boot:partial$starter.adoc[] ",16360,True,3134.6064699688013,median "--- title: 第 10 章 ISA设备驱动程序 prev: books/arch-handbook/driverbasics next: books/arch-handbook/pci showBookMenu: true weight: 12 path: ""/books/arch-handbook/"" --- [[isa-driver]] = ISA设备驱动程序 :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 10 :partnums: :source-highlighter: rouge :experimental: :images-path: books/arch-handbook/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[isa-driver-synopsis]] == 概述 本章介绍了编写ISA设备驱动程序相关的一些问题。这儿展示的伪代码 相当详细,很容易让人联想到真正的代码,不过这依然仅仅是伪代码。 它避免了与所讨论的主题无关的细节。真实的例子可以在实际驱动程序的 源代码中找到。``ep``和``aha`` 更是信息的好来源。 [[isa-driver-basics]] == 基本信息 典型的ISA驱动程序需要以下包含文件: [.programlisting] .... #include sys/module.h #include sys/bus.h #include machine/bus.h #include machine/resource.h #include sys/rman.h #include isa/isavar.h #include isa/pnpvar.h .... 它们描述了针对ISA和通用总线子系统的东西。 总线子系统是以面向对象的方式实现的,其主要结构通过相关联的 方法函数来访问。 ISA驱动程序实现的总线方法的列表与任何其他总线的很相似。 对于名字为""``xxx``""的假想驱动程序,它们将是: * `static void xxx_isa_identify (driver_t *, device_t);` 通常用于总线驱动程序而不是设备驱动程序。 但对于ISA设备,这个方法有特殊用途:如果设备提供某些设备特定的 (非PnP)方法自动侦测设备,这个例程可以实现它。 * `static int xxx_isa_probe (device_t dev);` 在已知(或PnP)位置探测设备。对于已经部分配置的 设备,这个例程也能够提供设备特定的对某些参数的自动侦测。 * `static int xxx_isa_attach (device_t dev);` 挂接和初始化设备。 * `static int xxx_isa_detach (device_t dev);` 卸载设备驱动模块前解挂设备。 * `static int xxx_isa_shutdown (device_t dev);` 系统关闭前执行设备的关闭。 * `static int xxx_isa_suspend (device_t dev);` 系统进入节能状态前挂起设备。也可以中止 切换到节能状态。 * `static int xxx_isa_resume (device_t dev);` 从节能状态返回后恢复设备的活动状态。 ``xxx_isa_probe()``和 ``xxx_isa_attach()``是必须提供的,其余例程根据设备的 需要可以有选择地实现。 使用下面一组描述符将设备驱动链接到系统。 [.programlisting] .... /* 支持的总线方法表 */ static device_method_t xxx_isa_methods[] = { /* 列出驱动程序支持的所有总线方法函数 */ /* 略去不支持的函数 */ DEVMETHOD(device_identify, xxx_isa_identify), DEVMETHOD(device_probe, xxx_isa_probe), DEVMETHOD(device_attach, xxx_isa_attach), DEVMETHOD(device_detach, xxx_isa_detach), DEVMETHOD(device_shutdown, xxx_isa_shutdown), DEVMETHOD(device_suspend, xxx_isa_suspend), DEVMETHOD(device_resume, xxx_isa_resume), { 0, 0 } }; static driver_t xxx_isa_driver = { ""xxx"", xxx_isa_methods, sizeof(struct xxx_softc), }; static devclass_t xxx_devclass; DRIVER_MODULE(xxx, isa, xxx_isa_driver, xxx_devclass, load_function, load_argument); .... 此处的结构``xxx_softc``是一个设备 特定的结构,它包含私有的驱动程序数据和驱动程序资源的描述符。 总线代码会自动按需要为每个设备分配一个softc描述符。 如果驱动程序作为可加载模块实现,当驱动程序被加载或卸载时, 会调用``load_function()``函数进行驱动程序特定的 初始化或清理工作,并将load_argument作为函数的一个参量传递进去。 如果驱动程序不支持动态加载(换句话说,它必须被链接到内核中),则 这些值应当被设置为0,最后的定义将看起来如下所示: [.programlisting] .... DRIVER_MODULE(xxx, isa, xxx_isa_driver, xxx_devclass, 0, 0); .... 如果驱动程序是为支持PnP的设备而写的,那么就必须定义一个包含 所有支持的PnP ID的表。这个表由此驱动程序所支持的PnP ID的列表 和以人可读的形式给出的、与这些ID对应的硬件类型和型号的描述 组成。看起来如下: [.programlisting] .... static struct isa_pnp_id xxx_pnp_ids[] = { /* 每个所支持的PnP ID占一行 */ { 0x12345678, ""Our device model 1234A"" }, { 0x12345679, ""Our device model 1234B"" }, { 0, NULL }, /* 表结束 */ }; .... 如果驱动程序不支持PnP设备,它仍然需要一个空的PnP ID表, 如下所示: [.programlisting] .... static struct isa_pnp_id xxx_pnp_ids[] = { { 0, NULL }, /* 表结束 */ }; .... [[isa-driver-device-t]] == Device_t指针 ``Device_t``是为设备结构而定义的指针类型, 这里我们只关心从设备驱动程序编写者的角度看感兴趣的方法。下面的方法 用来操纵设备结构中的值: * `device_t device_get_parent(dev)` 获取设备的父总线。 * `driver_t device_get_driver(dev)` 获取指向其驱动程序结构的指针。 * `char *device_get_name(dev)` 获取驱动程序的名字,在我们的 例子中为``""xxx""``。 * `int device_get_unit(dev)` 获取单元号(与每个驱动程序关联的设备从0开始编号)。 * `char *device_get_nameunit(dev)` 获取设备名,包括单元号。 例如""xxx0"",""xxx1"" 等。 * `char *device_get_desc(dev)` 获取设备描述。通常它以人可读的 形式描述设备的确切型号。 * ``device_set_desc(dev, desc)``设置描述信息。这使得设备描述指向desc字符串, 此后这个字符串就不能被解除分配。 * `device_set_desc_copy(dev, desc)` 设置描述信息。描述被拷贝到内部动态分配的 缓冲区,这样desc字符串在以后可以被改变而不会产生有害的结果。 * `void *device_get_softc(dev)` 获取指向与设备关联的设备描述符 (``xxx_softc``结构)的指针。 * `u_int32_t device_get_flags(dev)` 获取配置文件中特定于设备的 标志。 可以使用一个很方便的函数``device_printf(dev, fmt, ...)``从设备驱动程序中打印讯息。它自动在讯息前添加 单元名和冒号。 device_t的这些方法在文件[.filename]##kern/bus_subr.c## 中实现。 [[isa-driver-config]] == 配置文件与自动配置期间识别和探测的顺序 ISA设备在内核配置文件中的描述如下: [.programlisting] .... device xxx0 at isa? port 0x300 irq 10 drq 5 iomem 0xd0000 flags 0x1 sensitive .... 端口值、IRQ值和其他值被转换成与设备关联的资源值。根据设备 对自动配置需要和支持程度的不同,这些值是可选的。例如, 某些设备根本不需要读DRQ,而有些则允许设备从设备配置端口读取 IRQ设置。如果机器有多个ISA总线,可以在配置文件中明确指定哪条 总线,如``isa0``或``isa1``, 否则将在所有ISA总线上搜索设备。 ``敏感(sensitive)``是一种资源请求,它指示 必须在所有非敏感设备之前探测设备。此特性虽被支持,但似乎从未 在目前的任何驱动程序中使用过。 对于老的ISA设备,很多情况下驱动程序仍然能够侦测配置参数。 但是系统中配置的每个设备必须具有一个配置行。如果系统中装有同一 类型的两个设备,但对应的驱动程序却只有一个配置行,例如: [.programlisting] .... device xxx0 at isa? .... 那么只有一个设备会被配置。 但对于支持通过PnP或专有协议进行自动识别的设备,一个配置行 就足够配置系统中的所有设备,如上面的配置行,或者简单地: [.programlisting] .... device xxx at isa? .... 如果设备驱动程序既支持能自动识别的设备又支持老设备,并且 两类设备同时安装在一台机器上,那么只要在配置文件中描述老设备 就足够了。自动识别的设备将被自动添加。 如果ISA设备是自动配置的,发生的事件如下: 所有设备驱动程序的识别例程(包括识别所有PnP设备的PnP识别 例程)以随机顺序被调用。他们识别出设备后就把设备添加到ISA总线 上的列表中。通常驱动程序的识别例程将新设备与它们的驱动 程序关联起来。而PnP识别例程并不知道其他驱动程序,因此不能将 驱动程序与它所添加的新设备关联起来。 使用PnP协议让PnP设备进入睡眠,以防止它们被探测为老设备。 被标记为``敏感(sensitive)``的非PnP设备的 探测例程被调用。如果探测设备成功,那么就为其调用挂接(attach) 例程。 所有非PnP设备的探测和连接例程以同样的方式被调用。 PnP设备从睡眠中恢复过来,并给它们分配所请求的资源:I/O、 内存地址范围、IRQ和DRQ,所有这些与已连接的老设备不会冲突。 对于每个PnP设备,所有ISA设备驱动程序的探测例程都会被调用。 第一个要求此设备的驱动程序将被连接。多个驱动程序以不同的优先权 要求一个设备的情况是可能的,这种情况下,具有最高优先权的驱动程序 将获胜。探测例程必须调用``ISA_PNP_PROBE()``将 真实的PnP ID和驱动程序支持的ID列表作比较,如果ID不在表中则返回 失败。这意味着每个驱动程序,包括不支持任何PnP设备的驱动程序, 都必须对未知的PnP设备无条件调用 ``ISA_PNP_PROBE()``,对于未知设备, 至少要用一个 空的PnP ID表调用并返回失败。 探测例程遇到错误时会返回一个正值(错误码),成功时返回 零或负值。 负的返回值用于PnP设备支持多个接口的情况。例如,老的兼容接口 和新的高级接口通过不同的驱动程序来提供支持。两个驱动程序 都侦测设备。在探测例程中返回较高值的驱动程序优先(换句话说, 返回0的驱动程序具有最高的优先级,返回-1的其次,返回-2的更在 其后,如此下去)。如果多个驱动程序返回相同的值,那么最先调用的 获胜。因此,如果驱动程序返回0,就基本能够确信它获得优先权仲裁。 设备特定的识别例程也能够将一类而不是单个驱动程序指派给设备。 就象使用PnP的情况一样,对于某一设备,会探测这一类中所有的驱动程序。 由于这个特性在任何现存的驱动程序中总均未实现,故本文档中不再予以 考虑。 由于探测老设备的时候PnP设备被禁用,它们不会被连接两次 (一次作为老设备,一次作为PnP)。但如果识别例程设备相关的, 这种情况下设备驱动程序有责任确保同一设备不会被设备驱动程序 连接两次:一次作为老的由用户配置的,一次作为自动识别的。 对于自动识别的设备(包括PnP和设备特定的)的另一个实践结论是, 不能从内核配置文件中向它们传递旗标。因此它们必须要么根本不使用 旗标,要么为所有自动识别的设备使用单元号为0的设备的旗标,或者 使用sysctl接口而不是旗标。 通过使用函数族``resource_query_*()``和 ``resource_*_value()``直接访问配置资源, 从而可以提供其他不常用的配置。它们的实现位于 [.filename]#kern/subr_bus.c#。老的IDE磁盘驱动器 [.filename]##i386/isa/wd.c##包含这样使用的例子。 但必须优先使用配置的标准方法。将解析配置资源这类事情留给 总线配置代码。 [[isa-driver-resources]] == 资源 用户写入到内核配置文件中的信息被作为配置资源处理,并传递到内核。 总线配置代码解析这部分信息并将其转换为结构device_t的值和与之 关联的总线资源。对于复杂情况下的配置,驱动程序可以直接使用 `resource_*` 函数访问配置资源。 然而, 通常既不需要也不推荐这样做, 因此这儿不再进一步讨论这个问题。 总线资源与每个设备相关联。通过类型和类型中的数字标识它们。 对于ISA总线,定义了下面的类型: * _SYS_RES_IRQ_ - 中断号 * _SYS_RES_DRQ_ - ISA DMA通道号 * _SYS_RES_MEMORY_ - 映射到系统内存空间 的设备内存的范围 * _SYS_RES_IOPORT_ - 设备I/O寄存器的范围 类型内的枚举从0开始,因此如果设备有两个内存区域,它的 `SYS_RES_MEMORY` 类型的资源编号为0和1。 资源类型与C语言的类型无关, 所有资源值具有C语言 `unsigned long` 类型,并且必要时必须进行类型强制转换 (cast)。资源号不必连续, 尽管对于ISA它们一般是连续的。ISA设备允许的资源编号为: [.programlisting] .... IRQ: 0-1 DRQ: 0-1 MEMORY: 0-3 IOPORT: 0-7 .... 所有资源被表示为带有起始值和计数的范围。对于IRQ和DRQ资源, 计数一般等于1。内存的值引用物理地址。 对资源能够执行三种类型的动作: * set/get * allocate/release * activate/deactivate Set设置资源使用的范围。Allocation保留出请求的范围,使得 其它设备不能再占用(并检查此范围没有被其它设备占用)。 Activation执行必要的动作使得驱动程序可以访问资源(例如,对于 内存,它将被映射到内核的虚拟地址空间)。 操作资源的函数有: * `int bus_set_resource(device_t dev, int type, int rid, u_long start, u_long count)` + 为资源设置范围。成功则返回0,否则返回错误码。 一般此函数只有在``type``, ``rid``,``start``或 ``count``之一的值超出了允许的范围才会 返回错误。 ** dev - 驱动程序的设备 ** type - 资源类型,SYS_RES_* ** rid - 类型内部的资源号(ID) ** start, count - 资源范围 * `int bus_get_resource(device_t dev, int type, int rid, u_long *startp, u_long *countp)` + 取得资源范围。成功则返回0,如果资源尚未定义则返回错误码。 * `u_long bus_get_resource_start(device_t dev, int type, int rid) u_long bus_get_resource_count (device_t dev, int type, int rid)` + 便捷函数,只用来获取start或count。出错的情况下返回0, 因此如果0是资源的start合法值之一,将无法区分返回 的0是否指示错误。幸运的是,对于附加驱动程序,没有ISA资源的 start值从0开始。 * `void bus_delete_resource(device_t dev, int type, int rid)` + 删除资源,令其未定义。 * `struct resource * bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end, u_long count, u_int flags)` + 在start和end之间没有被其它设备占用的地方按count值 的范围分配一个资源。不过,不支持对齐。如果资源尚未被设置, 则自动创建它。start为0,end为~0(全1)的这对特殊值 意味着必须使用以前通过 ``bus_set_resource()``设置的固定值: start和count就是它们自己,end=(start+count),这种情况下, 如果以前资源没有定义,则返回错误。尽管rid通过引用传递, 但它并不被ISA总线的资源分配代码设置(其它总线可能使用不同的 方法并可能修改它)。 旗标是一个位映射,调用者感兴趣的有: * _RF_ACTIVE_ - 使得资源分配后 被自动激活。 * _RF_SHAREABLE_ - 资源可以同时 被多个驱动程序共享。 * _RF_TIMESHARE_ - 资源可以被多个驱动 程序分时共享,也就是说,被多个驱动程序同时分配,但任何 给定时间只能被其中一个激活。 * 出错返回0。被分配的值可以使用 ``rhand_*()``从返回的句柄获得。 * `int bus_release_resource(device_t dev, int type, int rid, struct resource *r)` * 释放资源,r为``bus_alloc_resource()`` 返回的句柄。成功则返回0,否则返回错误码。 * `int bus_activate_resource(device_t dev, int type, int rid, struct resource *r) int bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)` * 激活或禁用资源。成功则返回0,否则返回错误码。如果 资源被分时共享且当前被另一驱动程序激活,则返回 `EBUSY`。 * `int bus_setup_intr(device_t dev, struct resource *r, int flags, driver_intr_t *handler, void *arg, void **cookiep) int bus_teardown_intr(device_t dev, struct resource *r, void *cookie)` * 关联/分离中断处理程序与设备。成功则返回0,否则 返回错误码。 * r - 被激活的描述IRQ的资源句柄。 + flags - 中断优先级,如下之一: ** `INTR_TYPE_TTY` - 终端和其它 类似的字符类型设备。使用 ``spltty()``屏蔽它们。 ** `(INTR_TYPE_TTY | INTR_TYPE_FAST)` - 输入缓冲较小的终端类型 设备,而且输入上的数据丢失很关键(例如老式串口)。 使用``spltty()``屏蔽它们。 ** `INTR_TYPE_BIO` - 块类型设备, 不包括CAM控制器上的。使用 ``splbio()``屏蔽它们。 ** `INTR_TYPE_CAM` - CAM (通用访问 方法Common Access Method)总线控制器。使用 ``splcam()``屏蔽它们。 ** `INTR_TYPE_NET` - 网络接口 控制器。使用 ``splimp()``屏蔽它们。 ** `INTR_TYPE_MISC` - 各种其它设备。除了通过 ``splhigh()``没有其它方法屏蔽它们。 ``splhigh()``屏蔽所有中断。 当中断处理程序执行时,匹配其优先级的所有其它中断都被屏蔽, 唯一的例外是MISC级别,它不会屏蔽其它中断,也不会被其它中断 屏蔽。 * _handler_ - 指向处理程序的指针, 类型driver_intr_t被定义为``void driver_intr_t(void *)`` * _arg_ - 传递给处理程序的参量,标识 特定设备。由处理程序将它从void*转换为任何实际类型。ISA 中断处理程序的旧约定是使用单元号作为参量,新约定(推荐) 使用指向设备softc结构的指针。 * _cookie[p]_ - 从 ``setup()``接收的值,当传递给 ``teardown()`` 时用于标识处理程序。 定义了若干方法来操作资源句柄(struct resource *)。设备驱动 程序编写者感兴趣的有: * `u_long rman_get_start(r) u_long rman_get_end(r)` 取得被分配的资源范围的起始和结束。 * `void *rman_get_virtual(r)` 取得 被激活的内存资源的虚地址。 [[isa-driver-busmem]] == 总线内存映射 很多情况下设备驱动程序和设备之间的数据交换是通过内存 进行的。有两种可能的变体: (a) 内存位于设备卡上 (b) 内存为计算机的主内存 情况(a)中,驱动程序可能需要在卡上的内存与主存之间来回 拷贝数据。为了将卡上的内存映射到内核的虚地址空间,卡上内存的 物理地址和长度必须被定义为``SYS_RES_MEMORY``资源。 然后资源就可以被分配并激活,它的虚地址通过使用 ``rman_get_virtual()``获取。较老的驱动程序 将函数``pmap_mapdev()``用于此目的,现在 不应当再直接使用此函数。它已成为资源激活的一个内部步骤。 大多数ISA卡的内存配置为物理地位于640KB-1MB范围之间的 某个位置。某些ISA卡需要更大的内存范围,位于16M以下的某个 位置(由于ISA总线上24位地址限制)。这种情况下,如果机器有 比设备内存的起始地址更多的内存(换句话说,它们重叠),则 必须在被设备使用的内存起始地址处配置一个内存空洞。许多 BIOS允许在起始于14MB或15MB处配置1M的内存空洞。如果BIOS 正确地报告内存空洞,FreeBSD就能够正确处理它们(此特性 在老BIOS上可能会出问题)。 情况(b)中,只是数据的地址被发送到设备,设备使用DMA实际 访问主存中的数据。存在两个限制:首先,ISA卡只能访问16MB以下 的内存。其次,虚地址空间中连续的页面在物理地址空间中可能不 连续,设备可能不得不进行分散/收集操作。总线子系统为这些问题 提供现成现成的解决办法,剩下的必须由驱动程序自己完成。 DMA内存分配使用了两个结构, ``bus_dma_tag_t`` 和 ``bus_dmamap_t``。 标签(tag)描述了DMA内存要求的特性。映射(map)表示按照这些 特性分配的内存块。多个映射可以与同一标签关联。 标签按照对特性的继承而被组织成树型层次结构。子标签继承父 标签的所有要求,可以令其更严格,但不允许放宽要求。 一般地,每个设备单元创建一个顶层标签(没有父标签)。如果 每个设备需要不同要求的内存区,则为每个内存区都会创建一个标签,这些 标签作为父标签的孩子。 使用标签创建映射的方法有两种。 其一,分配一大块符合标签要求的连续内存(以后可以被释放)。 这一般用于分配为了与设备通信而存在相对较长时间的那些内存区。 将这样的内存加载到映射中非常容易:它总是被看作位于适当物理 内存范围的一整块。 其二,将虚拟内存中的任意区域加载到映射中。这片内存的 每一页都被检查,看是否符合映射的要求。如何符合则留在原始位置。 如果不符合则分配一个新的符合要求的 ""反弹页面(bounce page)"",用作中间存储。 当从不符合的原始页面写入数据时,数据首先被拷贝到反弹页面, 然后从反弹页面传递到设备。当读取时,数据将会从设备到反弹页面, 然后被拷贝到它们不符合的原始页面。原始和反弹页面之间的拷贝 处理被称作同步。这一般用于单次传输的基础之上:每次传输时 加载缓冲区,完成传输,卸载缓冲区。 工作在DMA内存上的函数有: * `int bus_dma_tag_create(bus_dma_tag_t parent, bus_size_t alignment, bus_size_t boundary, bus_addr_t lowaddr, bus_addr_t highaddr, bus_dma_filter_t *filter, void *filterarg, bus_size_t maxsize, int nsegments, bus_size_t maxsegsz, int flags, bus_dma_tag_t *dmat)` + 创建新标签。成功则返回0,否则返回错误码。 ** _parent_ - 父标签或者NULL, NULL用于创建顶层标签。 ** _alignment_ - 对将要分配给标签的内存区的对齐要求。""no specific alignment""时值为1。仅应用于以后的 ``bus_dmamem_alloc()``而不是 ``bus_dmamap_create()``调用。 ** _boundary_ - 物理地址边界, 分配内存时不能穿过。对于""no boundary"" 使用0。仅应用于以后的 ``bus_dmamem_alloc()``而不是 ``bus_dmamap_create()``调用。 必须为2的乘方。如果计划以非层叠DMA方式使用内存(也就是说, DMA地址由ISA DMA控制器提供而不是设备自身),则由于DMA硬件 限制,边界必须不能大于64KB (64*1024)。 ** _lowaddr, highaddr_ - 名字稍微 有些误导。这些值用于限制可用于内存分配的物理地址的允许 范围。其确切含义根据以后不同的使用而有所不同。 *** 对于``bus_dmamem_alloc()``, 从0到lowaddr-1的所有地址被视为允许,更高的地址不允许 使用。 *** 对于``bus_dmamap_create()``, 闭区间[lowaddr; highaddr]之外的所有地址被视为可访问。 范围之内的地址页面被传递给过滤函数,由它决定是否可访问。 如果没有提供过滤函数,则整个区间被视为不可访问。 *** 对于ISA设备,正常值(没有过滤函数)为: + lowaddr = BUS_SPACE_MAXADDR_24BIT + highaddr = BUS_SPACE_MAXADDR ** _filter, filterarg_ - 过滤函数及其 参数。如果filter为NULL,则当调用 ``bus_dmamap_create()``时,整个区间 [lowaddr, highaddr]被视为不可访问。 否则,区间[lowaddr; highaddr]内的每个被试图访问的页面的 物理地址被传递给过滤函数,由它决定是否可访问。过滤函数的 原型为:``int filterfunc(void *arg, bus_addr_t paddr)``。当页面可以被访问时它必须 返回0,否则返回非零值。 ** _maxsize_ - 通过此标签可以分配的 最大内存值(以字节计)。有时这个值很难估算,或者可以任意大, 这种情况下,对于ISA设备这个值可以设为 ``BUS_SPACE_MAXSIZE_24BIT``。 ** _nsegments_ - 设备支持的分散/收集段 的最大数目。如果不加限制,则使用应当使用值 ``BUS_SPACE_UNRESTRICTED``。 建议对父标签使用这个值,而为子孙标签指定实际限制。 nsegments值等于 ``BUS_SPACE_UNRESTRICTED`` 的标签不能用于实际加载映射,仅可以将它们作为父标签。 nsetments 的实际限制大约为250-300,再高的值将导致内核堆栈溢出(硬件 无法正常支持那么多的分散/收集缓冲区)。 ** _maxsegsz_ - 设备支持的分散/收集段 的最大尺寸。对于ISA设备的最大值为 ``BUS_SPACE_MAXSIZE_24BIT``。 ** _flags_ - 旗标的位图。感兴趣的旗标 只有: *** _BUS_DMA_ALLOCNOW_ - 创建标签时 请求分配所有可能用到的反射页面。 *** _BUS_DMA_ISA_ - 比较神秘的一个标志, 仅用于Alpha机器。i386机器没有定义它。Alpha机器的所有ISA设备 都应当使用这个标志,但似乎还没有这样的驱动程序。 ** _dmat_ - 指向返回的新标签的存储的 指针。 * `int bus_dma_tag_destroy(bus_dma_tag_t dmat)` + 销毁标签。成功则返回0,否则返回错误码。 + dmat - 被销毁的标签。 * `int bus_dmamem_alloc(bus_dma_tag_t dmat, void** vaddr, int flags, bus_dmamap_t *mapp)` + 分配标签所描述的一块连续内存区。被分配的内存的大小为标签的 maxsize。成功则返回0,否则返回错误码。调用结果被用于获取内存的 物理地址,但在此之前必须用``bus_dmamap_load()`` 将其加载。 ** _dmat_ - 标签 ** _vaddr_ - 指向存储的指针,该存储空间 用于返回的分配区域的内核虚地址。 ** flags - 旗标的位图。唯一感兴趣的旗标为: *** _BUS_DMA_NOWAIT_ - 如果内存不能 立即可用则返回错误。如果此标志没有设置,则允许例程 睡眠,直到内存可用为止。 ** _mapp_ - 指向返回的新映射的存储的指针。 * `void bus_dmamem_free(bus_dma_tag_t dmat, void *vaddr, bus_dmamap_t map)` + 释放由``bus_dmamem_alloc()``分配的内存。 目前,对分配的带有ISA限制的内存的释放没有实现。因此,建议的 使用模型为尽可能长时间地保持和重用分配的区域。不要轻易地 释放某些区域,然后再短时间地分配它。这并不意味着不应当使用 ``bus_dmamem_free()``:希望很快它就会被 完整地实现。 ** _dmat_ - 标签 ** _vaddr_ - 内存的内核虚地址 ** _map_ - 内存的映射(跟 ``bus_dmamem_alloc()``返回的一样) * ``int bus_dmamap_create(bus_dma_tag_t dmat, int flags, bus_dmamap_t *mapp)`` + 为标签创建映射,以后用于 ``bus_dmamap_load()``。成功则返回0,否则 返回错误码。 ** _dmat_ - 标签 ** _flags_ - 理论上是旗标的位图。但还 从未定义过任何旗标,因此目前总是0。 ** _mapp_ - 指向返回的新映射的存储的指针。 * ``int bus_dmamap_destroy(bus_dma_tag_t dmat, bus_dmamap_t map)`` + 销毁映射。成功则返回0,否则返回错误码。 ** dmat - 与映射关联的标签 ** map - 将要被销毁的映射 * ``int bus_dmamap_load(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf, bus_size_t buflen, bus_dmamap_callback_t *callback, void *callback_arg, int flags)`` + 加载缓冲区到映射中(映射必须事先由 ``bus_dmamap_create()``或者 ``bus_dmamem_alloc()``)创建。缓冲区的所有 页面都会被检查,看是否符合标签的要求,并为那些不符合的分配 反弹页面。会创建物理段描述符的数组,并将其传递给回调函数。 回调函数以某种方式处理这个数组。系统中的反弹缓冲区是受限的, 因此如果需要的反弹缓冲区不能立即获得,则将请求入队,当反弹 缓冲区可用时再调用回调函数。如果回调函数立即执行则返回0, 如果请求被排队,等待将来执行,则返回 ``EINPROGRESS``。后一种情况下, 与排队的回调函数之间的同步由驱动程序负责。 + ** _dmat_ - 标签 ** _map_ - 映射 ** _buf_ - 缓冲区的内核虚地址 ** _buflen_ - 缓冲区的长度 ** _callback_,``callback_arg`` - 回调函数及其参数 + 回调函数的原型为: + `void callback(void *arg, bus_dma_segment_t *seg, int nseg, int error)` + ** _arg_ - 与传递给 ``bus_dmamap_load()``的callback_arg 相同。 ** _seg_ - 段描述符的数组 ** _nseg_ - 数组中的描述符个数 ** _error_ - 表示段数目溢出:如被设为 `EFBIG`, 则标签允许的最大数目的段无法容纳缓冲区。 这种情况下数组中的描述符的数目只有标签许可的那么多。 对这种情况的处理由驱动程序决定:根据希望的语义,驱动 程序可以视其为错误,或将缓冲区分为两个并单独处理第二个。 + 段数组中的每一项包含如下字段: + ** _ds_addr_ - 段物理地址 ** _ds_len_ - 段长度 + * `void bus_dmamap_unload(bus_dma_tag_t dmat, bus_dmamap_t map)` + unload the map. + ** _dmat_ - 标签 ** _map_ - 已加载的映射 + * `void bus_dmamap_sync (bus_dma_tag_t dmat, bus_dmamap_t map, bus_dmasync_op_t op)` + 与设备进行物理传输前后,将加载的缓冲区与其反弹页面进行同步。 此函数完成原始缓冲区与其映射版本之间所有必需的数据拷贝工作。 进行传输之前和之后必须对缓冲区进行同步。 + ** _dmat_ - 标签 ** _map_ - 已加载的映射 ** _op_ - 要执行的同步操作的类型: + ** `BUS_DMASYNC_PREREAD` - 从设备到 缓冲区的读操作之前 ** `BUS_DMASYNC_POSTREAD` - 从设备到 缓冲区的读操作之后 ** `BUS_DMASYNC_PREWRITE` - 从缓冲区到 设备的写操作之前 ** `BUS_DMASYNC_POSTWRITE` - 从缓冲区到 设备的写操作之后 当前PREREAD和POSTWRITE为空操作,但将来可能会改变,因此驱动程序 中不能忽略它们。由``bus_dmamem_alloc()`` 获得的内存不需要同步。 从``bus_dmamap_load()``中调用回调函数之前, 段数组是存储在栈中的。并且是按标签允许的最大数目的段预先分配 好的。这样由于i386体系结构上对段数目的实际限制约为250-300 (内核栈为4KB减去用户结构的大小,段数组条目的大小为8字节,和 其它必须留出来的空间)。由于数组基于最大数目而分配,因此这个值 必须不能设置成超出实际需要。幸运的是,对于大多数硬件而言, 所支持的段的最大数目低很多。但如果驱动程序想处理具有非常多 分散/收集段的缓冲区,则应当一部分一部分地处理:加载缓冲区的 一部分,传输到设备,然后加载缓冲区的下一部分,如此反复。 另一个实践结论是段数目可能限制缓冲区的大小。如果缓冲区中的 所有页面碰巧物理上不连续,则分片情况下支持的最大缓冲区尺寸 为(nsegments * page_size)。例如,如果支持的段的最大数目为10, 则在i386上可以确保支持的最大缓冲区大小为40K。如果希望更大的 则需要在驱动程序中使用一些特殊技巧。 如果硬件根本不支持分散/收集,或者驱动程序希望即使在严重分片的 情况下仍然支持某种缓冲区大小,则解决办法是:如果无法容纳下原始 缓冲区,就在驱动程序中分配一个连续的缓冲区作为中间存储。 下面是当使用映射时的典型调用顺序,根据对映射的具体使用而不同。 字符-用于显示时间流。 对于从连接到分离设备,这期间位置一直不变的缓冲区: bus_dmamem_alloc - bus_dmamap_load - ...use buffer... - - bus_dmamap_unload - bus_dmamem_free 对于从驱动程序外部传递进去,并且经常变化的缓冲区: [.programlisting] .... bus_dmamap_create - - bus_dmamap_load - bus_dmamap_sync(PRE...) - do transfer - - bus_dmamap_sync(POST...) - bus_dmamap_unload - ... - bus_dmamap_load - bus_dmamap_sync(PRE...) - do transfer - - bus_dmamap_sync(POST...) - bus_dmamap_unload - - bus_dmamap_destroy .... 当加载由``bus_dmamem_alloc()``创建的映射时,传递 进去的缓冲区的地址和大小必须和 ``bus_dmamem_alloc()``中使用的一样。这种情况下就 可以保证整个缓冲区被作为一个段而映射(因而回调可以基于此假设), 并且请求被立即执行(永远不会返回EINPROGRESS)。这种情况下回调函数 需要作的只是保存物理地址。 典型示例如下: [.programlisting] .... static void alloc_callback(void *arg, bus_dma_segment_t *seg, int nseg, int error) { *(bus_addr_t *)arg = seg[0].ds_addr; } ... int error; struct somedata { .... }; struct somedata *vsomedata; /* 虚地址 */ bus_addr_t psomedata; /* 物理总线相关的地址 */ bus_dma_tag_t tag_somedata; bus_dmamap_t map_somedata; ... error=bus_dma_tag_create(parent_tag, alignment, boundary, lowaddr, highaddr, /*filter*/ NULL, /*filterarg*/ NULL, /*maxsize*/ sizeof(struct somedata), /*nsegments*/ 1, /*maxsegsz*/ sizeof(struct somedata), /*flags*/ 0, ); if(error) return error; error = bus_dmamem_alloc(tag_somedata, , /* flags*/ 0, ); if(error) return error; bus_dmamap_load(tag_somedata, map_somedata, (void *)vsomedata, sizeof (struct somedata), alloc_callback, (void *) , /*flags*/0); .... 代码看起来有点长,也比较复杂,但那是正确的使用方法。实际结果是: 如果分配多个内存区域,则总将它们组合成一个结构并作为整体分配 (如果对齐和边界限制允许的话)是一个很好的主意。 当加载任意缓冲区到由``bus_dmamap_create()`` 创建的映射时,由于回调可能被延迟,因此必须采取特殊措施与回调 函数进行同步。代码看起来像下面的样子: [.programlisting] .... { int s; int error; s = splsoftvm(); error = bus_dmamap_load( dmat, dmamap, buffer_ptr, buffer_len, callback, /*callback_arg*/ buffer_descriptor, /*flags*/0); if (error == EINPROGRESS) { /* * 执行必要的操作以确保与回调的同步。 * 回调被确保直到我们执行了splx()或tsleep()才会被调用。 */ } splx(s); } .... 处理请求的两种方法分别是: . 如果通过显式地标记请求已经结束来完成请求(例如CAM请求),则 将所有进一步的处理放入回调驱动程序中会比较简单,回调结束后会 标记请求。之后不需要太多额外的同步。由于流控制的原因,冻结请求 队列直到请求完成才释放可能是个好主意。 . 如果请求是在函数返回时完成(例如字符设备上传统的读写请求), 则需要在缓冲区描述符上设置同步标志,并调用 `tsleep()`。后面当回调函数被调用时,它将 执行处理并检查同步标志。如果设置了同步标志,它应该发出一个 唤醒操作。在这种方法中,回调函数或者进行所由必需的处理(就像 前面的情况),或者简单在缓冲区描述符中存储段数组。回调完成 后,回调函数就能使用这个存储的段数组并进行所有的处理。 [[isa-driver-dma]] == DMA ISA总线中Direct Memory Access (DMA)是通过DMA控制器(实际上是它们 中的两个,但这只是无关细节)实现的。为了使以前的ISA设备简单便宜, 总线控制和地址产生的逻辑都集中在DMA控制器中。幸运的是,FreeBSD 提供了一套函数,这些函数大多把DMA控制器的繁琐细节对设备驱动程序 隐藏了起来。 最简单情况是那些比较智能的设备。就象PCI上的总线主设备一样, 它们自己能产生总线周期和内存地址。它们真正从DMA控制器需要的 唯一事情是总线仲裁。所以为了此目的,它们假装是级联从DMA控制器。 当连接驱动程序时,系统DMA控制器需要做的唯一事情就是通过调用 如下函数在一个DMA通道上激活级联模式。 `void isa_dmacascade(int channel_number)` 所有进一步的活动通过对设备编程完成。当卸载驱动程序时,不需要 调用DMA相关的函数。 对于较简单的设备,事情反而变得复杂。使用的函数包括: * `int isa_dma_acquire(int chanel_number)` + 保留一个DMA通道。成功则返回0,如果通道已经被保留或被其它 驱动程序保留则返回EBUSY。大多数的ISA设备都不能共享DMA通道, 因此这个函数通常在连接设备时调用。总线资源的现代接口使得 这种保留成为多余,但目前仍必须使用。如果不使用,则后面其它 DMA例程将会panic。 * `int isa_dma_release(int chanel_number)` + 释放先前保留的DMA通道。释放通道时必须不能有正在进行中的 传输(另外,释放通道后设备必须不能再试图发起传输)。 * `void isa_dmainit(int chan, u_int bouncebufsize)` + 分配由特定通道使用的反弹缓冲区。请求的缓冲区大小不能超过 64KB。以后,如果传输缓冲区碰巧不是物理连续的,或超出ISA 总线可访问的内存范围,或跨越64KB的边界,则会自动使用反弹 缓冲区。如果传输总是使用符合上述条件的缓冲区(例如,由 ``bus_dmamem_alloc()``分配的那些),则 不需要调用``isa_dmainit()``。但使用此函数 会让通过DMA控制器传输任意数据变得非常方便。 + ** _chan_ - 通道号 ** _bouncebufsize_ - 以字节计数的反弹 缓冲区的大小 + * `void isa_dmastart(int flags, caddr_t addr, u_int nbytes, int chan)` + 准备启动DMA传输。实际启动设备上的传输之前必需调用此函数 来设置DMA控制器。它检查缓冲区是否连续的且在ISA内存范围 之内,如果不是则自动使用反弹缓冲区。如果需要反弹缓冲区, 但反弹缓冲区没有用``isa_dmainit()`` 设置,或对于请求的传输大小来说太小,则系统将panic。 写请求且使用反弹缓冲区的情况下,数据将被自动拷贝到反弹 缓冲区。 * flags - 位掩码,决定将要完成的操作的类型。方向位B_READ和 B_WRITE互斥。 + ** B_READ - 从ISA总线读到内存 ** B_WRITE - 从内存写到ISA总线上 ** B_RAW - 如果设置则DMA控制器将会记住缓冲区,并在传输结束后 自动重新初始化它自己,再次重复传输同一缓冲区(当然,驱动 程序可能发起设备的另一个传输之前改变缓冲区中的数据)。 如果没有设置,参数只对一次传输有效,在发起下一次传输之前 必须再次调用``isa_dmastart()``。只有在不 使用反弹缓冲区时使用B_RAW才有意义。 + * addr - 缓冲区的虚地址 * nbytes - 缓冲区长度。必须小于等于64KB。不允许长度为0:因为 DMA控制器将会理解为64KB,而内核代码把它理解为0,那样就会导致 不可预测的效果。对于通道号等于和高于4的情况,长度必需为偶数, 因为这些通道每次传输2字节。奇数长度情况下,最后一个字节不被 传输。 * chan - 通道号 * `void isa_dmadone(int flags, caddr_t addr, int nbytes, int chan)` + 设备报告传输完成后,同步内存。如果是使用反弹缓冲区的读操作, 则将数据从反弹缓冲区拷贝到原始缓冲区。参量与 ``isa_dmastart()``的相同。允许使用B_RAW标志, 但它一点也不会影响``isa_dmadone()``。 * `int isa_dmastatus(int channel_number)` + 返回当前传输中剩余的字节数。在 ``isa_dmastart()``中设置了B_READ的情况下, 返回的数字一定不会等于零。传输结束时它会被自动复位到缓冲区的 长度。正式的用法是在设备发信号指示传输已完成时检查剩余的字节数。 如果字节数不为0,则此次传输可能有问题。 * `int isa_dmastop(int channel_number)` + 放弃当前的传输并返回剩余未传输的字节数。 [[isa-driver-probe]] == xxx_isa_probe 这个函数探测设备是否存在。如果驱动程序支持自动侦测设备配置的 某些部分(如中断向量或内存地址),则自动侦测必须在此例程中完成。 对于任意其他总线,如果不能侦测到设备,或者侦测到但自检失败, 或者发生某些其他问题,则应当返回一个正值的错误。如果设备不 存在则必须返回值 `ENXIO`。 其他错误值可能表示其他条件。零或负值 意味着成功。大多数驱动程序返回零表示成功。 当PnP设备支持多个接口时使用负返回值。例如,不同驱动程序支持 老的兼容接口和较新的高级接口。则两个驱动程序都将侦测设备。 在探测例程中返回较高值的驱动程序获得优先(换句话说,返回0的 驱动程序具有最高的优先级,返回-1的其次,返回-2的更后,等等)。 这样,仅支持老接口的设备将被老驱动程序处理(其应当从探测例程中 返回-1),而同时也支持新接口的设备将由新驱动程序处理(其应当从 探测例程中返回0)。 设备描述符结构xxx_softc由系统在调用探测例程之前分配。如果 探测例程返回错误,描述符会被系统自动取消分配。因此如果出现 探测错误,驱动程序必须保证取消分配探测期间它使用的所有资源, 且确保没有什么能够阻止描述符被安全地取消分配。如果探测成功 完成,描述符将由系统保存并在以后传递给例程 `xxx_isa_attach()`。如果驱动程序返回负值, 就不能保证它将获得最高优先权且其连接例程会被调用。因此这种 情况下它也必须在返回前释放所有的资源,并在需要的时候在连接 例程中重新分配它们。当``xxx_isa_probe()`` 返回0时,在返回前释放资源也是一个好主意,而且中规中矩的驱动 程序应当这样做。但在释放资源会存在某些问题的情况下,允许驱动 程序在从探测例程返回0和连接例程的执行之间保持资源。 典型的探测例程以取得设备描述符和单元号开始: [.programlisting] .... struct xxx_softc *sc = device_get_softc(dev); int unit = device_get_unit(dev); int pnperror; int error = 0; sc-dev = dev; /* 链接回来 */ sc-unit = unit; .... 然后检查PnP设备。检查是通过一个包含PnP ID列表的表进行的。此表 包含这个驱动程序支持的PnP ID和以人工可读形式给出的对应这些ID的 设备型号的描述。 [.programlisting] .... pnperror=ISA_PNP_PROBE(device_get_parent(dev), dev, xxx_pnp_ids); if(pnperror == ENXIO) return ENXIO; .... ISA_PNP_PROBE的逻辑如下:如果卡(设备单元)没有被作为PnP侦测到, 则返回ENOENT。如果被作为PnP侦测到,但侦测到的ID不匹配表中的 任一ID,则返回ENXIO。最后,如果设备能支持PnP且匹配表中的一个 ID,则返回0,并且由``device_set_desc()``从 表中取得适当的描述进行设置。 如果设备驱动程序仅支持PnP设备,则情况看起来如下: [.programlisting] .... if(pnperror != 0) return pnperror; .... 对于不支持PnP的驱动程序不需要特殊处理,因为驱动程序会传递空的 PnP ID表,且如果在PnP卡上调用会得到ENXIO。 探测例程通常至少需要某些最少量的资源,如I/O端口号,来发现并探测卡。 对于不同的硬件,驱动程序可能会自动发现其他必需的资源。PnP设备的 所有资源由PnP子系统预先设置,因此驱动程序不需要自己发现它们。 通常访问设备所需要的最少信息就是端口号。然后某些设备允许从设备 配置寄存器中取得其余信息(尽管不是所有的设备都这样)。因此首先 我们尝试取得端口起始值: [.programlisting] .... sc-port0 = bus_get_resource_start(dev, SYS_RES_IOPORT, 0 /*rid*/); if(sc-port0 == 0) return ENXIO; .... 基端口地址被保存在softc结构中,以便将来使用。如果需要经常使用 端口,则每次都调用资源函数将会慢的无法忍受。如果我们没有得到 端口,则返回错误即可。相反,一些设备驱动程序相当聪明,尝试探测 所有可能的端口,如下: [.programlisting] .... /* 此设备所有可能的基I/O端口地址表 */ static struct xxx_allports { u_short port; /* 端口地址 */ short used; /* 旗标:此端口是否已被其他单元使用 */ } xxx_allports = { { 0x300, 0 }, { 0x320, 0 }, { 0x340, 0 }, { 0, 0 } /* 表结束 */ }; ... int port, i; ... port = bus_get_resource_start(dev, SYS_RES_IOPORT, 0 /*rid*/); if(port !=0 ) { for(i=0; xxx_allports[i].port!=0; i++) { if(xxx_allports[i].used || xxx_allports[i].port != port) continue; /* 找到了 */ xxx_allports[i].used = 1; /* 在已知端口上探测 */ return xxx_really_probe(dev, port); } return ENXIO; /* 端口无法识别或已经被使用 */ } /* 仅在需要猜测端口的时候才会到达这儿 */ for(i=0; xxx_allports[i].port!=0; i++) { if(xxx_allports[i].used) continue; /* 标记为已被使用 - 即使我们在此端口什么也没有发现 * 至少我们以后不会再次探测 */ xxx_allports[i].used = 1; error = xxx_really_probe(dev, xxx_allports[i].port); if(error == 0) /* 在那个端口找到一个设备 */ return 0; } /* 探测过所有可能的地址,但没有可用的 */ return ENXIO; .... 当然,做这些事情通常应该使用驱动程序的 ``identify()``例程。但可能有一个正当的理由来 说明为什么在函数``probe()``中完成更好:如果 这种探测会让一些其他敏感设备发疯。探测例程按旗标 ``sensitive``排序:敏感设备首先被探测,然后是 其他设备。但``identify()``例程在所有探测之前 被调用,因此它们不会考虑敏感设备并可能扰乱这些设备。 现在,我们得到起始端口以后就需要设置端口数(PnP设备除外),因为 内核在配置文件中没有这个信息。 [.programlisting] .... if(pnperror /* 只对非PnP设备 */ bus_set_resource(dev, SYS_RES_IOPORT, 0, sc-port0, XXX_PORT_COUNT)0) return ENXIO; .... 最后分配并激活一片端口地址空间(特殊值start和end意思是说 ""使用我们通过``bus_set_resource()`` 设置的那些值""): [.programlisting] .... sc-port0_rid = 0; sc-port0_r = bus_alloc_resource(dev, SYS_RES_IOPORT, port0_rid, /*start*/ 0, /*end*/ ~0, /*count*/ 0, RF_ACTIVE); if(sc-port0_r == NULL) return ENXIO; .... 现在可以访问端口映射的寄存器后,我们就可以以某种方式向设备写入 数据并检查设备是否如我们期望的那样作出反应。如果没有,则说明 可能其他的设备在这个地址上,或者这个地址上根本没有设备。 通常驱动程序直到连接例程才会设置中断处理函数。这之前我们替代以 轮询模式进行探测,超时则以``DELAY()``实现。 探测例程必须确保不能永久挂起,设备上的所有等待必须在超时内完成。 如果设备不在这段时间内响应,则可能设备出故障或配置错误,驱动程序 必须返回错误,当确定超时间隔时,给设备一些额外时间以确保可靠: 尽管假定``DELAY()``在任何机器上都延时相同数量的 时间,但随具体CPU的不同,此函数还是有一定的误差幅度。 如果探测例程真的想检查中断是否真的工作,它可以也配置和探测中断。 但不建议这样。 [.programlisting] .... /* 以严重依赖于具体设备的方式实现 */ if(error = xxx_probe_ports(sc)) goto bad; /* 返回前释放资源 */ .... 依赖于所发现设备的确切型号,函数 ``xxx_probe_ports()``也可能设置设备描述。但 如果只支持一种设备型号,则也可以硬编码的形式完成。当然,对于 PnP设备,PnP支持从表中自动设置描述。 [.programlisting] .... if(pnperror) device_set_desc(dev, ""Our device model 1234""); .... 探测例程应当或者通过读取设备配置寄存器来发现所有资源的范围, 或者确保由用户显式设置。我们将假定一个带板上内存的例子。 探测例程应当尽可能是非插入式的,这样分配和检查其余资源功能性 的工作就可以更好地留给连接例程来做。 内存地址可以在内核配置文件中指定,或者对应某些设备可以在非易失性 配置寄存器中预先配置。如果两种做法均可用却不同,那么应当用 哪个呢?可能用户厌烦在内核配置文件中明确设置地址,但他们知道 自己在干什么,则应当优先使用这个。一个实现的例子可能是这样的: [.programlisting] .... /* 首先试图找出配置地址 */ sc-mem0_p = bus_get_resource_start(dev, SYS_RES_MEMORY, 0 /*rid*/); if(sc-mem0_p == 0) { /* 没有,用户没指定 */ sc-mem0_p = xxx_read_mem0_from_device_config(sc); if(sc-mem0_p == 0) /* 从设备配置寄存器也到不了这儿 */ goto bad; } else { if(xxx_set_mem0_address_on_device(sc) 0) goto bad; /* 设备不支持那地址 */ } /* 就像端口,设置内存大小, * 对于某些设备,内存大小不是常数, * 而应当从设备配置寄存器中读取,以适应设备的不同型号 * 另一个选择是让用户把内存大小设置为“msize”配置资源, * 由ISA总线自动处理 */ if(pnperror) { /*仅对非PnP设备 */ sc-mem0_size = bus_get_resource_count(dev, SYS_RES_MEMORY, 0 /*rid*/); if(sc-mem0_size == 0) /* 用户没有指定 */ sc-mem0_size = xxx_read_mem0_size_from_device_config(sc); if(sc-mem0_size == 0) { /* 假定这是设备非常老的一种型号,没有自动配置特性, * 用户也没有偏好设置,因此假定最低要求的情况 * (当然,真实值将根据设备驱动程序而不同) */ sc-mem0_size = 8*1024; } if(xxx_set_mem0_size_on_device(sc) 0) goto bad; /*设备不支持那个大小 */ if(bus_set_resource(dev, SYS_RES_MEMORY, /*rid*/0, sc-mem0_p, sc-mem0_size)0) goto bad; } else { sc-mem0_size = bus_get_resource_count(dev, SYS_RES_MEMORY, 0 /*rid*/); } .... 类似, 很容易检查IRQ和DRQ所用的资源。 如果一切进行正常,然后就可以释放所有资源并返回成功。 [.programlisting] .... xxx_free_resources(sc); return 0; .... 最后,处理棘手情况。所有资源应当在返回前被释放。我们利用这样一个 事实:softc结构在传递给我们以前被零化,因此我们能够找出是否分配了 某些资源:如果分配则这些资源的描述符非零。 [.programlisting] .... bad: xxx_free_resources(sc); if(error) return error; else /* 确切错误未知 */ return ENXIO; .... 这是完整的探测例程。资源的释放从多个地方完成,因此将它挪到一个 函数中,看起来可能像下面的样子: [.programlisting] .... static void xxx_free_resources(sc) struct xxx_softc *sc; { /* 检查每个资源,如果非0则释放 */ /* 中断处理函数 */ if(sc-intr_r) { bus_teardown_intr(sc-dev, sc-intr_r, sc-intr_cookie); bus_release_resource(sc-dev, SYS_RES_IRQ, sc-intr_rid, sc-intr_r); sc-intr_r = 0; } /* 我们分配过的所有种类的内存 */ if(sc-data_p) { bus_dmamap_unload(sc-data_tag, sc-data_map); sc-data_p = 0; } if(sc-data) { /* sc-data_map等于0有可能合法 */ /* the map will also be freed */ bus_dmamem_free(sc-data_tag, sc-data, sc-data_map); sc-data = 0; } if(sc-data_tag) { bus_dma_tag_destroy(sc-data_tag); sc-data_tag = 0; } ... 如果有,释放其他的映射和标签 ... if(sc-parent_tag) { bus_dma_tag_destroy(sc-parent_tag); sc-parent_tag = 0; } /* 释放所有总线资源 */ if(sc-mem0_r) { bus_release_resource(sc-dev, SYS_RES_MEMORY, sc-mem0_rid, sc-mem0_r); sc-mem0_r = 0; } ... if(sc-port0_r) { bus_release_resource(sc-dev, SYS_RES_IOPORT, sc-port0_rid, sc-port0_r); sc-port0_r = 0; } } .... [[isa-driver-attach]] == xxx_isa_attach 如果探测例程返回成功并且系统选择连接那个驱动程序,则连接例程 负责将驱动程序实际连接到系统。如果探测例程返回0 ,则连接例程期望 接收完整的设备结构softc,此结构由探测例程设置。同时,如果探测例程 返回0,它可能期望这个设备的连接例程应当在将来的某点被调用。如果 探测例程返回负值,则驱动程序可能不会作此假设。 如果成功完成,连接例程返回0,否则返回错误码。 连接例程的启动跟探测例程相似,将一些常用数据取到一些更容易 访问的变量中。 [.programlisting] .... struct xxx_softc *sc = device_get_softc(dev); int unit = device_get_unit(dev); int error = 0; .... 然后分配并激活所需资源。由于端口范围通常在从探测返回前就 被释放,因此需要重新分配。我们希望探测例程已经适当地设置了 所有的资源范围,并将它们保存在结构softc中。如果探测例程留下了 一些被分配的资源,就不需要再次分配(重新分配被视为错误)。 [.programlisting] .... sc-port0_rid = 0; sc-port0_r = bus_alloc_resource(dev, SYS_RES_IOPORT, port0_rid, /*start*/ 0, /*end*/ ~0, /*count*/ 0, RF_ACTIVE); if(sc-port0_r == NULL) return ENXIO; /* 板上内存 */ sc-mem0_rid = 0; sc-mem0_r = bus_alloc_resource(dev, SYS_RES_MEMORY, mem0_rid, /*start*/ 0, /*end*/ ~0, /*count*/ 0, RF_ACTIVE); if(sc-mem0_r == NULL) goto bad; /* 取得虚地址 */ sc-mem0_v = rman_get_virtual(sc-mem0_r); .... DMA请求通道(DRQ)以相似方式被分配。使用 ``isa_dma*()``函数族进行初始化。例如: `isa_dmacascade(sc-drq0);` 中断请求线(IRQ)有点特殊。除了分配以外,驱动程序的中断处理 函数也应当与它关联。在古老的ISA驱动程序中,由系统传递给中断处理 函数的参量是设备单元号。但在现代驱动程序中,按照约定,建议传递 指向结构softc的指针。一个很重要的原因在于当结构softc被动态分配后, 从softc取得单元号很容易,而从单元号取得softc很困难。同时,这个 约定也使得用于不同总线的应用程序看起来统一,并允许它们共享代码: 每个总线有其自己的探测,连接,分离和其他总线相关的例程,而它们 之间可以共享大块的驱动程序代码。 [.programlisting] .... sc-intr_rid = 0; sc-intr_r = bus_alloc_resource(dev, SYS_RES_MEMORY, intr_rid, /*start*/ 0, /*end*/ ~0, /*count*/ 0, RF_ACTIVE); if(sc-intr_r == NULL) goto bad; /* * 假定对XXX_INTR_TYPE的定义依赖于驱动程序的类型, * 例如INTR_TYPE_CAM用于CAM的驱动程序 */ error = bus_setup_intr(dev, sc-intr_r, XXX_INTR_TYPE, (driver_intr_t *) xxx_intr, (void *) sc, intr_cookie); if(error) goto bad; .... 如果驱动程序需要与内存进行DMA,则这块内存应当按前述方式分配: [.programlisting] .... error=bus_dma_tag_create(NULL, /*alignment*/ 4, /*boundary*/ 0, /*lowaddr*/ BUS_SPACE_MAXADDR_24BIT, /*highaddr*/ BUS_SPACE_MAXADDR, /*filter*/ NULL, /*filterarg*/ NULL, /*maxsize*/ BUS_SPACE_MAXSIZE_24BIT, /*nsegments*/ BUS_SPACE_UNRESTRICTED, /*maxsegsz*/ BUS_SPACE_MAXSIZE_24BIT, /*flags*/ 0, parent_tag); if(error) goto bad; /* 很多东西是从父标签继承而来 * 假设sc-data指向存储共享数据的结构,例如一个环缓冲区可能是: * struct { * u_short rd_pos; * u_short wr_pos; * char bf[XXX_RING_BUFFER_SIZE] * } *data; */ error=bus_dma_tag_create(sc-parent_tag, 1, 0, BUS_SPACE_MAXADDR, 0, /*filter*/ NULL, /*filterarg*/ NULL, /*maxsize*/ sizeof(* sc-data), /*nsegments*/ 1, /*maxsegsz*/ sizeof(* sc-data), /*flags*/ 0, data_tag); if(error) goto bad; error = bus_dmamem_alloc(sc-data_tag, data, /* flags*/ 0, data_map); if(error) goto bad; /* 在data_p的情况下,xxx_alloc_callback()只是将物理地址 * 保存到作为其参量传递进去的指针中。 * 参看关于总线内存映射一节中的详细内容。 * 其实现可以像这样: * * static void * xxx_alloc_callback(void *arg, bus_dma_segment_t *seg, * int nseg, int error) * { * *(bus_addr_t *)arg = seg[0].ds_addr; * } */ bus_dmamap_load(sc-data_tag, sc-data_map, (void *)sc-data, sizeof (* sc-data), xxx_alloc_callback, (void *) data_p, /*flags*/0); .... 分配了所有的资源后,设备应当被初始化。初始化可能包括测试 所有特性,确保它们起作用。 [.programlisting] .... if(xxx_initialize(sc) 0) goto bad; .... 总线子系统将自动在控制台上打印由探测例程设置的设备描述。但 如果驱动程序想打印一些关于设备的额外信息,也是可能的,例如: [.programlisting] .... device_printf(dev, ""has on-card FIFO buffer of %d bytes\\n"", sc-fifosize); .... 如果初始化例程遇到任何问题,建议返回错误之前打印有关信息。 连接例程的最后一步是将设备连接到内核中的功能子系统。完成 这个步骤的精确方式依赖于驱动程序的类型:字符设备、块设备、网络 设备、CAM SCSI总线设备等等。 如果所有均工作正常则返回成功。 [.programlisting] .... error = xxx_attach_subsystem(sc); if(error) goto bad; return 0; .... 最后,处理棘手情况。返回错误前,所有资源应当被取消分配。 我们利用这样一个事实:结构softc传递给我们之前被零化,因此我们 能找出是否分配了某些资源:如果分配则它们的描述符非零。 [.programlisting] .... bad: xxx_free_resources(sc); if(error) return error; else /* exact error is unknown */ return ENXIO; .... 这就是连接例程的全部。 [[isa-driver-detach]] == xxx_isa_detach 如果驱动程序中存在这个函数,且驱动程序被编译为可加载模块,则 驱动程序具有被卸载的能力。如果硬件支持热插拔,这是一个很重要的 特性。但ISA总线不支持热插拔,因此这个特性对于ISA设备不是特别 重要。卸载驱动程序的能力可能在调试时有用,但很多情况下只有在 老版本的驱动程序莫名其妙地卡住系统的情况下才需要安装新版本的 驱动程序,并且无论如何都需要重启,这样使得花费精力写分离例程 有些不值得。另一个宣称卸载允许在用于生产的机器上升级驱动程序的 论点看起来似乎更多的只是理论而已。升级驱动程序是一项危险的操作, 决不不应当在用于生产的机器上实行(并且当系统运行于安全模式时这 也是不被允许的)。然而,出于完整性考虑,还是会提供分离例程。 如果驱动程序成功分离,分离例程返回0,否则返回错误码。 分离逻辑是连接的镜像。要做的第一件事情就是将驱动程序从内核 子系统分离。如果设备当前正打开着,驱动程序有两个选择:拒绝分离 或者强制关闭并继续进行分离。选用哪种方式取决于特定内核子系统 执行强制关闭的能力和驱动程序作者的偏好。通常强制关闭似乎是 更好的选择。 [.programlisting] .... struct xxx_softc *sc = device_get_softc(dev); int error; error = xxx_detach_subsystem(sc); if(error) return error; .... 下一步,驱动程序可能希望复位硬件到某种一致的状态。包括停止任何 将要进行的传输,禁用DMA通道和中断以避免设备破坏内存。对于大多数 驱动程序而言,这正是关闭例程所做的,因此如果驱动程序中包括关闭 例程,我们只要调用它就可以了。 `xxx_isa_shutdown(dev);` 最后释放所有资源并返回成功。 [.programlisting] .... xxx_free_resources(sc); return 0; .... [[isa-driver-shutdown]] == xxx_isa_shutdown 当系统要关闭的时候调用此例程。通过它使硬件进入某种一致的状态。 对于大多数ISA设备而言不需要特殊动作,因此这个函数并非真正必需, 因为不管怎样重启动时设备会被重新初始化。但有些设备必须按特定 步骤关闭,以确保在软重启后能被正确地检测到(对于很多使用私有 识别协议的设备特别有用)。很多情况下,在设备寄存器中禁用DMA和 中断,并停止将要进行的传输是个好主意。确切动作取决于硬件,因此 我们无法在此详细讨论。 [[isa-driver-intr]] == xxx_intr 当收到来自特定设备的中断时就会调用中断处理函数。ISA总线不支持 中断共享(某些特殊情况例外),因此实际上如果中断处理函数被调用, 几乎可以确信中断是来自其设备。然而,中断处理函数必须轮询设备 寄存器并确保中断是由它的设备产生的。如果不是,中断处理函数应当 返回。 ISA驱动程序的旧约定是取设备单元号作为参量。现在已经废弃,当 调用``bus_setup_intr()``时新驱动程序接收任何 在连接例程中为他们指定的参量。根据新约定,它应当是指向结构 softc的指针。因此中断处理函数通常像下面那样开始: [.programlisting] .... static void xxx_intr(struct xxx_softc *sc) { .... 它运行在由``bus_setup_intr()``的中断类型参数指定 的中断优先级上。这意味着禁用所有其他同类型的中断和所有软件中断。 为了避免竞争,中断处理例程通写成循环形式: [.programlisting] .... while(xxx_interrupt_pending(sc)) { xxx_process_interrupt(sc); xxx_acknowledge_interrupt(sc); } .... 中断处理函数必须只向设备应答中断,但不能向中断控制器应答,后者由 系统负责处理。 ",16151,True,2875.505841289384,median "[.configuration-legend] icon:lock[title=Fixed at build time] Configuration property fixed at build time - All other configuration properties are overridable at runtime [.configuration-reference, cols=""80,.^10,.^10""] |=== h|[[quarkus-oidc-oidc-config_configuration]]link:#quarkus-oidc-oidc-config_configuration[Configuration property] h|Type h|Default a| [[quarkus-oidc-oidc-config_quarkus.oidc.auth-server-url]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.auth-server-url[quarkus.oidc.auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, `https://host:port/auth`. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: `https://host:port/auth/realms/++{++realm++}++` where `++{++realm++}++` has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.discovery-enabled]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.discovery-enabled[quarkus.oidc.discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the 'token-path' property must be configured. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.token-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token-path[quarkus.oidc.token-path]` [.description] -- Relative path of the OIDC token endpoint which issues access and refresh tokens using either 'client_credentials' or 'password' grants --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.client-id]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.client-id[quarkus.oidc.client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.connection-delay]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.connection-delay[quarkus.oidc.connection-delay]` [.description] -- The maximum amount of time connecting to the currently unavailable OIDC server will be attempted for. The number of times the connection request will be repeated is calculated by dividing the value of this property by 2. For example, setting it to `20S` will allow for requesting the connection up to 10 times with a 2 seconds delay between the retries. Note this property is only effective when the initial OIDC connection is created, for example, when requesting a well-known OIDC configuration. Use the 'connection-retry-count' property to support trying to re-establish an already available connection which may have been dropped. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-oidc-config_quarkus.oidc.connection-retry-count]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.connection-retry-count[quarkus.oidc.connection-retry-count]` [.description] -- The number of times an attempt to re-establish an already available connection will be repeated for. Note this property is different to the `connection-delay` property which is only effective during the initial OIDC connection creation. This property is used to try to recover the existing connection which may have been temporarily lost. For example, if a request to the OIDC token endpoint fails due to a connection exception then the request will be retried for a number of times configured by this property. --|int |`3` a| [[quarkus-oidc-oidc-config_quarkus.oidc.connection-timeout]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.connection-timeout[quarkus.oidc.connection-timeout]` [.description] -- The amount of time after which the current OIDC connection request will time out. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10S` a| [[quarkus-oidc-oidc-config_quarkus.oidc.max-pool-size]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.max-pool-size[quarkus.oidc.max-pool-size]` [.description] -- The maximum size of the connection pool used by the WebClient --|int | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.secret]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.secret[quarkus.oidc.credentials.secret]` [.description] -- Client secret which is used for a `client_secret_basic` authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.client-secret.value]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.client-secret.value[quarkus.oidc.credentials.client-secret.value]` [.description] -- The client secret --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.client-secret.method]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.client-secret.method[quarkus.oidc.credentials.client-secret.method]` [.description] -- Authentication method. --|`basic`, `post` | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.secret]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.secret[quarkus.oidc.credentials.jwt.secret]` [.description] -- If provided, indicates that JWT is signed using a secret key --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-file]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-file[quarkus.oidc.credentials.jwt.key-file]` [.description] -- If provided, indicates that JWT is signed using a private key in PEM or JWK format --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-store-file]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-store-file[quarkus.oidc.credentials.jwt.key-store-file]` [.description] -- If provided, indicates that JWT is signed using a private key from a key store --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-store-password]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-store-password[quarkus.oidc.credentials.jwt.key-store-password]` [.description] -- A parameter to specify the password of the key store file. If not given, the default (""password"") is used. --|string |`password` a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-id]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-id[quarkus.oidc.credentials.jwt.key-id]` [.description] -- The private key id/alias --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-password]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.key-password[quarkus.oidc.credentials.jwt.key-password]` [.description] -- The private key password --|string |`password` a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.token-key-id]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.token-key-id[quarkus.oidc.credentials.jwt.token-key-id]` [.description] -- Key identifier of the signing key added as a JWT 'kid' header --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.lifespan]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.credentials.jwt.lifespan[quarkus.oidc.credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc-oidc-config_quarkus.oidc.proxy.host]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.proxy.host[quarkus.oidc.proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.proxy.port]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.proxy.port[quarkus.oidc.proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc-oidc-config_quarkus.oidc.proxy.username]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.proxy.username[quarkus.oidc.proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.proxy.password]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.proxy.password[quarkus.oidc.proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.tls.verification]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.tls.verification[quarkus.oidc.tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. --|`required`, `none` | a| [[quarkus-oidc-oidc-config_quarkus.oidc.tenant-id]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.tenant-id[quarkus.oidc.tenant-id]` [.description] -- A unique tenant identifier. It must be set by `TenantConfigResolver` providers which resolve the tenant configuration dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.tenant-enabled]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.tenant-enabled[quarkus.oidc.tenant-enabled]` [.description] -- If this tenant configuration is enabled. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.application-type]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.application-type[quarkus.oidc.application-type]` [.description] -- The application type, which can be one of the following values from enum `ApplicationType`. --|`web-app`, `service`, `hybrid` |`service` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authorization-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authorization-path[quarkus.oidc.authorization-path]` [.description] -- Relative path of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.user-info-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.user-info-path[quarkus.oidc.user-info-path]` [.description] -- Relative path of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.introspection-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.introspection-path[quarkus.oidc.introspection-path]` [.description] -- Relative path of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.jwks-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.jwks-path[quarkus.oidc.jwks-path]` [.description] -- Relative path of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.end-session-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.end-session-path[quarkus.oidc.end-session-path]` [.description] -- Relative path of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.public-key]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.public-key[quarkus.oidc.public-key]` [.description] -- Public key for the local JWT token verification. OIDC server connection will not be created when this property is set. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.roles.role-claim-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.roles.role-claim-path[quarkus.oidc.roles.role-claim-path]` [.description] -- Path to the claim containing an array of groups. It starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: ""realm/groups"". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in a different claim. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.roles.role-claim-separator]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.roles.role-claim-separator[quarkus.oidc.roles.role-claim-separator]` [.description] -- Separator for splitting a string which may contain multiple group values. It will only be used if the ""role-claim-path"" property points to a custom claim whose value is a string. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.roles.source]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.roles.source[quarkus.oidc.roles.source]` [.description] -- Source of the principal roles. --|`idtoken`, `accesstoken`, `userinfo` | a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.issuer]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.issuer[quarkus.oidc.token.issuer]` [.description] -- Expected issuer 'iss' claim value. Note this property overrides the `issuer` property which may be set in OpenId Connect provider's well-known configuration. If the `iss` claim value varies depending on the host/IP address or tenant id of the provider then you may skip the issuer verification by setting this property to 'any' but it should be done only when other options (such as configuring the provider to use the fixed `iss` claim value) are not possible. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.audience]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.audience[quarkus.oidc.token.audience]` [.description] -- Expected audience 'aud' claim value which may be a string or an array of strings. --|list of string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.token-type]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.token-type[quarkus.oidc.token.token-type]` [.description] -- Expected token type --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.lifespan-grace]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.lifespan-grace[quarkus.oidc.token.lifespan-grace]` [.description] -- Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds. --|int | a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.principal-claim]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.principal-claim[quarkus.oidc.token.principal-claim]` [.description] -- Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and `sub` claims are checked. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.refresh-expired]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.refresh-expired[quarkus.oidc.token.refresh-expired]` [.description] -- Refresh expired ID tokens. If this property is enabled then a refresh token request will be performed if the ID token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the `authentication.session-age-extension` property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type `ApplicationType++#++WEB_APP`++}++. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.refresh-token-time-skew]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.refresh-token-time-skew[quarkus.oidc.token.refresh-token-time-skew]` [.description] -- Refresh token time skew in seconds. If this property is enabled then the configured number of seconds is added to the current time when checking whether the access token should be refreshed. If the sum is greater than this access token's expiration time then a refresh is going to happen. This property will be ignored if the 'refresh-expired' property is not enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.forced-jwk-refresh-interval]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.forced-jwk-refresh-interval[quarkus.oidc.token.forced-jwk-refresh-interval]` [.description] -- Forced JWK set refresh interval in minutes. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10M` a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.header]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.header[quarkus.oidc.token.header]` [.description] -- Custom HTTP header that contains a bearer token. This option is valid only when the application is of type `ApplicationType++#++SERVICE`++}++. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.allow-jwt-introspection]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.allow-jwt-introspection[quarkus.oidc.token.allow-jwt-introspection]` [.description] -- Allow the remote introspection of JWT tokens when no matching JWK key is available. Note this property is set to 'true' by default for backward-compatibility reasons and will be set to `false` instead in one of the next releases. Also note this property will be ignored if JWK endpoint URI is not available and introspecting the tokens is the only verification option. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.token.allow-opaque-token-introspection]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token.allow-opaque-token-introspection[quarkus.oidc.token.allow-opaque-token-introspection]` [.description] -- Allow the remote introspection of the opaque tokens. Set this property to 'false' if only JWT tokens are expected. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.logout.path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.logout.path[quarkus.oidc.logout.path]` [.description] -- The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.logout.post-logout-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.logout.post-logout-path[quarkus.oidc.logout.post-logout-path]` [.description] -- Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.redirect-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.redirect-path[quarkus.oidc.authentication.redirect-path]` [.description] -- Relative path for calculating a ""redirect_uri"" query parameter. It has to start from a forward slash and will be appended to the request URI's host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated if 'restorePathAfterRedirect' is set to 'true'. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.restore-path-after-redirect]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.restore-path-after-redirect[quarkus.oidc.authentication.restore-path-after-redirect]` [.description] -- If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. Note if `redirectPath` property is not set the the original request URI will be restored even if this property is disabled. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.remove-redirect-parameters]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.remove-redirect-parameters[quarkus.oidc.authentication.remove-redirect-parameters]` [.description] -- Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.verify-access-token]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.verify-access-token[quarkus.oidc.authentication.verify-access-token]` [.description] -- Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if `quarkus.oidc.roles.source` property is set to `accesstoken` which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.force-redirect-https-scheme]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.force-redirect-https-scheme[quarkus.oidc.authentication.force-redirect-https-scheme]` [.description] -- Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout `post_logout_redirect_uri` and the local redirect requests. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.scopes]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.scopes[quarkus.oidc.authentication.scopes]` [.description] -- List of scopes --|list of string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.cookie-force-secure]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.cookie-force-secure[quarkus.oidc.authentication.cookie-force-secure]` [.description] -- If enabled the state, session and post logout cookies will have their 'secure' parameter set to 'true' when HTTP is used. It may be necessary when running behind an SSL terminating reverse proxy. The cookies will always be secure if HTTPS is used even if this property is set to false. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.cookie-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.cookie-path[quarkus.oidc.authentication.cookie-path]` [.description] -- Cookie path parameter value which, if set, will be used to set a path parameter for the session, state and post logout cookies. The `cookie-path-header` property, if set, will be checked first. --|string |`/` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.cookie-path-header]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.cookie-path-header[quarkus.oidc.authentication.cookie-path-header]` [.description] -- Cookie path header parameter value which, if set, identifies the incoming HTTP header whose value will be used to set a path parameter for the session, state and post logout cookies. If the header is missing then the `cookie-path` property will be checked. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.cookie-domain]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.cookie-domain[quarkus.oidc.authentication.cookie-domain]` [.description] -- Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.user-info-required]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.user-info-required[quarkus.oidc.authentication.user-info-required]` [.description] -- If this property is set to 'true' then an OIDC UserInfo endpoint will be called --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.session-age-extension]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.session-age-extension[quarkus.oidc.authentication.session-age-extension]` [.description] -- Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the `token.refresh-expired` property has not been enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`5M` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.java-script-auto-redirect]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.java-script-auto-redirect[quarkus.oidc.authentication.java-script-auto-redirect]` [.description] -- If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since it automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to `false` then a status code of '499' will be returned to allow the client to handle the redirect manually --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.token-state-manager.strategy]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token-state-manager.strategy[quarkus.oidc.token-state-manager.strategy]` [.description] -- Default TokenStateManager strategy. --|`keep-all-tokens`, `id-token`, `id-refresh-tokens` |`keep-all-tokens` a| [[quarkus-oidc-oidc-config_quarkus.oidc.token-state-manager.split-tokens]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.token-state-manager.split-tokens[quarkus.oidc.token-state-manager.split-tokens]` [.description] -- Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.authentication.extra-params-extra-params]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.authentication.extra-params-extra-params[quarkus.oidc.authentication.extra-params]` [.description] -- Additional properties which will be added as the query parameters to the authentication redirect URI. --|`Map` | h|[[quarkus-oidc-oidc-config_quarkus.oidc.named-tenants-additional-named-tenants]]link:#quarkus-oidc-oidc-config_quarkus.oidc.named-tenants-additional-named-tenants[Additional named tenants] h|Type h|Default a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.auth-server-url]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.auth-server-url[quarkus.oidc.""tenant"".auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, `https://host:port/auth`. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: `https://host:port/auth/realms/++{++realm++}++` where `++{++realm++}++` has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.discovery-enabled]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.discovery-enabled[quarkus.oidc.""tenant"".discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the 'token-path' property must be configured. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token-path[quarkus.oidc.""tenant"".token-path]` [.description] -- Relative path of the OIDC token endpoint which issues access and refresh tokens using either 'client_credentials' or 'password' grants --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.client-id]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.client-id[quarkus.oidc.""tenant"".client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.connection-delay]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.connection-delay[quarkus.oidc.""tenant"".connection-delay]` [.description] -- The maximum amount of time connecting to the currently unavailable OIDC server will be attempted for. The number of times the connection request will be repeated is calculated by dividing the value of this property by 2. For example, setting it to `20S` will allow for requesting the connection up to 10 times with a 2 seconds delay between the retries. Note this property is only effective when the initial OIDC connection is created, for example, when requesting a well-known OIDC configuration. Use the 'connection-retry-count' property to support trying to re-establish an already available connection which may have been dropped. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.connection-retry-count]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.connection-retry-count[quarkus.oidc.""tenant"".connection-retry-count]` [.description] -- The number of times an attempt to re-establish an already available connection will be repeated for. Note this property is different to the `connection-delay` property which is only effective during the initial OIDC connection creation. This property is used to try to recover the existing connection which may have been temporarily lost. For example, if a request to the OIDC token endpoint fails due to a connection exception then the request will be retried for a number of times configured by this property. --|int |`3` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.connection-timeout]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.connection-timeout[quarkus.oidc.""tenant"".connection-timeout]` [.description] -- The amount of time after which the current OIDC connection request will time out. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10S` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.max-pool-size]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.max-pool-size[quarkus.oidc.""tenant"".max-pool-size]` [.description] -- The maximum size of the connection pool used by the WebClient --|int | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.secret]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.secret[quarkus.oidc.""tenant"".credentials.secret]` [.description] -- Client secret which is used for a `client_secret_basic` authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.client-secret.value]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.client-secret.value[quarkus.oidc.""tenant"".credentials.client-secret.value]` [.description] -- The client secret --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.client-secret.method]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.client-secret.method[quarkus.oidc.""tenant"".credentials.client-secret.method]` [.description] -- Authentication method. --|`basic`, `post` | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.secret]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.secret[quarkus.oidc.""tenant"".credentials.jwt.secret]` [.description] -- If provided, indicates that JWT is signed using a secret key --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-file]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-file[quarkus.oidc.""tenant"".credentials.jwt.key-file]` [.description] -- If provided, indicates that JWT is signed using a private key in PEM or JWK format --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-store-file]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-store-file[quarkus.oidc.""tenant"".credentials.jwt.key-store-file]` [.description] -- If provided, indicates that JWT is signed using a private key from a key store --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-store-password]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-store-password[quarkus.oidc.""tenant"".credentials.jwt.key-store-password]` [.description] -- A parameter to specify the password of the key store file. If not given, the default (""password"") is used. --|string |`password` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-id]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-id[quarkus.oidc.""tenant"".credentials.jwt.key-id]` [.description] -- The private key id/alias --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-password]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.key-password[quarkus.oidc.""tenant"".credentials.jwt.key-password]` [.description] -- The private key password --|string |`password` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.token-key-id]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.token-key-id[quarkus.oidc.""tenant"".credentials.jwt.token-key-id]` [.description] -- Key identifier of the signing key added as a JWT 'kid' header --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.lifespan]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.credentials.jwt.lifespan[quarkus.oidc.""tenant"".credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.proxy.host]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.proxy.host[quarkus.oidc.""tenant"".proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.proxy.port]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.proxy.port[quarkus.oidc.""tenant"".proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.proxy.username]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.proxy.username[quarkus.oidc.""tenant"".proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.proxy.password]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.proxy.password[quarkus.oidc.""tenant"".proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.tls.verification]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.tls.verification[quarkus.oidc.""tenant"".tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. --|`required`, `none` | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.tenant-id]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.tenant-id[quarkus.oidc.""tenant"".tenant-id]` [.description] -- A unique tenant identifier. It must be set by `TenantConfigResolver` providers which resolve the tenant configuration dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.tenant-enabled]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.tenant-enabled[quarkus.oidc.""tenant"".tenant-enabled]` [.description] -- If this tenant configuration is enabled. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.application-type]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.application-type[quarkus.oidc.""tenant"".application-type]` [.description] -- The application type, which can be one of the following values from enum `ApplicationType`. --|`web-app`, `service`, `hybrid` |`service` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authorization-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authorization-path[quarkus.oidc.""tenant"".authorization-path]` [.description] -- Relative path of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.user-info-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.user-info-path[quarkus.oidc.""tenant"".user-info-path]` [.description] -- Relative path of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.introspection-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.introspection-path[quarkus.oidc.""tenant"".introspection-path]` [.description] -- Relative path of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.jwks-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.jwks-path[quarkus.oidc.""tenant"".jwks-path]` [.description] -- Relative path of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.end-session-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.end-session-path[quarkus.oidc.""tenant"".end-session-path]` [.description] -- Relative path of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.public-key]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.public-key[quarkus.oidc.""tenant"".public-key]` [.description] -- Public key for the local JWT token verification. OIDC server connection will not be created when this property is set. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.roles.role-claim-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.roles.role-claim-path[quarkus.oidc.""tenant"".roles.role-claim-path]` [.description] -- Path to the claim containing an array of groups. It starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: ""realm/groups"". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in a different claim. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.roles.role-claim-separator]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.roles.role-claim-separator[quarkus.oidc.""tenant"".roles.role-claim-separator]` [.description] -- Separator for splitting a string which may contain multiple group values. It will only be used if the ""role-claim-path"" property points to a custom claim whose value is a string. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.roles.source]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.roles.source[quarkus.oidc.""tenant"".roles.source]` [.description] -- Source of the principal roles. --|`idtoken`, `accesstoken`, `userinfo` | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.issuer]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.issuer[quarkus.oidc.""tenant"".token.issuer]` [.description] -- Expected issuer 'iss' claim value. Note this property overrides the `issuer` property which may be set in OpenId Connect provider's well-known configuration. If the `iss` claim value varies depending on the host/IP address or tenant id of the provider then you may skip the issuer verification by setting this property to 'any' but it should be done only when other options (such as configuring the provider to use the fixed `iss` claim value) are not possible. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.audience]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.audience[quarkus.oidc.""tenant"".token.audience]` [.description] -- Expected audience 'aud' claim value which may be a string or an array of strings. --|list of string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.token-type]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.token-type[quarkus.oidc.""tenant"".token.token-type]` [.description] -- Expected token type --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.lifespan-grace]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.lifespan-grace[quarkus.oidc.""tenant"".token.lifespan-grace]` [.description] -- Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds. --|int | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.principal-claim]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.principal-claim[quarkus.oidc.""tenant"".token.principal-claim]` [.description] -- Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and `sub` claims are checked. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.refresh-expired]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.refresh-expired[quarkus.oidc.""tenant"".token.refresh-expired]` [.description] -- Refresh expired ID tokens. If this property is enabled then a refresh token request will be performed if the ID token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the `authentication.session-age-extension` property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type `ApplicationType++#++WEB_APP`++}++. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.refresh-token-time-skew]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.refresh-token-time-skew[quarkus.oidc.""tenant"".token.refresh-token-time-skew]` [.description] -- Refresh token time skew in seconds. If this property is enabled then the configured number of seconds is added to the current time when checking whether the access token should be refreshed. If the sum is greater than this access token's expiration time then a refresh is going to happen. This property will be ignored if the 'refresh-expired' property is not enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.forced-jwk-refresh-interval]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.forced-jwk-refresh-interval[quarkus.oidc.""tenant"".token.forced-jwk-refresh-interval]` [.description] -- Forced JWK set refresh interval in minutes. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10M` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.header]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.header[quarkus.oidc.""tenant"".token.header]` [.description] -- Custom HTTP header that contains a bearer token. This option is valid only when the application is of type `ApplicationType++#++SERVICE`++}++. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.allow-jwt-introspection]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.allow-jwt-introspection[quarkus.oidc.""tenant"".token.allow-jwt-introspection]` [.description] -- Allow the remote introspection of JWT tokens when no matching JWK key is available. Note this property is set to 'true' by default for backward-compatibility reasons and will be set to `false` instead in one of the next releases. Also note this property will be ignored if JWK endpoint URI is not available and introspecting the tokens is the only verification option. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.allow-opaque-token-introspection]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token.allow-opaque-token-introspection[quarkus.oidc.""tenant"".token.allow-opaque-token-introspection]` [.description] -- Allow the remote introspection of the opaque tokens. Set this property to 'false' if only JWT tokens are expected. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.logout.path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.logout.path[quarkus.oidc.""tenant"".logout.path]` [.description] -- The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.logout.post-logout-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.logout.post-logout-path[quarkus.oidc.""tenant"".logout.post-logout-path]` [.description] -- Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.redirect-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.redirect-path[quarkus.oidc.""tenant"".authentication.redirect-path]` [.description] -- Relative path for calculating a ""redirect_uri"" query parameter. It has to start from a forward slash and will be appended to the request URI's host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated if 'restorePathAfterRedirect' is set to 'true'. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.restore-path-after-redirect]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.restore-path-after-redirect[quarkus.oidc.""tenant"".authentication.restore-path-after-redirect]` [.description] -- If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. Note if `redirectPath` property is not set the the original request URI will be restored even if this property is disabled. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.remove-redirect-parameters]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.remove-redirect-parameters[quarkus.oidc.""tenant"".authentication.remove-redirect-parameters]` [.description] -- Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters. --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.verify-access-token]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.verify-access-token[quarkus.oidc.""tenant"".authentication.verify-access-token]` [.description] -- Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if `quarkus.oidc.roles.source` property is set to `accesstoken` which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.force-redirect-https-scheme]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.force-redirect-https-scheme[quarkus.oidc.""tenant"".authentication.force-redirect-https-scheme]` [.description] -- Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout `post_logout_redirect_uri` and the local redirect requests. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.scopes]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.scopes[quarkus.oidc.""tenant"".authentication.scopes]` [.description] -- List of scopes --|list of string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.extra-params-extra-params]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.extra-params-extra-params[quarkus.oidc.""tenant"".authentication.extra-params]` [.description] -- Additional properties which will be added as the query parameters to the authentication redirect URI. --|`Map` | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.cookie-force-secure]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.cookie-force-secure[quarkus.oidc.""tenant"".authentication.cookie-force-secure]` [.description] -- If enabled the state, session and post logout cookies will have their 'secure' parameter set to 'true' when HTTP is used. It may be necessary when running behind an SSL terminating reverse proxy. The cookies will always be secure if HTTPS is used even if this property is set to false. --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.cookie-path]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.cookie-path[quarkus.oidc.""tenant"".authentication.cookie-path]` [.description] -- Cookie path parameter value which, if set, will be used to set a path parameter for the session, state and post logout cookies. The `cookie-path-header` property, if set, will be checked first. --|string |`/` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.cookie-path-header]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.cookie-path-header[quarkus.oidc.""tenant"".authentication.cookie-path-header]` [.description] -- Cookie path header parameter value which, if set, identifies the incoming HTTP header whose value will be used to set a path parameter for the session, state and post logout cookies. If the header is missing then the `cookie-path` property will be checked. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.cookie-domain]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.cookie-domain[quarkus.oidc.""tenant"".authentication.cookie-domain]` [.description] -- Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies. --|string | a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.user-info-required]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.user-info-required[quarkus.oidc.""tenant"".authentication.user-info-required]` [.description] -- If this property is set to 'true' then an OIDC UserInfo endpoint will be called --|boolean |`false` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.session-age-extension]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.session-age-extension[quarkus.oidc.""tenant"".authentication.session-age-extension]` [.description] -- Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the `token.refresh-expired` property has not been enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`5M` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.java-script-auto-redirect]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.authentication.java-script-auto-redirect[quarkus.oidc.""tenant"".authentication.java-script-auto-redirect]` [.description] -- If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since it automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to `false` then a status code of '499' will be returned to allow the client to handle the redirect manually --|boolean |`true` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token-state-manager.strategy]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token-state-manager.strategy[quarkus.oidc.""tenant"".token-state-manager.strategy]` [.description] -- Default TokenStateManager strategy. --|`keep-all-tokens`, `id-token`, `id-refresh-tokens` |`keep-all-tokens` a| [[quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token-state-manager.split-tokens]]`link:#quarkus-oidc-oidc-config_quarkus.oidc.-tenant-.token-state-manager.split-tokens[quarkus.oidc.""tenant"".token-state-manager.split-tokens]` [.description] -- Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size --|boolean |`false` |=== ifndef::no-duration-note[] [NOTE] [[duration-note-anchor]] .About the Duration format ==== The format for durations uses the standard `java.time.Duration` format. You can learn more about it in the link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-[Duration#parse() javadoc]. You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, `PT` is implicitly prepended to the value to obtain a standard `java.time.Duration` format. ==== endif::no-duration-note[] ",16157,True,4641.788350210085,median "[.configuration-legend] icon:lock[title=Fixed at build time] Configuration property fixed at build time - All other configuration properties are overridable at runtime [.configuration-reference, cols=""80,.^10,.^10""] |=== h|[[quarkus-knative-knative-config_configuration]]link:#quarkus-knative-knative-config_configuration[Configuration property] h|Type h|Default a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.part-of]]`link:#quarkus-knative-knative-config_quarkus.knative.part-of[quarkus.knative.part-of]` [.description] -- The name of the group this component belongs too --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.name]]`link:#quarkus-knative-knative-config_quarkus.knative.name[quarkus.knative.name]` [.description] -- The name of the application. This value will be used for naming Kubernetes resources like: - Deployment - Service and so on ... --|string |`${quarkus.container-image.name}` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.version]]`link:#quarkus-knative-knative-config_quarkus.knative.version[quarkus.knative.version]` [.description] -- The version of the application. --|string |`${quarkus.container-image.tag}` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.add-build-timestamp]]`link:#quarkus-knative-knative-config_quarkus.knative.add-build-timestamp[quarkus.knative.add-build-timestamp]` [.description] -- Whether or not to add the build timestamp to the Kubernetes annotations This is a very useful way to have manifests of successive builds of the same application differ - thus ensuring that Kubernetes will apply the updated resources --|boolean |`true` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.working-dir]]`link:#quarkus-knative-knative-config_quarkus.knative.working-dir[quarkus.knative.working-dir]` [.description] -- Working directory --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.command]]`link:#quarkus-knative-knative-config_quarkus.knative.command[quarkus.knative.command]` [.description] -- The commands --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.arguments]]`link:#quarkus-knative-knative-config_quarkus.knative.arguments[quarkus.knative.arguments]` [.description] -- The arguments --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.service-account]]`link:#quarkus-knative-knative-config_quarkus.knative.service-account[quarkus.knative.service-account]` [.description] -- The service account --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.host]]`link:#quarkus-knative-knative-config_quarkus.knative.host[quarkus.knative.host]` [.description] -- The host under which the application is going to be exposed --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.service-type]]`link:#quarkus-knative-knative-config_quarkus.knative.service-type[quarkus.knative.service-type]` [.description] -- The type of service that will be generated for the application --|`cluster-ip`, `node-port`, `load-balancer`, `external-name` |`cluster-ip` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.image-pull-policy]]`link:#quarkus-knative-knative-config_quarkus.knative.image-pull-policy[quarkus.knative.image-pull-policy]` [.description] -- Image pull policy --|`always`, `if-not-present`, `never` |`always` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.image-pull-secrets]]`link:#quarkus-knative-knative-config_quarkus.knative.image-pull-secrets[quarkus.knative.image-pull-secrets]` [.description] -- The image pull secret --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.liveness-probe.http-action-path]]`link:#quarkus-knative-knative-config_quarkus.knative.liveness-probe.http-action-path[quarkus.knative.liveness-probe.http-action-path]` [.description] -- The http path to use for the probe For this to work, the container port also needs to be set Assuming the container port has been set (as per above comment), if execAction or tcpSocketAction are not set, an http probe will be used automatically even if no path is set (which will result in the root path being used) --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.liveness-probe.exec-action]]`link:#quarkus-knative-knative-config_quarkus.knative.liveness-probe.exec-action[quarkus.knative.liveness-probe.exec-action]` [.description] -- The command to use for the probe. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.liveness-probe.tcp-socket-action]]`link:#quarkus-knative-knative-config_quarkus.knative.liveness-probe.tcp-socket-action[quarkus.knative.liveness-probe.tcp-socket-action]` [.description] -- The tcp socket to use for the probe (the format is host:port). --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.liveness-probe.initial-delay]]`link:#quarkus-knative-knative-config_quarkus.knative.liveness-probe.initial-delay[quarkus.knative.liveness-probe.initial-delay]` [.description] -- The amount of time to wait before starting to probe. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`0` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.liveness-probe.period]]`link:#quarkus-knative-knative-config_quarkus.knative.liveness-probe.period[quarkus.knative.liveness-probe.period]` [.description] -- The period in which the action should be called. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`30s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.liveness-probe.timeout]]`link:#quarkus-knative-knative-config_quarkus.knative.liveness-probe.timeout[quarkus.knative.liveness-probe.timeout]` [.description] -- The amount of time to wait for each action. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.liveness-probe.success-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.liveness-probe.success-threshold[quarkus.knative.liveness-probe.success-threshold]` [.description] -- The success threshold to use. --|int |`1` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.liveness-probe.failure-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.liveness-probe.failure-threshold[quarkus.knative.liveness-probe.failure-threshold]` [.description] -- The failure threshold to use. --|int |`3` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.readiness-probe.http-action-path]]`link:#quarkus-knative-knative-config_quarkus.knative.readiness-probe.http-action-path[quarkus.knative.readiness-probe.http-action-path]` [.description] -- The http path to use for the probe For this to work, the container port also needs to be set Assuming the container port has been set (as per above comment), if execAction or tcpSocketAction are not set, an http probe will be used automatically even if no path is set (which will result in the root path being used) --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.readiness-probe.exec-action]]`link:#quarkus-knative-knative-config_quarkus.knative.readiness-probe.exec-action[quarkus.knative.readiness-probe.exec-action]` [.description] -- The command to use for the probe. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.readiness-probe.tcp-socket-action]]`link:#quarkus-knative-knative-config_quarkus.knative.readiness-probe.tcp-socket-action[quarkus.knative.readiness-probe.tcp-socket-action]` [.description] -- The tcp socket to use for the probe (the format is host:port). --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.readiness-probe.initial-delay]]`link:#quarkus-knative-knative-config_quarkus.knative.readiness-probe.initial-delay[quarkus.knative.readiness-probe.initial-delay]` [.description] -- The amount of time to wait before starting to probe. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`0` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.readiness-probe.period]]`link:#quarkus-knative-knative-config_quarkus.knative.readiness-probe.period[quarkus.knative.readiness-probe.period]` [.description] -- The period in which the action should be called. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`30s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.readiness-probe.timeout]]`link:#quarkus-knative-knative-config_quarkus.knative.readiness-probe.timeout[quarkus.knative.readiness-probe.timeout]` [.description] -- The amount of time to wait for each action. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.readiness-probe.success-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.readiness-probe.success-threshold[quarkus.knative.readiness-probe.success-threshold]` [.description] -- The success threshold to use. --|int |`1` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.readiness-probe.failure-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.readiness-probe.failure-threshold[quarkus.knative.readiness-probe.failure-threshold]` [.description] -- The failure threshold to use. --|int |`3` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.env.secrets]]`link:#quarkus-knative-knative-config_quarkus.knative.env.secrets[quarkus.knative.env.secrets]` [.description] -- The optional list of Secret names to load environment variables from. --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.env.configmaps]]`link:#quarkus-knative-knative-config_quarkus.knative.env.configmaps[quarkus.knative.env.configmaps]` [.description] -- The optional list of ConfigMap names to load environment variables from. --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.labels-labels]]`link:#quarkus-knative-knative-config_quarkus.knative.labels-labels[quarkus.knative.labels]` [.description] -- Custom labels to add to all resources --|`Map` |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.annotations-annotations]]`link:#quarkus-knative-knative-config_quarkus.knative.annotations-annotations[quarkus.knative.annotations]` [.description] -- Custom annotations to add to all resources --|`Map` |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.ports.-ports-.container-port]]`link:#quarkus-knative-knative-config_quarkus.knative.ports.-ports-.container-port[quarkus.knative.ports.""ports"".container-port]` [.description] -- The port number. Refers to the container port. --|int | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.ports.-ports-.host-port]]`link:#quarkus-knative-knative-config_quarkus.knative.ports.-ports-.host-port[quarkus.knative.ports.""ports"".host-port]` [.description] -- The host port. --|int | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.ports.-ports-.path]]`link:#quarkus-knative-knative-config_quarkus.knative.ports.-ports-.path[quarkus.knative.ports.""ports"".path]` [.description] -- The application path (refers to web application path). --|string |`/` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.ports.-ports-.protocol]]`link:#quarkus-knative-knative-config_quarkus.knative.ports.-ports-.protocol[quarkus.knative.ports.""ports"".protocol]` [.description] -- The protocol. --|`tcp`, `udp` |`tcp` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.mounts.-mounts-.name]]`link:#quarkus-knative-knative-config_quarkus.knative.mounts.-mounts-.name[quarkus.knative.mounts.""mounts"".name]` [.description] -- The name of the volumeName to mount. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.mounts.-mounts-.path]]`link:#quarkus-knative-knative-config_quarkus.knative.mounts.-mounts-.path[quarkus.knative.mounts.""mounts"".path]` [.description] -- The path to mount. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.mounts.-mounts-.sub-path]]`link:#quarkus-knative-knative-config_quarkus.knative.mounts.-mounts-.sub-path[quarkus.knative.mounts.""mounts"".sub-path]` [.description] -- Path within the volumeName from which the container's volumeName should be mounted. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.mounts.-mounts-.read-only]]`link:#quarkus-knative-knative-config_quarkus.knative.mounts.-mounts-.read-only[quarkus.knative.mounts.""mounts"".read-only]` [.description] -- ReadOnly --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.secret-volumes.-secret-volumes-.secret-name]]`link:#quarkus-knative-knative-config_quarkus.knative.secret-volumes.-secret-volumes-.secret-name[quarkus.knative.secret-volumes.""secret-volumes"".secret-name]` [.description] -- The name of the secret to mount. --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.secret-volumes.-secret-volumes-.default-mode]]`link:#quarkus-knative-knative-config_quarkus.knative.secret-volumes.-secret-volumes-.default-mode[quarkus.knative.secret-volumes.""secret-volumes"".default-mode]` [.description] -- Default mode. When specifying an octal number, leading zero must be present. --|string |`0600` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.secret-volumes.-secret-volumes-.optional]]`link:#quarkus-knative-knative-config_quarkus.knative.secret-volumes.-secret-volumes-.optional[quarkus.knative.secret-volumes.""secret-volumes"".optional]` [.description] -- Optional --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.config-map-volumes.-config-map-volumes-.config-map-name]]`link:#quarkus-knative-knative-config_quarkus.knative.config-map-volumes.-config-map-volumes-.config-map-name[quarkus.knative.config-map-volumes.""config-map-volumes"".config-map-name]` [.description] -- The name of the ConfigMap to mount. --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.config-map-volumes.-config-map-volumes-.default-mode]]`link:#quarkus-knative-knative-config_quarkus.knative.config-map-volumes.-config-map-volumes-.default-mode[quarkus.knative.config-map-volumes.""config-map-volumes"".default-mode]` [.description] -- Default mode. When specifying an octal number, leading zero must be present. --|string |`0600` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.config-map-volumes.-config-map-volumes-.optional]]`link:#quarkus-knative-knative-config_quarkus.knative.config-map-volumes.-config-map-volumes-.optional[quarkus.knative.config-map-volumes.""config-map-volumes"".optional]` [.description] -- Optional --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.git-repo-volumes.-git-repo-volumes-.repository]]`link:#quarkus-knative-knative-config_quarkus.knative.git-repo-volumes.-git-repo-volumes-.repository[quarkus.knative.git-repo-volumes.""git-repo-volumes"".repository]` [.description] -- Git repoistory URL. --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.git-repo-volumes.-git-repo-volumes-.directory]]`link:#quarkus-knative-knative-config_quarkus.knative.git-repo-volumes.-git-repo-volumes-.directory[quarkus.knative.git-repo-volumes.""git-repo-volumes"".directory]` [.description] -- The directory of the repository to mount. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.git-repo-volumes.-git-repo-volumes-.revision]]`link:#quarkus-knative-knative-config_quarkus.knative.git-repo-volumes.-git-repo-volumes-.revision[quarkus.knative.git-repo-volumes.""git-repo-volumes"".revision]` [.description] -- The commit hash to use. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.pvc-volumes.-pvc-volumes-.claim-name]]`link:#quarkus-knative-knative-config_quarkus.knative.pvc-volumes.-pvc-volumes-.claim-name[quarkus.knative.pvc-volumes.""pvc-volumes"".claim-name]` [.description] -- The name of the claim to mount. --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.pvc-volumes.-pvc-volumes-.default-mode]]`link:#quarkus-knative-knative-config_quarkus.knative.pvc-volumes.-pvc-volumes-.default-mode[quarkus.knative.pvc-volumes.""pvc-volumes"".default-mode]` [.description] -- Default mode. When specifying an octal number, leading zero must be present. --|string |`0600` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.pvc-volumes.-pvc-volumes-.optional]]`link:#quarkus-knative-knative-config_quarkus.knative.pvc-volumes.-pvc-volumes-.optional[quarkus.knative.pvc-volumes.""pvc-volumes"".optional]` [.description] -- Optional --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.aws-elastic-block-store-volumes.-aws-elastic-block-store-volumes-.volume-id]]`link:#quarkus-knative-knative-config_quarkus.knative.aws-elastic-block-store-volumes.-aws-elastic-block-store-volumes-.volume-id[quarkus.knative.aws-elastic-block-store-volumes.""aws-elastic-block-store-volumes"".volume-id]` [.description] -- The name of the disk to mount. --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.aws-elastic-block-store-volumes.-aws-elastic-block-store-volumes-.partition]]`link:#quarkus-knative-knative-config_quarkus.knative.aws-elastic-block-store-volumes.-aws-elastic-block-store-volumes-.partition[quarkus.knative.aws-elastic-block-store-volumes.""aws-elastic-block-store-volumes"".partition]` [.description] -- The partition. --|int | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.aws-elastic-block-store-volumes.-aws-elastic-block-store-volumes-.fs-type]]`link:#quarkus-knative-knative-config_quarkus.knative.aws-elastic-block-store-volumes.-aws-elastic-block-store-volumes-.fs-type[quarkus.knative.aws-elastic-block-store-volumes.""aws-elastic-block-store-volumes"".fs-type]` [.description] -- Filesystem type. --|string |`ext4` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.aws-elastic-block-store-volumes.-aws-elastic-block-store-volumes-.read-only]]`link:#quarkus-knative-knative-config_quarkus.knative.aws-elastic-block-store-volumes.-aws-elastic-block-store-volumes-.read-only[quarkus.knative.aws-elastic-block-store-volumes.""aws-elastic-block-store-volumes"".read-only]` [.description] -- Wether the volumeName is read only or not. --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-file-volumes.-azure-file-volumes-.share-name]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-file-volumes.-azure-file-volumes-.share-name[quarkus.knative.azure-file-volumes.""azure-file-volumes"".share-name]` [.description] -- The share name. --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-file-volumes.-azure-file-volumes-.secret-name]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-file-volumes.-azure-file-volumes-.secret-name[quarkus.knative.azure-file-volumes.""azure-file-volumes"".secret-name]` [.description] -- The secret name. --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-file-volumes.-azure-file-volumes-.read-only]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-file-volumes.-azure-file-volumes-.read-only[quarkus.knative.azure-file-volumes.""azure-file-volumes"".read-only]` [.description] -- Wether the volumeName is read only or not. --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.disk-name]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.disk-name[quarkus.knative.azure-disk-volumes.""azure-disk-volumes"".disk-name]` [.description] -- The name of the disk to mount. --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.disk-uri]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.disk-uri[quarkus.knative.azure-disk-volumes.""azure-disk-volumes"".disk-uri]` [.description] -- The URI of the vhd blob object OR the resourceID of an Azure managed data disk if Kind is Managed --|string |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.kind]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.kind[quarkus.knative.azure-disk-volumes.""azure-disk-volumes"".kind]` [.description] -- Kind of disk. --|`managed`, `shared` |`managed` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.caching-mode]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.caching-mode[quarkus.knative.azure-disk-volumes.""azure-disk-volumes"".caching-mode]` [.description] -- Disk caching mode. --|`read-write`, `read-only`, `none` |`read-write` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.fs-type]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.fs-type[quarkus.knative.azure-disk-volumes.""azure-disk-volumes"".fs-type]` [.description] -- File system type. --|string |`ext4` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.read-only]]`link:#quarkus-knative-knative-config_quarkus.knative.azure-disk-volumes.-azure-disk-volumes-.read-only[quarkus.knative.azure-disk-volumes.""azure-disk-volumes"".read-only]` [.description] -- Wether the volumeName is read only or not. --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.image]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.image[quarkus.knative.init-containers.""init-containers"".image]` [.description] -- The container image. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.working-dir]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.working-dir[quarkus.knative.init-containers.""init-containers"".working-dir]` [.description] -- Working directory. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.command]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.command[quarkus.knative.init-containers.""init-containers"".command]` [.description] -- The commands --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.arguments]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.arguments[quarkus.knative.init-containers.""init-containers"".arguments]` [.description] -- The arguments --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.service-account]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.service-account[quarkus.knative.init-containers.""init-containers"".service-account]` [.description] -- The service account. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.host]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.host[quarkus.knative.init-containers.""init-containers"".host]` [.description] -- The host under which the application is going to be exposed. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.ports.-ports-.container-port]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.ports.-ports-.container-port[quarkus.knative.init-containers.""init-containers"".ports.""ports"".container-port]` [.description] -- The port number. Refers to the container port. --|int | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.ports.-ports-.host-port]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.ports.-ports-.host-port[quarkus.knative.init-containers.""init-containers"".ports.""ports"".host-port]` [.description] -- The host port. --|int | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.ports.-ports-.path]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.ports.-ports-.path[quarkus.knative.init-containers.""init-containers"".ports.""ports"".path]` [.description] -- The application path (refers to web application path). --|string |`/` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.ports.-ports-.protocol]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.ports.-ports-.protocol[quarkus.knative.init-containers.""init-containers"".ports.""ports"".protocol]` [.description] -- The protocol. --|`tcp`, `udp` |`tcp` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.image-pull-policy]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.image-pull-policy[quarkus.knative.init-containers.""init-containers"".image-pull-policy]` [.description] -- Image pull policy. --|`always`, `if-not-present`, `never` |`always` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.image-pull-secrets]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.image-pull-secrets[quarkus.knative.init-containers.""init-containers"".image-pull-secrets]` [.description] -- The image pull secret --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.mounts.-mounts-.name]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.mounts.-mounts-.name[quarkus.knative.init-containers.""init-containers"".mounts.""mounts"".name]` [.description] -- The name of the volumeName to mount. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.mounts.-mounts-.path]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.mounts.-mounts-.path[quarkus.knative.init-containers.""init-containers"".mounts.""mounts"".path]` [.description] -- The path to mount. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.mounts.-mounts-.sub-path]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.mounts.-mounts-.sub-path[quarkus.knative.init-containers.""init-containers"".mounts.""mounts"".sub-path]` [.description] -- Path within the volumeName from which the container's volumeName should be mounted. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.mounts.-mounts-.read-only]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.mounts.-mounts-.read-only[quarkus.knative.init-containers.""init-containers"".mounts.""mounts"".read-only]` [.description] -- ReadOnly --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.env.secrets]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.env.secrets[quarkus.knative.init-containers.""init-containers"".env.secrets]` [.description] -- The optional list of Secret names to load environment variables from. --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.env.configmaps]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.env.configmaps[quarkus.knative.init-containers.""init-containers"".env.configmaps]` [.description] -- The optional list of ConfigMap names to load environment variables from. --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.env.fields-fields]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.env.fields-fields[quarkus.knative.init-containers.""init-containers"".env.fields]` [.description] -- The map associating environment variable names to their associated field references they take their value from. --|`Map` |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.env.vars-vars]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.env.vars-vars[quarkus.knative.init-containers.""init-containers"".env.vars]` [.description] -- The map associating environment name to its associated value. --|`Map` |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.image]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.image[quarkus.knative.containers.""containers"".image]` [.description] -- The container image. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.working-dir]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.working-dir[quarkus.knative.containers.""containers"".working-dir]` [.description] -- Working directory. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.command]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.command[quarkus.knative.containers.""containers"".command]` [.description] -- The commands --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.arguments]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.arguments[quarkus.knative.containers.""containers"".arguments]` [.description] -- The arguments --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.service-account]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.service-account[quarkus.knative.containers.""containers"".service-account]` [.description] -- The service account. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.host]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.host[quarkus.knative.containers.""containers"".host]` [.description] -- The host under which the application is going to be exposed. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.ports.-ports-.container-port]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.ports.-ports-.container-port[quarkus.knative.containers.""containers"".ports.""ports"".container-port]` [.description] -- The port number. Refers to the container port. --|int | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.ports.-ports-.host-port]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.ports.-ports-.host-port[quarkus.knative.containers.""containers"".ports.""ports"".host-port]` [.description] -- The host port. --|int | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.ports.-ports-.path]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.ports.-ports-.path[quarkus.knative.containers.""containers"".ports.""ports"".path]` [.description] -- The application path (refers to web application path). --|string |`/` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.ports.-ports-.protocol]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.ports.-ports-.protocol[quarkus.knative.containers.""containers"".ports.""ports"".protocol]` [.description] -- The protocol. --|`tcp`, `udp` |`tcp` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.image-pull-policy]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.image-pull-policy[quarkus.knative.containers.""containers"".image-pull-policy]` [.description] -- Image pull policy. --|`always`, `if-not-present`, `never` |`always` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.image-pull-secrets]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.image-pull-secrets[quarkus.knative.containers.""containers"".image-pull-secrets]` [.description] -- The image pull secret --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.mounts.-mounts-.name]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.mounts.-mounts-.name[quarkus.knative.containers.""containers"".mounts.""mounts"".name]` [.description] -- The name of the volumeName to mount. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.mounts.-mounts-.path]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.mounts.-mounts-.path[quarkus.knative.containers.""containers"".mounts.""mounts"".path]` [.description] -- The path to mount. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.mounts.-mounts-.sub-path]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.mounts.-mounts-.sub-path[quarkus.knative.containers.""containers"".mounts.""mounts"".sub-path]` [.description] -- Path within the volumeName from which the container's volumeName should be mounted. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.mounts.-mounts-.read-only]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.mounts.-mounts-.read-only[quarkus.knative.containers.""containers"".mounts.""mounts"".read-only]` [.description] -- ReadOnly --|boolean |`false` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.env.secrets]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.env.secrets[quarkus.knative.containers.""containers"".env.secrets]` [.description] -- The optional list of Secret names to load environment variables from. --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.env.configmaps]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.env.configmaps[quarkus.knative.containers.""containers"".env.configmaps]` [.description] -- The optional list of ConfigMap names to load environment variables from. --|list of string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.env.fields-fields]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.env.fields-fields[quarkus.knative.containers.""containers"".env.fields]` [.description] -- The map associating environment variable names to their associated field references they take their value from. --|`Map` |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.env.vars-vars]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.env.vars-vars[quarkus.knative.containers.""containers"".env.vars]` [.description] -- The map associating environment name to its associated value. --|`Map` |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.env.fields-fields]]`link:#quarkus-knative-knative-config_quarkus.knative.env.fields-fields[quarkus.knative.env.fields]` [.description] -- The map associating environment variable names to their associated field references they take their value from. --|`Map` |required icon:exclamation-circle[title=Configuration property is required] a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.env.vars-vars]]`link:#quarkus-knative-knative-config_quarkus.knative.env.vars-vars[quarkus.knative.env.vars]` [.description] -- The map associating environment name to its associated value. --|`Map` |required icon:exclamation-circle[title=Configuration property is required] h|[[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe]]link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe[The liveness probe] This configuration section is optional h|Type h|Default a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.http-action-path]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.http-action-path[quarkus.knative.init-containers.""init-containers"".liveness-probe.http-action-path]` [.description] -- The http path to use for the probe For this to work, the container port also needs to be set Assuming the container port has been set (as per above comment), if execAction or tcpSocketAction are not set, an http probe will be used automatically even if no path is set (which will result in the root path being used) --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.exec-action]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.exec-action[quarkus.knative.init-containers.""init-containers"".liveness-probe.exec-action]` [.description] -- The command to use for the probe. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.tcp-socket-action]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.tcp-socket-action[quarkus.knative.init-containers.""init-containers"".liveness-probe.tcp-socket-action]` [.description] -- The tcp socket to use for the probe (the format is host:port). --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.initial-delay]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.initial-delay[quarkus.knative.init-containers.""init-containers"".liveness-probe.initial-delay]` [.description] -- The amount of time to wait before starting to probe. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`0` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.period]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.period[quarkus.knative.init-containers.""init-containers"".liveness-probe.period]` [.description] -- The period in which the action should be called. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`30s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.timeout]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.timeout[quarkus.knative.init-containers.""init-containers"".liveness-probe.timeout]` [.description] -- The amount of time to wait for each action. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.success-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.success-threshold[quarkus.knative.init-containers.""init-containers"".liveness-probe.success-threshold]` [.description] -- The success threshold to use. --|int |`1` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.failure-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.liveness-probe.failure-threshold[quarkus.knative.init-containers.""init-containers"".liveness-probe.failure-threshold]` [.description] -- The failure threshold to use. --|int |`3` h|[[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe]]link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe[The readiness probe] This configuration section is optional h|Type h|Default a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.http-action-path]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.http-action-path[quarkus.knative.init-containers.""init-containers"".readiness-probe.http-action-path]` [.description] -- The http path to use for the probe For this to work, the container port also needs to be set Assuming the container port has been set (as per above comment), if execAction or tcpSocketAction are not set, an http probe will be used automatically even if no path is set (which will result in the root path being used) --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.exec-action]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.exec-action[quarkus.knative.init-containers.""init-containers"".readiness-probe.exec-action]` [.description] -- The command to use for the probe. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.tcp-socket-action]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.tcp-socket-action[quarkus.knative.init-containers.""init-containers"".readiness-probe.tcp-socket-action]` [.description] -- The tcp socket to use for the probe (the format is host:port). --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.initial-delay]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.initial-delay[quarkus.knative.init-containers.""init-containers"".readiness-probe.initial-delay]` [.description] -- The amount of time to wait before starting to probe. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`0` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.period]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.period[quarkus.knative.init-containers.""init-containers"".readiness-probe.period]` [.description] -- The period in which the action should be called. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`30s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.timeout]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.timeout[quarkus.knative.init-containers.""init-containers"".readiness-probe.timeout]` [.description] -- The amount of time to wait for each action. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.success-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.success-threshold[quarkus.knative.init-containers.""init-containers"".readiness-probe.success-threshold]` [.description] -- The success threshold to use. --|int |`1` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.failure-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.init-containers.-init-containers-.readiness-probe.failure-threshold[quarkus.knative.init-containers.""init-containers"".readiness-probe.failure-threshold]` [.description] -- The failure threshold to use. --|int |`3` h|[[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe]]link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe[The liveness probe] This configuration section is optional h|Type h|Default a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.http-action-path]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.http-action-path[quarkus.knative.containers.""containers"".liveness-probe.http-action-path]` [.description] -- The http path to use for the probe For this to work, the container port also needs to be set Assuming the container port has been set (as per above comment), if execAction or tcpSocketAction are not set, an http probe will be used automatically even if no path is set (which will result in the root path being used) --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.exec-action]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.exec-action[quarkus.knative.containers.""containers"".liveness-probe.exec-action]` [.description] -- The command to use for the probe. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.tcp-socket-action]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.tcp-socket-action[quarkus.knative.containers.""containers"".liveness-probe.tcp-socket-action]` [.description] -- The tcp socket to use for the probe (the format is host:port). --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.initial-delay]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.initial-delay[quarkus.knative.containers.""containers"".liveness-probe.initial-delay]` [.description] -- The amount of time to wait before starting to probe. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`0` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.period]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.period[quarkus.knative.containers.""containers"".liveness-probe.period]` [.description] -- The period in which the action should be called. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`30s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.timeout]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.timeout[quarkus.knative.containers.""containers"".liveness-probe.timeout]` [.description] -- The amount of time to wait for each action. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.success-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.success-threshold[quarkus.knative.containers.""containers"".liveness-probe.success-threshold]` [.description] -- The success threshold to use. --|int |`1` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.failure-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.liveness-probe.failure-threshold[quarkus.knative.containers.""containers"".liveness-probe.failure-threshold]` [.description] -- The failure threshold to use. --|int |`3` h|[[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe]]link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe[The readiness probe] This configuration section is optional h|Type h|Default a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.http-action-path]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.http-action-path[quarkus.knative.containers.""containers"".readiness-probe.http-action-path]` [.description] -- The http path to use for the probe For this to work, the container port also needs to be set Assuming the container port has been set (as per above comment), if execAction or tcpSocketAction are not set, an http probe will be used automatically even if no path is set (which will result in the root path being used) --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.exec-action]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.exec-action[quarkus.knative.containers.""containers"".readiness-probe.exec-action]` [.description] -- The command to use for the probe. --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.tcp-socket-action]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.tcp-socket-action[quarkus.knative.containers.""containers"".readiness-probe.tcp-socket-action]` [.description] -- The tcp socket to use for the probe (the format is host:port). --|string | a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.initial-delay]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.initial-delay[quarkus.knative.containers.""containers"".readiness-probe.initial-delay]` [.description] -- The amount of time to wait before starting to probe. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`0` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.period]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.period[quarkus.knative.containers.""containers"".readiness-probe.period]` [.description] -- The period in which the action should be called. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`30s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.timeout]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.timeout[quarkus.knative.containers.""containers"".readiness-probe.timeout]` [.description] -- The amount of time to wait for each action. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10s` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.success-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.success-threshold[quarkus.knative.containers.""containers"".readiness-probe.success-threshold]` [.description] -- The success threshold to use. --|int |`1` a|icon:lock[title=Fixed at build time] [[quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.failure-threshold]]`link:#quarkus-knative-knative-config_quarkus.knative.containers.-containers-.readiness-probe.failure-threshold[quarkus.knative.containers.""containers"".readiness-probe.failure-threshold]` [.description] -- The failure threshold to use. --|int |`3` |=== [NOTE] [[duration-note-anchor]] .About the Duration format ==== The format for durations uses the standard `java.time.Duration` format. You can learn more about it in the link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-[Duration#parse() javadoc]. You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, `PT` is implicitly prepended to the value to obtain a standard `java.time.Duration` format. ==== ",16220,True,5059.873862605554,median "[[kafka-component]] == Kafka Component *Available as of Camel version 2.13* The *kafka:* component is used for communicating with http://kafka.apache.org/[Apache Kafka] message broker. Maven users will need to add the following dependency to their `pom.xml` for this component. [source,xml] ------------------------------------------------------------ org.apache.camel camel-kafka x.x.x ------------------------------------------------------------ === URI format [source,java] --------------------------- kafka:topic[?options] --------------------------- === Options // component options: START The Kafka component supports 8 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | Allows to pre-configure the Kafka component with common options that the endpoints will reuse. | | KafkaConfiguration | *brokers* (common) | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *workerPool* (advanced) | To use a shared custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. If using this option then you must handle the lifecycle of the thread pool to shut the pool down when no longer needed. | | ExecutorService | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *breakOnFirstError* (consumer) | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | boolean | *allowManualCommit* (consumer) | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | boolean | *kafkaManualCommit Factory* (consumer) | Factory to use for creating KafkaManualCommit instances. This allows to plugin a custom factory to create custom KafkaManualCommit instances in case special logic is needed when doing manual commits that deviates from the default implementation that comes out of the box. | | KafkaManualCommit Factory | *resolveProperty Placeholders* (advanced) | Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders. | true | boolean |=== // component options: END // endpoint options: START The Kafka endpoint is configured using URI syntax: ---- kafka:topic ---- with the following path and query parameters: ==== Path Parameters (1 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *topic* | *Required* Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. | | String |=== ==== Query Parameters (95 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *brokers* (common) | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *clientId* (common) | The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | | String | *headerFilterStrategy* (common) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *reconnectBackoffMaxMs* (common) | The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | *allowManualCommit* (consumer) | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | boolean | *autoCommitEnable* (consumer) | If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin. | true | Boolean | *autoCommitIntervalMs* (consumer) | The frequency in ms that the consumer offsets are committed to zookeeper. | 5000 | Integer | *autoCommitOnStop* (consumer) | Whether to perform an explicit auto commit when the consumer stops to ensure the broker has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. The possible values are: sync, async, or none. And sync is the default value. | sync | String | *autoOffsetReset* (consumer) | What to do when there is no initial offset in ZooKeeper or if an offset is out of range: earliest : automatically reset the offset to the earliest offset latest : automatically reset the offset to the latest offset fail: throw exception to the consumer | latest | String | *breakOnFirstError* (consumer) | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *checkCrcs* (consumer) | Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | *consumerRequestTimeoutMs* (consumer) | The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. | 40000 | Integer | *consumersCount* (consumer) | The number of consumers that connect to kafka server | 1 | int | *consumerStreams* (consumer) | Number of concurrent consumers on the consumer | 10 | int | *fetchMaxBytes* (consumer) | The maximum amount of data the server should return for a fetch request This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | *fetchMinBytes* (consumer) | The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. | 1 | Integer | *fetchWaitMaxMs* (consumer) | The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes | 500 | Integer | *groupId* (consumer) | A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group. This option is required for consumers. | | String | *heartbeatIntervalMs* (consumer) | The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. | 3000 | Integer | *kafkaHeaderDeserializer* (consumer) | Sets custom KafkaHeaderDeserializer for deserialization kafka headers values to camel headers values. | | KafkaHeaderDeserializer | *keyDeserializer* (consumer) | Deserializer class for key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *maxPartitionFetchBytes* (consumer) | The maximum amount of data per-partition the server will return. The maximum total memory used for a request will be #partitions max.partition.fetch.bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. | 1048576 | Integer | *maxPollIntervalMs* (consumer) | The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. | | Long | *maxPollRecords* (consumer) | The maximum number of records returned in a single call to poll() | 500 | Integer | *offsetRepository* (consumer) | The offset repository to use in order to locally store the offset of each partition of the topic. Defining one will disable the autocommit. | | StateRepository | *partitionAssignor* (consumer) | The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used | org.apache.kafka.clients.consumer.RangeAssignor | String | *pollTimeoutMs* (consumer) | The timeout used when polling the KafkaConsumer. | 5000 | Long | *seekTo* (consumer) | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning | | String | *sessionTimeoutMs* (consumer) | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer | *specificAvroReader* (consumer) | This enables the use of a specific Avro reader for use with the Confluent schema registry and the io.confluent.kafka.serializers.KafkaAvroDeserializer. This option is only available in the Confluent Kafka product (not standard Apache Kafka) | false | boolean | *topicIsPattern* (consumer) | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | boolean | *valueDeserializer* (consumer) | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *bridgeEndpoint* (producer) | If the option is true, then KafkaProducer will ignore the KafkaConstants.TOPIC header setting of the inbound message. | false | boolean | *bufferMemorySize* (producer) | The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will either block or throw an exception based on the preference specified by block.on.buffer.full.This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | *circularTopicDetection* (producer) | If the option is true, then KafkaProducer will detect if the message is attempted to be sent back to the same topic it may come from, if the message was original from a kafka consumer. If the KafkaConstants.TOPIC header is the same as the original kafka consumer topic, then the header setting is ignored, and the topic of the producer endpoint is used. In other words this avoids sending the same message back to where it came from. This option is not in use if the option bridgeEndpoint is set to true. | true | boolean | *compressionCodec* (producer) | This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are none, gzip and snappy. | none | String | *connectionMaxIdleMs* (producer) | Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | *enableIdempotence* (producer) | If set to 'true' the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries may write duplicates of the retried message in the stream. If set to true this option will require max.in.flight.requests.per.connection to be set to 1 and retries cannot be zero and additionally acks must be set to 'all'. | false | boolean | *kafkaHeaderSerializer* (producer) | Sets custom KafkaHeaderDeserializer for serialization camel headers values to kafka headers values. | | KafkaHeaderSerializer | *key* (producer) | The record key (or null if no key is specified). If this option has been configured then it take precedence over header KafkaConstants#KEY | | String | *keySerializerClass* (producer) | The serializer class for keys (defaults to the same as for messages if nothing is given). | org.apache.kafka.common.serialization.StringSerializer | String | *lingerMs* (producer) | The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delaythat is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absense of load. | 0 | Integer | *maxBlockMs* (producer) | The configuration controls how long sending to kafka will block. These methods can be blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata | 60000 | Integer | *maxInFlightRequest* (producer) | The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). | 5 | Integer | *maxRequestSize* (producer) | The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. | 1048576 | Integer | *metadataMaxAgeMs* (producer) | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | *metricReporters* (producer) | A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics. | | String | *metricsSampleWindowMs* (producer) | The number of samples maintained to compute metrics. | 30000 | Integer | *noOfMetricsSample* (producer) | The number of samples maintained to compute metrics. | 2 | Integer | *partitioner* (producer) | The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. | org.apache.kafka.clients.producer.internals.DefaultPartitioner | String | *partitionKey* (producer) | The partition to which the record will be sent (or null if no partition was specified). If this option has been configured then it take precedence over header KafkaConstants#PARTITION_KEY | | Integer | *producerBatchSize* (producer) | The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | *queueBufferingMaxMessages* (producer) | The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped. | 10000 | Integer | *receiveBufferBytes* (producer) | The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. | 65536 | Integer | *reconnectBackoffMs* (producer) | The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all requests sent by the consumer to the broker. | 50 | Integer | *recordMetadata* (producer) | Whether the producer should store the RecordMetadata results from sending to Kafka. The results are stored in a List containing the RecordMetadata metadata's. The list is stored on a header with the key KafkaConstants#KAFKA_RECORDMETA | true | boolean | *requestRequiredAcks* (producer) | The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. | 1 | String | *requestTimeoutMs* (producer) | The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. | 305000 | Integer | *retries* (producer) | Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first. | 0 | Integer | *retryBackoffMs* (producer) | Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. | 100 | Integer | *sendBufferBytes* (producer) | Socket write buffer size | 131072 | Integer | *serializerClass* (producer) | The serializer class for messages. | org.apache.kafka.common.serialization.StringSerializer | String | *workerPool* (producer) | To use a custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | | ExecutorService | *workerPoolCoreSize* (producer) | Number of core threads for the worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | 10 | Integer | *workerPoolMaxSize* (producer) | Maximum number of threads for the worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. | 20 | Integer | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *interceptorClasses* (monitoring) | Sets interceptors for producer or consumers. Producer interceptors have to be classes implementing org.apache.kafka.clients.producer.ProducerInterceptor Consumer interceptors have to be classes implementing org.apache.kafka.clients.consumer.ConsumerInterceptor Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime | | String | *kerberosBeforeReloginMin Time* (security) | Login thread sleep time between refresh attempts. | 60000 | Integer | *kerberosInitCmd* (security) | Kerberos kinit command path. Default is /usr/bin/kinit | /usr/bin/kinit | String | *kerberosPrincipalToLocal Rules* (security) | A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names of the form {username}/{hostname}{REALM} are mapped to {username}. For more details on the format please see the security authorization and acls documentation.. Multiple values can be separated by comma | DEFAULT | String | *kerberosRenewJitter* (security) | Percentage of random jitter added to the renewal time. | 0.05 | Double | *kerberosRenewWindowFactor* (security) | Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | *saslJaasConfig* (security) | Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=USERNAME password=PASSWORD; | | String | *saslKerberosServiceName* (security) | The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config. | | String | *saslMechanism* (security) | The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see a href= http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtmlhttp://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml | GSSAPI | String | *securityProtocol* (security) | Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT and SSL are supported | PLAINTEXT | String | *sslCipherSuites* (security) | A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.By default all the available cipher suites are supported. | | String | *sslContextParameters* (security) | SSL configuration using a Camel SSLContextParameters object. If configured it's applied before the other SSL endpoint parameters. | | SSLContextParameters | *sslEnabledProtocols* (security) | The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. | TLSv1.2,TLSv1.1,TLSv1 | String | *sslEndpointAlgorithm* (security) | The endpoint identification algorithm to validate server hostname using server certificate. | | String | *sslKeymanagerAlgorithm* (security) | The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | *sslKeyPassword* (security) | The password of the private key in the key store file. This is optional for client. | | String | *sslKeystoreLocation* (security) | The location of the key store file. This is optional for client and can be used for two-way authentication for client. | | String | *sslKeystorePassword* (security) | The store password for the key store file.This is optional for client and only needed if ssl.keystore.location is configured. | | String | *sslKeystoreType* (security) | The file format of the key store file. This is optional for client. Default value is JKS | JKS | String | *sslProtocol* (security) | The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. | TLS | String | *sslProvider* (security) | The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | | String | *sslTrustmanagerAlgorithm* (security) | The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | *sslTruststoreLocation* (security) | The location of the trust store file. | | String | *sslTruststoreType* (security) | The file format of the trust store file. Default value is JKS. | JKS | String | *schemaRegistryURL* (confluent) | URL of the Confluent schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in the Confluent documentation. This option is only available in the Confluent Kafka product (not standard Apache Kafka) | | String | *sslTruststorePassword* (security) | The password for the trust store file. | | String |=== // endpoint options: END // spring-boot-auto-configure options: START === Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-kafka-starter x.x.x ---- The component supports 100 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.kafka.allow-manual-commit* | Whether to allow doing manual commits via KafkaManualCommit. If this option is enabled then an instance of KafkaManualCommit is stored on the Exchange message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | Boolean | *camel.component.kafka.break-on-first-error* | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | Boolean | *camel.component.kafka.brokers* | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers. This option is known as bootstrap.servers in the Kafka documentation. | | String | *camel.component.kafka.configuration.allow-manual-commit* | Whether to allow doing manual commits via {@link KafkaManualCommit}.

    If this option is enabled then an instance of {@link KafkaManualCommit} is stored on the {@link Exchange} message header, which allows end users to access this API and perform manual offset commits via the Kafka consumer. | false | Boolean | *camel.component.kafka.configuration.auto-commit-enable* | If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin. | true | Boolean | *camel.component.kafka.configuration.auto-commit-interval-ms* | The frequency in ms that the consumer offsets are committed to zookeeper. | 5000 | Integer | *camel.component.kafka.configuration.auto-commit-on-stop* | Whether to perform an explicit auto commit when the consumer stops to ensure the broker has a commit from the last consumed message. This requires the option autoCommitEnable is turned on. The possible values are: sync, async, or none. And sync is the default value. | sync | String | *camel.component.kafka.configuration.auto-offset-reset* | What to do when there is no initial offset in ZooKeeper or if an offset is out of range: earliest : automatically reset the offset to the earliest offset latest : automatically reset the offset to the latest offset fail: throw exception to the consumer | latest | String | *camel.component.kafka.configuration.break-on-first-error* | This options controls what happens when a consumer is processing an exchange and it fails. If the option is false then the consumer continues to the next message and processes it. If the option is true then the consumer breaks out, and will seek back to offset of the message that caused a failure, and then re-attempt to process this message. However this can lead to endless processing of the same message if its bound to fail every time, eg a poison message. Therefore its recommended to deal with that for example by using Camel's error handler. | false | Boolean | *camel.component.kafka.configuration.bridge-endpoint* | If the option is true, then KafkaProducer will ignore the KafkaConstants.TOPIC header setting of the inbound message. | false | Boolean | *camel.component.kafka.configuration.brokers* | URL of the Kafka brokers to use. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers.

    This option is known as bootstrap.servers in the Kafka documentation. | | String | *camel.component.kafka.configuration.buffer-memory-size* | The total bytes of memory the producer can use to buffer records waiting to be sent to the server. If records are sent faster than they can be delivered to the server the producer will either block or throw an exception based on the preference specified by block.on.buffer.full.This setting should correspond roughly to the total memory the producer will use, but is not a hard bound since not all memory the producer uses is used for buffering. Some additional memory will be used for compression (if compression is enabled) as well as for maintaining in-flight requests. | 33554432 | Integer | *camel.component.kafka.configuration.check-crcs* | Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. | true | Boolean | *camel.component.kafka.configuration.circular-topic-detection* | If the option is true, then KafkaProducer will detect if the message is attempted to be sent back to the same topic it may come from, if the message was original from a kafka consumer. If the KafkaConstants.TOPIC header is the same as the original kafka consumer topic, then the header setting is ignored, and the topic of the producer endpoint is used. In other words this avoids sending the same message back to where it came from. This option is not in use if the option bridgeEndpoint is set to true. | true | Boolean | *camel.component.kafka.configuration.client-id* | The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request. | | String | *camel.component.kafka.configuration.compression-codec* | This parameter allows you to specify the compression codec for all data generated by this producer. Valid values are ""none"", ""gzip"" and ""snappy"". | none | String | *camel.component.kafka.configuration.connection-max-idle-ms* | Close idle connections after the number of milliseconds specified by this config. | 540000 | Integer | *camel.component.kafka.configuration.consumer-request-timeout-ms* | The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted. | 40000 | Integer | *camel.component.kafka.configuration.consumer-streams* | Number of concurrent consumers on the consumer | 10 | Integer | *camel.component.kafka.configuration.consumers-count* | The number of consumers that connect to kafka server | 1 | Integer | *camel.component.kafka.configuration.enable-idempotence* | If set to 'true' the producer will ensure that exactly one copy of each message is written in the stream. If 'false', producer retries may write duplicates of the retried message in the stream. If set to true this option will require max.in.flight.requests.per.connection to be set to 1 and retries cannot be zero and additionally acks must be set to 'all'. | false | Boolean | *camel.component.kafka.configuration.fetch-max-bytes* | The maximum amount of data the server should return for a fetch request This is not an absolute maximum, if the first message in the first non-empty partition of the fetch is larger than this value, the message will still be returned to ensure that the consumer can make progress. The maximum message size accepted by the broker is defined via message.max.bytes (broker config) or max.message.bytes (topic config). Note that the consumer performs multiple fetches in parallel. | 52428800 | Integer | *camel.component.kafka.configuration.fetch-min-bytes* | The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request. | 1 | Integer | *camel.component.kafka.configuration.fetch-wait-max-ms* | The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes | 500 | Integer | *camel.component.kafka.configuration.group-id* | A string that uniquely identifies the group of consumer processes to which this consumer belongs. By setting the same group id multiple processes indicate that they are all part of the same consumer group. This option is required for consumers. | | String | *camel.component.kafka.configuration.header-filter-strategy* | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *camel.component.kafka.configuration.heartbeat-interval-ms* | The expected time between heartbeats to the consumer coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session.timeout.ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. | 3000 | Integer | *camel.component.kafka.configuration.interceptor-classes* | Sets interceptors for producer or consumers. Producer interceptors have to be classes implementing {@link org.apache.kafka.clients.producer.ProducerInterceptor} Consumer interceptors have to be classes implementing {@link org.apache.kafka.clients.consumer.ConsumerInterceptor} Note that if you use Producer interceptor on a consumer it will throw a class cast exception in runtime | | String | *camel.component.kafka.configuration.kafka-header-deserializer* | Sets custom KafkaHeaderDeserializer for deserialization kafka headers values to camel headers values. | | KafkaHeaderDeserializer | *camel.component.kafka.configuration.kafka-header-serializer* | Sets custom KafkaHeaderDeserializer for serialization camel headers values to kafka headers values. | | KafkaHeaderSerializer | *camel.component.kafka.configuration.kerberos-before-relogin-min-time* | Login thread sleep time between refresh attempts. | 60000 | Integer | *camel.component.kafka.configuration.kerberos-init-cmd* | Kerberos kinit command path. Default is /usr/bin/kinit | /usr/bin/kinit | String | *camel.component.kafka.configuration.kerberos-principal-to-local-rules* | A list of rules for mapping from principal names to short names (typically operating system usernames). The rules are evaluated in order and the first rule that matches a principal name is used to map it to a short name. Any later rules in the list are ignored. By default, principal names of the form {username}/{hostname}@{REALM} are mapped to {username}. For more details on the format please see the security authorization and acls documentation..

    Multiple values can be separated by comma | DEFAULT | String | *camel.component.kafka.configuration.kerberos-renew-jitter* | Percentage of random jitter added to the renewal time. | 0.05 | Double | *camel.component.kafka.configuration.kerberos-renew-window-factor* | Login thread will sleep until the specified window factor of time from last refresh to ticket's expiry has been reached, at which time it will try to renew the ticket. | 0.8 | Double | *camel.component.kafka.configuration.key* | The record key (or null if no key is specified). If this option has been configured then it take precedence over header {@link KafkaConstants#KEY} | | String | *camel.component.kafka.configuration.key-deserializer* | Deserializer class for key that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *camel.component.kafka.configuration.key-serializer-class* | The serializer class for keys (defaults to the same as for messages if nothing is given). | org.apache.kafka.common.serialization.StringSerializer | String | *camel.component.kafka.configuration.linger-ms* | The producer groups together any records that arrive in between request transmissions into a single batched request. Normally this occurs only under load when records arrive faster than they can be sent out. However in some circumstances the client may want to reduce the number of requests even under moderate load. This setting accomplishes this by adding a small amount of artificial delay—that is, rather than immediately sending out a record the producer will wait for up to the given delay to allow other records to be sent so that the sends can be batched together. This can be thought of as analogous to Nagle's algorithm in TCP. This setting gives the upper bound on the delay for batching: once we get batch.size worth of records for a partition it will be sent immediately regardless of this setting, however if we have fewer than this many bytes accumulated for this partition we will 'linger' for the specified time waiting for more records to show up. This setting defaults to 0 (i.e. no delay). Setting linger.ms=5, for example, would have the effect of reducing the number of requests sent but would add up to 5ms of latency to records sent in the absense of load. | 0 | Integer | *camel.component.kafka.configuration.max-block-ms* | The configuration controls how long sending to kafka will block. These methods can be blocked for multiple reasons. For e.g: buffer full, metadata unavailable.This configuration imposes maximum limit on the total time spent in fetching metadata, serialization of key and value, partitioning and allocation of buffer memory when doing a send(). In case of partitionsFor(), this configuration imposes a maximum time threshold on waiting for metadata | 60000 | Integer | *camel.component.kafka.configuration.max-in-flight-request* | The maximum number of unacknowledged requests the client will send on a single connection before blocking. Note that if this setting is set to be greater than 1 and there are failed sends, there is a risk of message re-ordering due to retries (i.e., if retries are enabled). | 5 | Integer | *camel.component.kafka.configuration.max-partition-fetch-bytes* | The maximum amount of data per-partition the server will return. The maximum total memory used for a request will be #partitions * max.partition.fetch.bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. | 1048576 | Integer | *camel.component.kafka.configuration.max-poll-interval-ms* | The maximum delay between invocations of poll() when using consumer group management. This places an upper bound on the amount of time that the consumer can be idle before fetching more records. If poll() is not called before expiration of this timeout, then the consumer is considered failed and the group will rebalance in order to reassign the partitions to another member. | | Long | *camel.component.kafka.configuration.max-poll-records* | The maximum number of records returned in a single call to poll() | 500 | Integer | *camel.component.kafka.configuration.max-request-size* | The maximum size of a request. This is also effectively a cap on the maximum record size. Note that the server has its own cap on record size which may be different from this. This setting will limit the number of record batches the producer will send in a single request to avoid sending huge requests. | 1048576 | Integer | *camel.component.kafka.configuration.metadata-max-age-ms* | The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. | 300000 | Integer | *camel.component.kafka.configuration.metric-reporters* | A list of classes to use as metrics reporters. Implementing the MetricReporter interface allows plugging in classes that will be notified of new metric creation. The JmxReporter is always included to register JMX statistics. | | String | *camel.component.kafka.configuration.metrics-sample-window-ms* | The number of samples maintained to compute metrics. | 30000 | Integer | *camel.component.kafka.configuration.no-of-metrics-sample* | The number of samples maintained to compute metrics. | 2 | Integer | *camel.component.kafka.configuration.offset-repository* | The offset repository to use in order to locally store the offset of each partition of the topic. Defining one will disable the autocommit. | | StateRepository | *camel.component.kafka.configuration.partition-assignor* | The class name of the partition assignment strategy that the client will use to distribute partition ownership amongst consumer instances when group management is used | org.apache.kafka.clients.consumer.RangeAssignor | String | *camel.component.kafka.configuration.partition-key* | The partition to which the record will be sent (or null if no partition was specified). If this option has been configured then it take precedence over header {@link KafkaConstants#PARTITION_KEY} | | Integer | *camel.component.kafka.configuration.partitioner* | The partitioner class for partitioning messages amongst sub-topics. The default partitioner is based on the hash of the key. | org.apache.kafka.clients.producer.internals.DefaultPartitioner | String | *camel.component.kafka.configuration.poll-timeout-ms* | The timeout used when polling the KafkaConsumer. | 5000 | Long | *camel.component.kafka.configuration.producer-batch-size* | The producer will attempt to batch records together into fewer requests whenever multiple records are being sent to the same partition. This helps performance on both the client and the server. This configuration controls the default batch size in bytes. No attempt will be made to batch records larger than this size.Requests sent to brokers will contain multiple batches, one for each partition with data available to be sent.A small batch size will make batching less common and may reduce throughput (a batch size of zero will disable batching entirely). A very large batch size may use memory a bit more wastefully as we will always allocate a buffer of the specified batch size in anticipation of additional records. | 16384 | Integer | *camel.component.kafka.configuration.queue-buffering-max-messages* | The maximum number of unsent messages that can be queued up the producer when using async mode before either the producer must be blocked or data must be dropped. | 10000 | Integer | *camel.component.kafka.configuration.receive-buffer-bytes* | The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. | 65536 | Integer | *camel.component.kafka.configuration.reconnect-backoff-max-ms* | The maximum amount of time in milliseconds to wait when reconnecting to a broker that has repeatedly failed to connect. If provided, the backoff per host will increase exponentially for each consecutive connection failure, up to this maximum. After calculating the backoff increase, 20% random jitter is added to avoid connection storms. | 1000 | Integer | *camel.component.kafka.configuration.reconnect-backoff-ms* | The amount of time to wait before attempting to reconnect to a given host. This avoids repeatedly connecting to a host in a tight loop. This backoff applies to all requests sent by the consumer to the broker. | 50 | Integer | *camel.component.kafka.configuration.record-metadata* | Whether the producer should store the {@link RecordMetadata} results from sending to Kafka. The results are stored in a {@link List} containing the {@link RecordMetadata} metadata's. The list is stored on a header with the key {@link KafkaConstants#KAFKA_RECORDMETA} | true | Boolean | *camel.component.kafka.configuration.request-required-acks* | The number of acknowledgments the producer requires the leader to have received before considering a request complete. This controls the durability of records that are sent. The following settings are common: acks=0 If set to zero then the producer will not wait for any acknowledgment from the server at all. The record will be immediately added to the socket buffer and considered sent. No guarantee can be made that the server has received the record in this case, and the retries configuration will not take effect (as the client won't generally know of any failures). The offset given back for each record will always be set to -1. acks=1 This will mean the leader will write the record to its local log but will respond without awaiting full acknowledgement from all followers. In this case should the leader fail immediately after acknowledging the record but before the followers have replicated it then the record will be lost. acks=all This means the leader will wait for the full set of in-sync replicas to acknowledge the record. This guarantees that the record will not be lost as long as at least one in-sync replica remains alive. This is the strongest available guarantee. | 1 | String | *camel.component.kafka.configuration.request-timeout-ms* | The amount of time the broker will wait trying to meet the request.required.acks requirement before sending back an error to the client. | 305000 | Integer | *camel.component.kafka.configuration.retries* | Setting a value greater than zero will cause the client to resend any record whose send fails with a potentially transient error. Note that this retry is no different than if the client resent the record upon receiving the error. Allowing retries will potentially change the ordering of records because if two records are sent to a single partition, and the first fails and is retried but the second succeeds, then the second record may appear first. | 0 | Integer | *camel.component.kafka.configuration.retry-backoff-ms* | Before each retry, the producer refreshes the metadata of relevant topics to see if a new leader has been elected. Since leader election takes a bit of time, this property specifies the amount of time that the producer waits before refreshing the metadata. | 100 | Integer | *camel.component.kafka.configuration.sasl-jaas-config* | Expose the kafka sasl.jaas.config parameter Example: org.apache.kafka.common.security.plain.PlainLoginModule required username=""USERNAME"" password=""PASSWORD""; | | String | *camel.component.kafka.configuration.sasl-kerberos-service-name* | The Kerberos principal name that Kafka runs as. This can be defined either in Kafka's JAAS config or in Kafka's config. | | String | *camel.component.kafka.configuration.sasl-mechanism* | The Simple Authentication and Security Layer (SASL) Mechanism used. For the valid values see http://www.iana.org/assignments/sasl-mechanisms/sasl-mechanisms.xhtml | GSSAPI | String | *camel.component.kafka.configuration.schema-registry-u-r-l* | URL of the Confluent schema registry servers to use. The format is host1:port1,host2:port2. This is known as schema.registry.url in the Confluent documentation. This option is only available in the Confluent Kafka product (not standard Apache Kafka) | | String | *camel.component.kafka.configuration.security-protocol* | Protocol used to communicate with brokers. SASL_PLAINTEXT, PLAINTEXT and SSL are supported | PLAINTEXT | String | *camel.component.kafka.configuration.seek-to* | Set if KafkaConsumer will read from beginning or end on startup: beginning : read from beginning end : read from end This is replacing the earlier property seekToBeginning | | String | *camel.component.kafka.configuration.send-buffer-bytes* | Socket write buffer size | 131072 | Integer | *camel.component.kafka.configuration.serializer-class* | The serializer class for messages. | org.apache.kafka.common.serialization.StringSerializer | String | *camel.component.kafka.configuration.session-timeout-ms* | The timeout used to detect failures when using Kafka's group management facilities. | 10000 | Integer | *camel.component.kafka.configuration.specific-avro-reader* | This enables the use of a specific Avro reader for use with the Confluent schema registry and the io.confluent.kafka.serializers.KafkaAvroDeserializer. This option is only available in the Confluent Kafka product (not standard Apache Kafka) | false | Boolean | *camel.component.kafka.configuration.ssl-cipher-suites* | A list of cipher suites. This is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol.By default all the available cipher suites are supported. | | String | *camel.component.kafka.configuration.ssl-context-parameters* | SSL configuration using a Camel {@link SSLContextParameters} object. If configured it's applied before the other SSL endpoint parameters. | | SSLContextParameters | *camel.component.kafka.configuration.ssl-enabled-protocols* | The list of protocols enabled for SSL connections. TLSv1.2, TLSv1.1 and TLSv1 are enabled by default. | TLSv1.2,TLSv1.1,TLSv1 | String | *camel.component.kafka.configuration.ssl-endpoint-algorithm* | The endpoint identification algorithm to validate server hostname using server certificate. | | String | *camel.component.kafka.configuration.ssl-key-password* | The password of the private key in the key store file. This is optional for client. | | String | *camel.component.kafka.configuration.ssl-keymanager-algorithm* | The algorithm used by key manager factory for SSL connections. Default value is the key manager factory algorithm configured for the Java Virtual Machine. | SunX509 | String | *camel.component.kafka.configuration.ssl-keystore-location* | The location of the key store file. This is optional for client and can be used for two-way authentication for client. | | String | *camel.component.kafka.configuration.ssl-keystore-password* | The store password for the key store file.This is optional for client and only needed if ssl.keystore.location is configured. | | String | *camel.component.kafka.configuration.ssl-keystore-type* | The file format of the key store file. This is optional for client. Default value is JKS | JKS | String | *camel.component.kafka.configuration.ssl-protocol* | The SSL protocol used to generate the SSLContext. Default setting is TLS, which is fine for most cases. Allowed values in recent JVMs are TLS, TLSv1.1 and TLSv1.2. SSL, SSLv2 and SSLv3 may be supported in older JVMs, but their usage is discouraged due to known security vulnerabilities. | TLS | String | *camel.component.kafka.configuration.ssl-provider* | The name of the security provider used for SSL connections. Default value is the default security provider of the JVM. | | String | *camel.component.kafka.configuration.ssl-trustmanager-algorithm* | The algorithm used by trust manager factory for SSL connections. Default value is the trust manager factory algorithm configured for the Java Virtual Machine. | PKIX | String | *camel.component.kafka.configuration.ssl-truststore-location* | The location of the trust store file. | | String | *camel.component.kafka.configuration.ssl-truststore-password* | The password for the trust store file. | | String | *camel.component.kafka.configuration.ssl-truststore-type* | The file format of the trust store file. Default value is JKS. | JKS | String | *camel.component.kafka.configuration.topic* | Name of the topic to use. On the consumer you can use comma to separate multiple topics. A producer can only send a message to a single topic. | | String | *camel.component.kafka.configuration.topic-is-pattern* | Whether the topic is a pattern (regular expression). This can be used to subscribe to dynamic number of topics matching the pattern. | false | Boolean | *camel.component.kafka.configuration.value-deserializer* | Deserializer class for value that implements the Deserializer interface. | org.apache.kafka.common.serialization.StringDeserializer | String | *camel.component.kafka.configuration.worker-pool* | To use a custom worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | | ExecutorService | *camel.component.kafka.configuration.worker-pool-core-size* | Number of core threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | 10 | Integer | *camel.component.kafka.configuration.worker-pool-max-size* | Maximum number of threads for the worker pool for continue routing {@link Exchange} after kafka server has acknowledge the message that was sent to it from {@link KafkaProducer} using asynchronous non-blocking processing. | 20 | Integer | *camel.component.kafka.enabled* | Enable kafka component | true | Boolean | *camel.component.kafka.kafka-manual-commit-factory* | Factory to use for creating KafkaManualCommit instances. This allows to plugin a custom factory to create custom KafkaManualCommit instances in case special logic is needed when doing manual commits that deviates from the default implementation that comes out of the box. The option is a org.apache.camel.component.kafka.KafkaManualCommitFactory type. | | String | *camel.component.kafka.resolve-property-placeholders* | Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders. | true | Boolean | *camel.component.kafka.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean | *camel.component.kafka.worker-pool* | To use a shared custom worker pool for continue routing Exchange after kafka server has acknowledge the message that was sent to it from KafkaProducer using asynchronous non-blocking processing. If using this option then you must handle the lifecycle of the thread pool to shut the pool down when no longer needed. The option is a java.util.concurrent.ExecutorService type. | | String |=== // spring-boot-auto-configure options: END For more information about Producer/Consumer configuration: http://kafka.apache.org/documentation.html#newconsumerconfigs[http://kafka.apache.org/documentation.html#newconsumerconfigs] http://kafka.apache.org/documentation.html#producerconfigs[http://kafka.apache.org/documentation.html#producerconfigs] === Message headers ==== Consumer headers The following headers are available when consuming messages from Kafka. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.TOPIC | ""kafka.TOPIC"" | String | The topic from where the message originated | KafkaConstants.PARTITION | ""kafka.PARTITION"" | Integer | The partition where the message was stored | KafkaConstants.OFFSET | ""kafka.OFFSET"" | Long | The offset of the message | KafkaConstants.KEY | ""kafka.KEY"" | Object | The key of the message if configured | KafkaConstants.HEADERS | ""kafka.HEADERS"" | org.apache.kafka.common.header.Headers | The record headers | KafkaConstants.LAST_RECORD_BEFORE_COMMIT | ""kafka.LAST_RECORD_BEFORE_COMMIT"" | Boolean | Whether or not it's the last record before commit (only available if `autoCommitEnable` endpoint parameter is `false`) | KafkaConstants.MANUAL_COMMIT | ""CamelKafkaManualCommit"" | KafkaManualCommit | Can be used for forcing manual offset commit when using Kafka consumer. | |=== ==== Producer headers Before sending a message to Kafka you can configure the following headers. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.KEY | ""kafka.KEY"" | Object | *Required* The key of the message in order to ensure that all related message goes in the same partition | KafkaConstants.TOPIC | ""kafka.TOPIC"" | String | The topic to which send the message (only read if the `bridgeEndpoint` endpoint parameter is `true`) | KafkaConstants.PARTITION_KEY | ""kafka.PARTITION_KEY"" | Integer | Explicitly specify the partition (only used if the `KafkaConstants.KEY` header is defined) |=== After the message is sent to Kafka, the following headers are available [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | KafkaConstants.KAFKA_RECORDMETA | ""org.apache.kafka.clients.producer.RecordMetadata"" | List | The metadata (only configured if `recordMetadata` endpoint parameter is `true` |=== === Samples ==== Consuming messages from Kafka Here is the minimal route you need in order to read messages from Kafka. [source,java] ---- from(""kafka:test?brokers=localhost:9092"") .log(""Message received from Kafka : ${body}"") .log("" on the topic ${headers[kafka.TOPIC]}"") .log("" on the partition ${headers[kafka.PARTITION]}"") .log("" with the offset ${headers[kafka.OFFSET]}"") .log("" with the key ${headers[kafka.KEY]}"") ---- If you need to consume messages from multiple topics you can use a comma separated list of topic names [source,java] ---- from(""kafka:test,test1,test2?brokers=localhost:9092"") .log(""Message received from Kafka : ${body}"") .log("" on the topic ${headers[kafka.TOPIC]}"") .log("" on the partition ${headers[kafka.PARTITION]}"") .log("" with the offset ${headers[kafka.OFFSET]}"") .log("" with the key ${headers[kafka.KEY]}"") ---- When consuming messages from Kafka you can use your own offset management and not delegate this management to Kafka. In order to keep the offsets the component needs a `StateRepository` implementation such as `FileStateRepository`. This bean should be available in the registry. Here how to use it : [source,java] ---- // Create the repository in which the Kafka offsets will be persisted FileStateRepository repository = FileStateRepository.fileStateRepository(new File(""/path/to/repo.dat"")); // Bind this repository into the Camel registry JndiRegistry registry = new JndiRegistry(); registry.bind(""offsetRepo"", repository); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + // Setup the topic and broker address ""&groupId=A"" + // The consumer processor group ID ""&autoOffsetReset=earliest"" + // Ask to start from the beginning if we have unknown offset ""&offsetRepository=#offsetRepo"") // Keep the offsets in the previously configured repository .to(""mock:result""); } }); ----   ==== Producing messages to Kafka Here is the minimal route you need in order to write messages to Kafka. [source,java] ---- from(""direct:start"") .setBody(constant(""Message from Camel"")) // Message to send .setHeader(KafkaConstants.KEY, constant(""Camel"")) // Key of the message .to(""kafka:test?brokers=localhost:9092""); ---- === SSL configuration You have 2 different ways to configure the SSL communication on the Kafka` component. The first way is through the many SSL endpoint parameters [source,java] ---- from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + ""&groupId=A"" + ""&sslKeystoreLocation=/path/to/keystore.jks"" + ""&sslKeystorePassword=changeit"" + ""&sslKeyPassword=changeit"" + ""&securityProtocol=SSL"") .to(""mock:result""); ---- The second way is to use the `sslContextParameters` endpoint parameter. [source,java] ---- // Configure the SSLContextParameters object KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/path/to/keystore.jks""); ksp.setPassword(""changeit""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""changeit""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); // Bind this SSLContextParameters into the Camel registry JndiRegistry registry = new JndiRegistry(); registry.bind(""ssl"", scp); // Configure the camel context DefaultCamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from(""kafka:"" + TOPIC + ""?brokers=localhost:{{kafkaPort}}"" + // Setup the topic and broker address ""&groupId=A"" + // The consumer processor group ID ""&sslContextParameters=#ssl"" + // The security protocol ""&securityProtocol=SSL) // Reference the SSL configuration .to(""mock:result""); } }); ---- === Using the Kafka idempotent repository *Available from Camel 2.19* The `camel-kafka` library provides a Kafka topic-based idempotent repository. This repository stores broadcasts all changes to idempotent state (add/remove) in a Kafka topic, and populates a local in-memory cache for each repository's process instance through event sourcing. The topic used must be unique per idempotent repository instance. The mechanism does not have any requirements about the number of topic partitions; as the repository consumes from all partitions at the same time. It also does not have any requirements about the replication factor of the topic. Each repository instance that uses the topic (e.g. typically on different machines running in parallel) controls its own consumer group, so in a cluster of 10 Camel processes using the same topic each will control its own offset. On startup, the instance subscribes to the topic and rewinds the offset to the beginning, rebuilding the cache to the latest state. The cache will not be considered warmed up until one poll of `pollDurationMs` in length returns 0 records. Startup will not be completed until either the cache has warmed up, or 30 seconds go by; if the latter happens the idempotent repository may be in an inconsistent state until its consumer catches up to the end of the topic. A `KafkaIdempotentRepository` has the following properties: [width=""100%"",cols=""2m,5"",options=""header""] |=== | Property | Description | topic | The name of the Kafka topic to use to broadcast changes. (required) | bootstrapServers | The `bootstrap.servers` property on the internal Kafka producer and consumer. Use this as shorthand if not setting `consumerConfig` and `producerConfig`. If used, this component will apply sensible default configurations for the producer and consumer. | producerConfig | Sets the properties that will be used by the Kafka producer that broadcasts changes. Overrides `bootstrapServers`, so must define the Kafka `bootstrap.servers` property itself | consumerConfig | Sets the properties that will be used by the Kafka consumer that populates the cache from the topic. Overrides `bootstrapServers`, so must define the Kafka `bootstrap.servers` property itself | maxCacheSize | How many of the most recently used keys should be stored in memory (default 1000). | pollDurationMs | The poll duration of the Kafka consumer. The local caches are updated immediately. This value will affect how far behind other peers that update their caches from the topic are relative to the idempotent consumer instance that sent the cache action message. The default value of this is 100 ms. + If setting this value explicitly, be aware that there is a tradeoff between the remote cache liveness and the volume of network traffic between this repository's consumer and the Kafka brokers. The cache warmup process also depends on there being one poll that fetches nothing - this indicates that the stream has been consumed up to the current point. If the poll duration is excessively long for the rate at which messages are sent on the topic, there exists a possibility that the cache cannot be warmed up and will operate in an inconsistent state relative to its peers until it catches up. |=== The repository can be instantiated by defining the `topic` and `bootstrapServers`, or the `producerConfig` and `consumerConfig` property sets can be explicitly defined to enable features such as SSL/SASL. To use, this repository must be placed in the Camel registry, either manually or by registration as a bean in Spring/Blueprint, as it is `CamelContext` aware. Sample usage is as follows: [source,java] ---- KafkaIdempotentRepository kafkaIdempotentRepository = new KafkaIdempotentRepository(""idempotent-db-inserts"", ""localhost:9091""); SimpleRegistry registry = new SimpleRegistry(); registry.put(""insertDbIdemRepo"", kafkaIdempotentRepository); // must be registered in the registry, to enable access to the CamelContext CamelContext context = new CamelContext(registry); // later in RouteBuilder... from(""direct:performInsert"") .idempotentConsumer(header(""id"")).messageIdRepositoryRef(""insertDbIdemRepo"") // once-only insert into database .end() ---- In XML: [source,xml] ---- localhost:9091 localhost:9091 ---- === Using manual commit with Kafka consumer *Available as of Camel 2.21* By default the Kafka consumer will use auto commit, where the offset will be committed automatically in the background using a given interval. In case you want to force manual commits, you can use `KafkaManualCommit` API from the Camel Exchange, stored on the message header. This requires to turn on manual commits by either setting the option `allowManualCommit` to `true` on the `KafkaComponent` or on the endpoint, for example: [source,java] ---- KafkaComponent kafka = new KafkaComponent(); kafka.setAllowManualCommit(true); ... camelContext.addComponent(""kafka"", kafka); ---- You can then use the `KafkaManualCommit` from Java code such as a Camel `Processor`: [source,java] ---- public void process(Exchange exchange) { KafkaManualCommit manual = exchange.getIn().getHeader(KafkaConstants.MANUAL_COMMIT, KafkaManualCommit.class); manual.commitSync(); } ---- This will force a synchronous commit which will block until the commit is acknowledge on Kafka, or if it fails an exception is thrown. If you want to use a custom implementation of `KafkaManualCommit` then you can configure a custom `KafkaManualCommitFactory` on the `KafkaComponent` that creates instances of your custom implementation. === Kafka Headers propagation *Available as of Camel 2.22* When consuming messages from Kafka, headers will be propagated to camel exchange headers automatically. Producing flow backed by same behaviour - camel headers of particular exchange will be propagated to kafka message headers. Since kafka headers allows only `byte[]` values, in order camel exchnage header to be propagated its value should be serialized to `bytes[]`, otherwise header will be skipped. Following header value types are supported: `String`, `Integer`, `Long`, `Double`, `Boolean`, `byte[]`. Note: all headers propagated *from* kafka *to* camel exchange will contain `byte[]` value by default. In order to override default functionality uri parameters can be set: `kafkaHeaderDeserializer` for `from` route and `kafkaHeaderSerializer` for `to` route. Example: ``` from(""kafka:my_topic?kafkaHeaderDeserializer=#myDeserializer"") ... .to(""kafka:my_topic?kafkaHeaderSerializer=#mySerializer"") ``` By default all headers are being filtered by `KafkaHeaderFilterStrategy`. Strategy filters out headers which start with `Camel` or `org.apache.camel` prefixes. Default strategy can be overridden by using `headerFilterStrategy` uri parameter in both `to` and `from` routes: ``` from(""kafka:my_topic?headerFilterStrategy=#myStrategy"") ... .to(""kafka:my_topic?headerFilterStrategy=#myStrategy"") ``` `myStrategy` object should be subclass of `HeaderFilterStrategy` and must be placed in the Camel registry, either manually or by registration as a bean in Spring/Blueprint, as it is `CamelContext` aware. ",16261,True,3444.3562135094653,median "/** * VERSION: 1.697 * DATE: 2012-02-23 * AS3 (AS2 version is also available) * UPDATES AND DOCS AT: http://www.greensock.com/timelinemax/ **/ package com.greensock { import com.greensock.core.*; import com.greensock.events.TweenEvent; import flash.events.*; /** * TimelineMax extends TimelineLite, offering exactly the same functionality plus useful * (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, * currentLabel, addCallback(), removeCallback(), tweenTo(), tweenFromTo(), getLabelAfter(), getLabelBefore(), * and getActive() (and probably more in the future). It is the ultimate sequencing tool. * Think of a TimelineMax instance like a virtual MovieClip timeline or a container where * you place tweens (or other timelines) over the course of time. You can: * *

      *
    • build sequences easily by adding tweens with the append(), prepend(), insert(), appendMultiple(), * prependMultiple(), and insertMultiple() methods. Tweens can overlap as much as you want and you have * complete control over where they get placed on the timeline.
    • * *
    • add labels, play(), stop(), gotoAndPlay(), gotoAndStop(), restart(), tweenTo() and even reverse()!
    • * *
    • nest timelines within timelines as deeply as you want.
    • * *
    • set the progress of the timeline using its currentProgress property. For example, to skip to * the halfway point, set myTimeline.currentProgress = 0.5.
    • * *
    • tween the currentTime, totalTime, currentProgress, or totalProgress * property to fastforward/rewind the timeline. You could * even attach a slider to one of these properties to give the user the ability to drag * forwards/backwards through the whole timeline.
    • * *
    • add onStart, onUpdate, onComplete, onReverseComplete, and/or onRepeat callbacks using the * constructor's vars object.
    • * *
    • speed up or slow down the entire timeline with its timeScale property. You can even tween * this property to gradually speed up or slow down the timeline.
    • * *
    • use the insertMultiple(), appendMultiple(), or prependMultiple() methods to create * complex sequences including various alignment modes and staggering capabilities. * Works great in conjunction with TweenMax.allTo() too.
    • * *
    • base the timing on frames instead of seconds if you prefer. Please note, however, that * the timeline's timing mode dictates its childrens' timing mode as well.
    • * *
    • kill the tweens of a particular object inside the timeline with killTweensOf() or get the tweens of an object * with getTweensOf() or get all the tweens/timelines in the timeline with getChildren()
    • * *
    • set the timeline to repeat any number of times or indefinitely. You can even set a delay * between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse * every other cycle.
    • * *
    • listen for START, UPDATE, REPEAT, REVERSE_COMPLETE, and COMPLETE events.
    • * *
    • get the active tweens in the timeline with getActive().
    • * *
    • add callbacks (function calls) anywhere in the timeline that call a function of your choosing when * the ""virtual playhead"" passes a particular spot.
    • * *
    • Get the currentLabel or find labels at various positions in the timeline * using getLabelAfter() and getLabelBefore()
    • *
    * * EXAMPLE:

    * * import com.greensock.~~;

    * * //create the timeline and add an onComplete call to myFunction when the timeline completes
    * var myTimeline:TimelineMax = new TimelineMax({onComplete:myFunction});

    * * //add a tween
    * myTimeline.append(new TweenLite(mc, 1, {x:200, y:100}));

    * * //add another tween at the end of the timeline (makes sequencing easy)
    * myTimeline.append(new TweenLite(mc, 0.5, {alpha:0}));

    * * //repeat the entire timeline twice
    * myTimeline.repeat = 2;

    * * //delay the repeat by 0.5 seconds each time.
    * myTimeline.repeatDelay = 0.5;

    * * //pause the timeline (stop() works too)
    * myTimeline.pause();

    * * //reverse it anytime...
    * myTimeline.reverse();

    * * //Add a ""spin"" label 3-seconds into the timeline.
    * myTimeline.addLabel(""spin"", 3);

    * * //insert a rotation tween at the ""spin"" label (you could also define the insert point as the time instead of a label)
    * myTimeline.insert(new TweenLite(mc, 2, {rotation:""360""}), ""spin"");

    * * //go to the ""spin"" label and play the timeline from there...
    * myTimeline.gotoAndPlay(""spin"");

    * * //call myCallbackwhen the ""virtual playhead"" travels past the 1.5-second point. * myTimeline.addCallback(myCallback, 1.5); * * //add a tween to the beginning of the timeline, pushing all the other existing tweens back in time
    * myTimeline.prepend(new TweenMax(mc, 1, {tint:0xFF0000}));

    * * //nest another TimelineMax inside your timeline...
    * var nestedTimeline:TimelineMax = new TimelineMax();
    * nestedTimeline.append(new TweenLite(mc2, 1, {x:200}));
    * myTimeline.append(nestedTimeline);

    * * * insertMultiple() and appendMultiple() provide some very powerful sequencing tools as well, * allowing you to add an Array of tweens/timelines and optionally align them with SEQUENCE or START * modes, and even stagger them if you want. For example, to insert 3 tweens into the timeline, aligning their start times but * staggering them by 0.2 seconds,

    * * myTimeline.insertMultiple([new TweenLite(mc, 1, {y:""100""}), * new TweenLite(mc2, 1, {x:120}), * new TweenLite(mc3, 1, {alpha:0.5})], * 0, * TweenAlign.START, * 0.2);

    * * You can use the constructor's vars object to do all the setup too, like:

    * * var myTimeline:TimelineMax = new TimelineMax({tweens:[new TweenLite(mc1, 1, {y:""100""}), TweenMax.to(mc2, 1, {tint:0xFF0000})], align:TweenAlign.SEQUENCE, onComplete:myFunction, repeat:2, repeatDelay:1});

    * * If that confuses you, don't worry. Just use the append(), insert(), and prepend() methods to build your * sequence. But power users will likely appreciate the quick, compact way they can set up sequences now.

    * * * NOTES: *
      *
    • TimelineMax automatically inits the OverwriteManager class to prevent unexpected overwriting behavior in sequences. * The default mode is AUTO, but you can set it to whatever you want with OverwriteManager.init() * (see http://www.greensock.com/overwritemanager/)
    • *
    • TimelineMax adds about 4.9k to your SWF (not including OverwriteManager).
    • *
    * * Copyright 2012, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com **/ public class TimelineMax extends TimelineLite implements IEventDispatcher { /** @private **/ public static const version:Number = 1.697; /** @private **/ protected var _repeat:int; /** @private **/ protected var _repeatDelay:Number; /** @private **/ protected var _cyclesComplete:int; /** @private **/ protected var _dispatcher:EventDispatcher; /** @private **/ protected var _hasUpdateListener:Boolean; /** * Works in conjunction with the repeat property, determining the behavior of each cycle; when yoyo is true, * the timeline will go back and forth, appearing to reverse every other cycle (this has no affect on the reversed property though). * So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. * But if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. **/ public var yoyo:Boolean; /** * Constructor.

    * * SPECIAL PROPERTIES
    * The following special properties may be passed in via the constructor's vars parameter, like * new TimelineMax({paused:true, onComplete:myFunction, repeat:2, yoyo:true}) * *
      *
    • delay : Number Amount of delay in seconds (or frames for frames-based timelines) before the timeline should begin.
    • * *
    • useFrames : Boolean If useFrames is set to true, the timeline's timing mode will be based on frames. * Otherwise, it will be based on seconds/time. NOTE: a TimelineLite's timing mode is * always determined by its parent timeline.
    • * *
    • paused : Boolean Sets the initial paused state of the timeline (by default, timelines automatically begin playing immediately)
    • * *
    • reversed : Boolean If true, the timeline will be reversed initially. This does NOT force it to the very end and start * playing backwards. It simply affects the orientation of the timeline, so if reversed is set to * true initially, it will appear not to play because it is already at the beginning. To cause it to * play backwards from the end, set reversed to true and then set the currentProgress property to 1 immediately * after creating the timeline.
    • * *
    • tweens : Array To immediately insert several tweens into the timeline, use the tweens special property * to pass in an Array of TweenLite/TweenMax/TimelineLite/TimelineMax instances. You can use this in conjunction * with the align and stagger special properties to set up complex sequences with minimal code. * These values simply get passed to the insertMultiple() method.
    • * *
    • align : String Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately through the constructor. The value simply gets passed to the * insertMultiple() method. The default is TweenAlign.NORMAL. Options are: *
        *
      • TweenAlign.SEQUENCE: aligns the tweens one-after-the-other in a sequence
      • *
      • TweenAlign.START: aligns the start times of all of the tweens (ignores delays)
      • *
      • TweenAlign.NORMAL: aligns the start times of all the tweens (honors delays)
      • *
      The align special property does not force all child tweens/timelines to maintain * relative positioning, so for example, if you use TweenAlign.SEQUENCE and then later change the duration * of one of the nested tweens, it does not force all subsequent timelines to change their position * on the timeline. The align special property only affects the alignment of the tweens that are * initially placed into the timeline through the tweens special property of the vars object.
    • * *
    • stagger : Number Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately. It staggers the tweens by a set amount of time (in seconds) (or * in frames if useFrames is true). For example, if the stagger value is 0.5 and the align * property is set to TweenAlign.START, the second tween will start 0.5 seconds after the first one * starts, then 0.5 seconds later the third one will start, etc. If the align property is * TweenAlign.SEQUENCE, there would be 0.5 seconds added between each tween. This value simply gets * passed to the insertMultiple() method. Default is 0.
    • * *
    • onStart : Function A function that should be called when the timeline begins (the currentProgress won't necessarily * be zero when onStart is called. For example, if the timeline is created and then its currentProgress * property is immediately set to 0.5 or if its currentTime property is set to something other than zero, * onStart will still get fired because it is the first time the timeline is getting rendered.)
    • * *
    • onStartParams : Array An Array of parameters to pass the onStart function.
    • * *
    • onUpdate : Function A function that should be called every time the timeline's time/position is updated * (on every frame while the timeline is active)
    • * *
    • onUpdateParams : Array An Array of parameters to pass the onUpdate function
    • * *
    • onComplete : Function A function that should be called when the timeline has finished
    • * *
    • onCompleteParams : Array An Array of parameters to pass the onComplete function
    • * *
    • onReverseComplete : Function A function that should be called when the timeline has reached its starting point again after having been reversed
    • * *
    • onReverseCompleteParams : Array An Array of parameters to pass the onReverseComplete functions
    • * *
    • onRepeat : Function A function that should be called every time the timeline repeats
    • * *
    • onRepeatParams : Array An Array of parameters to pass the onRepeat function
    • * *
    • autoRemoveChildren : Boolean If autoRemoveChildren is set to true, as soon as child tweens/timelines complete, * they will automatically get killed/removed. This is normally undesireable because * it prevents going backwards in time (like if you want to reverse() or set the * currentProgress value to a lower value, etc.). It can, however, improve speed and memory * management. TweenLite's root timelines use autoRemoveChildren:true.
    • * *
    • repeat : int Number of times that the timeline should repeat. To repeat indefinitely, use -1.
    • * *
    • repeatDelay : Number Amount of time in seconds (or frames for frames-based timelines) between repeats.
    • * *
    • yoyo : Boolean Works in conjunction with the repeat property, determining the behavior of each * cycle. When yoyo is true, the timeline will go back and forth, appearing to reverse * every other cycle (this has no affect on the reversed property though). So if repeat is * 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But * if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
    • * *
    • onStartListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it begins. * This is the same as doing myTimeline.addEventListener(TweenEvent.START, myFunction);
    • * *
    • onUpdateListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent every time it * updates values. This is the same as doing myTimeline.addEventListener(TweenEvent.UPDATE, myFunction);
    • * *
    • onCompleteListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it completes. * This is the same as doing myTimeline.addEventListener(TweenEvent.COMPLETE, myFunction);
    • *
    * * @param vars optionally pass in special properties like useFrames, onComplete, onCompleteParams, onUpdate, onUpdateParams, onStart, onStartParams, tweens, align, stagger, delay, autoRemoveChildren, onCompleteListener, onStartListener, onUpdateListener, repeat, repeatDelay, and/or yoyo. */ public function TimelineMax(vars:Object=null) { super(vars); _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; _cyclesComplete = 0; this.yoyo = Boolean(this.vars.yoyo == true); this.cacheIsDirty = true; if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } } /** * If you want a function to be called at a particular time or label, use addCallback. When you add * a callback, it is technically considered a zero-duration tween, so if you getChildren() there will be * a tween returned for each callback. You can discern a callback from other tweens by the fact that * their target is a function and the duration is zero. * * @param function the function to be called * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label at which the callback should be inserted. For example, myTimeline.addCallback(myFunction, 3) would call myFunction() 3-seconds into the timeline, and myTimeline.addCallback(myFunction, ""myLabel"") would call it at the ""myLabel"" label. * @param params an Array of parameters to pass the callback * @return com.greensock.TweenLite instance */ public function addCallback(callback:Function, timeOrLabel:*, params:Array=null):TweenLite { var cb:TweenLite = new TweenLite(callback, 0, {onComplete:callback, onCompleteParams:params, overwrite:0, immediateRender:false}); insert(cb, timeOrLabel); return cb; } /** * Removes a callback from a particular time or label. If timeOrLabel is null, all callbacks of that * particular function are removed from the timeline. * * @param function callback function to be removed * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label from which the callback should be removed. For example, myTimeline.removeCallback(myFunction, 3) would remove the callback from 3-seconds into the timeline, and myTimeline.removeCallback(myFunction, ""myLabel"") would remove it from the ""myLabel"" label, and myTimeline.removeCallback(myFunction, null) would remove ALL callbacks of that function regardless of where they are on the timeline. * @return true if any callbacks were successfully found and removed. false otherwise. */ public function removeCallback(callback:Function, timeOrLabel:*=null):Boolean { if (timeOrLabel == null) { return killTweensOf(callback, false); } else { if (typeof(timeOrLabel) == ""string"") { if (!(timeOrLabel in _labels)) { return false; } timeOrLabel = _labels[timeOrLabel]; } var a:Array = getTweensOf(callback, false), success:Boolean; var i:int = a.length; while (--i > -1) { if (a[i].cachedStartTime == timeOrLabel) { remove(a[i] as TweenCore); success = true; } } return success; } } /** * Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops. For * example, to make the TimelineMax play to the ""myLabel2"" label, simply do:

    * * myTimeline.tweenTo(""myLabel2"");

    * * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween to the 5-second point on the * timeline and then call a function named myFunction and pass in a parameter that's references this * TimelineMax and use a Strong.easeOut ease, you'd do:

    * * myTimeline.tweenTo(5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

    * * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method.

    * * If you plan to sequence multiple playhead tweens one-after-the-other, it is typically better to use * tweenFromTo() so that you can define the starting point and ending point, allowing the * duration to be accurately determined immediately. * * @see #tweenFromTo() * @param timeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(5) would play from wherever the timeline is currently to the 5-second point whereas myTimeline.tweenTo(""myLabel"") would play to wherever ""myLabel"" is on the timeline. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenTo() sets it internally) * @return com.greensock.TweenLite instance that handles tweening the timeline to the desired time/label. */ public function tweenTo(timeOrLabel:*, vars:Object=null):TweenLite { var varsCopy:Object = {ease:easeNone, overwrite:2, useFrames:this.useFrames, immediateRender:false}; for (var p:String in vars) { varsCopy[p] = vars[p]; } varsCopy.onInit = onInitTweenTo; varsCopy.onInitParams = [null, this, NaN]; varsCopy.currentTime = parseTimeOrLabel(timeOrLabel); var tl:TweenLite = new TweenLite(this, (Math.abs(Number(varsCopy.currentTime) - this.cachedTime) / this.cachedTimeScale) || 0.001, varsCopy); tl.vars.onInitParams[0] = tl; return tl; } /** * Creates a linear tween that essentially scrubs the playhead from a particular time or label to another * time or label and then stops. If you plan to sequence multiple playhead tweens one-after-the-other, * tweenFromTo() is better to use than tweenTo() because it allows the duration * to be determined immediately, ensuring that subsequent tweens that are appended to a sequence are * positioned appropriately. For example, to make the TimelineMax play from the label ""myLabel1"" to the ""myLabel2"" * label, and then from ""myLabel2"" back to the beginning (a time of 0), simply do:

    * * var playheadTweens:TimelineMax = new TimelineMax();
    * playheadTweens.append( myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") );
    * playheadTweens.append( myTimeline.tweenFromTo(""myLabel2"", 0);

    * * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween from the start (0) to the * 5-second point on the timeline and then call a function named myFunction and pass in a parameter * that's references this TimelineMax and use a Strong.easeOut ease, you'd do:

    * * myTimeline.tweenFromTo(0, 5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

    * * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenFromTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenFromTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method. * * @see #tweenTo() * @param fromTimeOrLabel The beginning time in seconds (or frame if the timeline is frames-based) or label from which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param toTimeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenFromTo() sets it internally) * @return com.greensock.TweenLite instance that handles tweening the timeline between the desired times/labels. */ public function tweenFromTo(fromTimeOrLabel:*, toTimeOrLabel:*, vars:Object=null):TweenLite { var tl:TweenLite = tweenTo(toTimeOrLabel, vars); tl.vars.onInitParams[2] = parseTimeOrLabel(fromTimeOrLabel); tl.duration = Math.abs(Number(tl.vars.currentTime) - tl.vars.onInitParams[2]) / this.cachedTimeScale; return tl; } /** @private **/ private static function onInitTweenTo(tween:TweenLite, timeline:TimelineMax, fromTime:Number):void { timeline.paused = true; if (!isNaN(fromTime)) { timeline.currentTime = fromTime; } if (tween.vars.currentTime != timeline.currentTime) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. tween.duration = Math.abs(Number(tween.vars.currentTime) - timeline.currentTime) / timeline.cachedTimeScale; } } /** @private **/ private static function easeNone(t:Number, b:Number, c:Number, d:Number):Number { return t / d; } /** @private **/ override public function renderTime(time:Number, suppressEvents:Boolean=false, force:Boolean=false):void { if (this.gc) { this.setEnabled(true, false); } else if (!this.active && !this.cachedPaused) { this.active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. } var totalDur:Number = (this.cacheIsDirty) ? this.totalDuration : this.cachedTotalDuration, prevTime:Number = this.cachedTime, prevTotalTime:Number = this.cachedTotalTime, prevStart:Number = this.cachedStartTime, prevTimeScale:Number = this.cachedTimeScale, tween:TweenCore, isComplete:Boolean, rendered:Boolean, repeated:Boolean, next:TweenCore, dur:Number, prevPaused:Boolean = this.cachedPaused; if (time >= totalDur) { if (prevTotalTime != totalDur && _rawPrevTime != time) { this.cachedTotalTime = totalDur; if (!this.cachedReversed && this.yoyo && _repeat % 2 != 0) { this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); } else { this.cachedTime = this.cachedDuration; forceChildrenToEnd(this.cachedDuration, suppressEvents); } isComplete = !this.hasPausedChild() && !this.cachedReversed; rendered = true; if (this.cachedDuration == 0 && isComplete && (time == 0 || _rawPrevTime < 0)) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; } } } else if (time <= 0) { if (time < 0) { this.active = false; if (this.cachedDuration == 0 && _rawPrevTime > 0) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; isComplete = true; } } else if (time == 0 && !this.initted) { force = true; } if (prevTotalTime != 0 && _rawPrevTime != time) { this.cachedTotalTime = 0; this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); rendered = true; if (this.cachedReversed) { isComplete = true; } } } else { this.cachedTotalTime = this.cachedTime = time; } _rawPrevTime = time; if (_repeat != 0) { var cycleDuration:Number = this.cachedDuration + _repeatDelay; var prevCycles:int = _cyclesComplete; if ((_cyclesComplete = (this.cachedTotalTime / cycleDuration) >> 0) == (this.cachedTotalTime / cycleDuration) && _cyclesComplete != 0) { _cyclesComplete--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } repeated = Boolean(prevCycles != _cyclesComplete); if (isComplete) { if (this.yoyo && _repeat % 2) { this.cachedTime = 0; } } else if (time > 0) { this.cachedTime = this.cachedTotalTime - (_cyclesComplete * cycleDuration); //originally this.cachedTotalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!) if (this.yoyo && _cyclesComplete % 2) { this.cachedTime = this.cachedDuration - this.cachedTime; } else if (this.cachedTime >= this.cachedDuration) { this.cachedTime = this.cachedDuration; } if (this.cachedTime < 0) { this.cachedTime = 0; } } else { _cyclesComplete = 0; } if (repeated && !isComplete && (this.cachedTotalTime != prevTotalTime || force)) { /* make sure children at the end/beginning of the timeline are rendered properly. If, for example, a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So we need to push the timeline to the end (and/or beginning depending on its yoyo value). */ var forward:Boolean = Boolean(!this.yoyo || (_cyclesComplete % 2 == 0)); var prevForward:Boolean = Boolean(!this.yoyo || (prevCycles % 2 == 0)); var wrap:Boolean = Boolean(forward == prevForward); if (prevCycles > _cyclesComplete) { prevForward = !prevForward; } if (prevForward) { prevTime = forceChildrenToEnd(this.cachedDuration, suppressEvents); if (wrap) { prevTime = forceChildrenToBeginning(0, true); } } else { prevTime = forceChildrenToBeginning(0, suppressEvents); if (wrap) { prevTime = forceChildrenToEnd(this.cachedDuration, true); } } rendered = false; } } if (this.cachedTime == prevTime && !force) { return; } else if (!this.initted) { this.initted = true; } if (prevTotalTime == 0 && this.cachedTotalTime != 0 && !suppressEvents) { if (this.vars.onStart) { this.vars.onStart.apply(null, this.vars.onStartParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START)); } } if (rendered) { //already rendered, so ignore } else if (this.cachedTime > prevTime) { tween = _firstChild; while (tween) { next = tween.nextNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= this.cachedTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } else { tween = _lastChild; while (tween) { next = tween.prevNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= prevTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } if (_hasUpdate && !suppressEvents) { this.vars.onUpdate.apply(null, this.vars.onUpdateParams); } if (_hasUpdateListener && !suppressEvents) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE)); } if (repeated && !suppressEvents) { if (this.vars.onRepeat) { this.vars.onRepeat.apply(null, this.vars.onRepeatParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REPEAT)); } } if (isComplete && (prevStart == this.cachedStartTime || prevTimeScale != this.cachedTimeScale) && (totalDur >= this.totalDuration || this.cachedTime == 0)) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline) or if it added more tweens to the timeline, we shouldn't run complete() because it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would have called complete() if it was necessary at the new time. The only exception is the timeScale property. complete(true, suppressEvents); } } /** * Forces the timeline to completion. * * @param skipRender to skip rendering the final state of the timeline, set skipRender to true. * @param suppressEvents If true, no events or callbacks will be triggered for this render (like onComplete, onUpdate, onReverseComplete, etc.) */ override public function complete(skipRender:Boolean=false, suppressEvents:Boolean=false):void { super.complete(skipRender, suppressEvents); if (_dispatcher && !suppressEvents) { if (this.cachedReversed && this.cachedTotalTime == 0 && this.cachedDuration != 0) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REVERSE_COMPLETE)); } else { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE)); } } } /** * Returns the tweens/timelines that are currently active in the timeline. * * @param nested determines whether or not tweens and/or timelines that are inside nested timelines should be returned. If you only want the ""top level"" tweens/timelines, set this to false. * @param tweens determines whether or not tweens (TweenLite and TweenMax instances) should be included in the results * @param timelines determines whether or not timelines (TimelineLite and TimelineMax instances) should be included in the results * @return an Array of active tweens/timelines */ public function getActive(nested:Boolean=true, tweens:Boolean=true, timelines:Boolean=false):Array { var a:Array = [], all:Array = getChildren(nested, tweens, timelines), i:int, tween:TweenCore; var l:int = all.length; var cnt:int = 0; for (i = 0; i < l; i += 1) { tween = all[i]; //note: we cannot just check tween.active because timelines that contain paused children will continue to have ""active"" set to true even after the playhead passes their end point (technically a timeline can only be considered complete after all of its children have completed too, but paused tweens are...well...just waiting and until they're unpaused we don't know where their end point will be). if (!tween.cachedPaused && tween.timeline.cachedTotalTime >= tween.cachedStartTime && tween.timeline.cachedTotalTime < tween.cachedStartTime + tween.cachedTotalDuration / tween.cachedTimeScale && !OverwriteManager.getGlobalPaused(tween.timeline)) { a[cnt++] = all[i]; } } return a; } /** @inheritDoc **/ override public function invalidate():void { _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; this.yoyo = Boolean(this.vars.yoyo == true); if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } setDirtyCache(true); super.invalidate(); } /** * Returns the next label (if any) that occurs AFTER the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time after which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is after the time passed to getLabelAfter() */ public function getLabelAfter(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var l:int = labels.length; for (var i:int = 0; i < l; i += 1) { if (labels[i].time > time) { return labels[i].name; } } return null; } /** * Returns the previous label (if any) that occurs BEFORE the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time before which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is before the time passed to getLabelBefore() */ public function getLabelBefore(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var i:int = labels.length; while (--i > -1) { if (labels[i].time < time) { return labels[i].name; } } return null; } /** @private Returns an Array of label objects, each with a ""time"" and ""name"" property, in the order that they occur in the timeline. **/ protected function getLabelsArray():Array { var a:Array = []; for (var p:String in _labels) { a[a.length] = {time:_labels[p], name:p}; } a.sortOn(""time"", Array.NUMERIC); return a; } //---- EVENT DISPATCHING ---------------------------------------------------------------------------------------------------------- /** @private **/ protected function initDispatcher():void { if (_dispatcher == null) { _dispatcher = new EventDispatcher(this); } if (this.vars.onStartListener is Function) { _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true); } if (this.vars.onUpdateListener is Function) { _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true); _hasUpdateListener = true; } if (this.vars.onCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true); } if (this.vars.onRepeatListener is Function) { _dispatcher.addEventListener(TweenEvent.REPEAT, this.vars.onRepeatListener, false, 0, true); } if (this.vars.onReverseCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.REVERSE_COMPLETE, this.vars.onReverseCompleteListener, false, 0, true); } } /** @private **/ public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { if (_dispatcher == null) { initDispatcher(); } if (type == TweenEvent.UPDATE) { _hasUpdateListener = true; } _dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** @private **/ public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { if (_dispatcher != null) { _dispatcher.removeEventListener(type, listener, useCapture); } } /** @private **/ public function hasEventListener(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.hasEventListener(type); } /** @private **/ public function willTrigger(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.willTrigger(type); } /** @private **/ public function dispatchEvent(e:Event):Boolean { return (_dispatcher == null) ? false : _dispatcher.dispatchEvent(e); } //---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- /** @inheritDoc **/ override public function set currentProgress(n:Number):void { this.currentTime = this.duration * n; } /** * Value between 0 and 1 indicating the overall progress of the timeline according to its totalDuration * where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished. currentProgress, * by contrast, describes the progress according to the timeline's duration which does not * include repeats and repeatDelays. For example, if a TimelineMax instance is set * to repeat once, at the end of the first cycle totalProgress would only be 0.5 * whereas currentProgress would be 1. If you tracked both properties over the course of the * tween, you'd see currentProgress go from 0 to 1 twice (once for each cycle) in the same * time it takes the totalProgress property to go from 0 to 1 once. **/ public function get totalProgress():Number { return this.cachedTotalTime / this.totalDuration; } public function set totalProgress(n:Number):void { setTotalTime(this.totalDuration * n, false); } /** * Duration of the timeline in seconds (or frames for frames-based timelines) including any repeats * or repeatDelays. ""duration"", by contrast, does NOT include repeats and repeatDelays. **/ override public function get totalDuration():Number { if (this.cacheIsDirty) { var temp:Number = super.totalDuration; //just forces refresh //Instead of Infinity, we use 999999999999 so that we can accommodate reverses. this.cachedTotalDuration = (_repeat == -1) ? 999999999999 : this.cachedDuration * (_repeat + 1) + (_repeatDelay * _repeat); } return this.cachedTotalDuration; } /** @private **/ override public function set currentTime(n:Number):void { if (_cyclesComplete == 0) { setTotalTime(n, false); } else if (this.yoyo && (_cyclesComplete % 2 == 1)) { setTotalTime((this.duration - n) + (_cyclesComplete * (this.cachedDuration + _repeatDelay)), false); } else { setTotalTime(n + (_cyclesComplete * (this.duration + _repeatDelay)), false); } } /** Number of times that the timeline should repeat; -1 repeats indefinitely. **/ public function get repeat():int { return _repeat; } public function set repeat(n:int):void { _repeat = n; setDirtyCache(true); } /** Amount of time in seconds (or frames for frames-based timelines) between repeats **/ public function get repeatDelay():Number { return _repeatDelay; } public function set repeatDelay(n:Number):void { _repeatDelay = n; setDirtyCache(true); } /** The closest label that is at or before the current time. **/ public function get currentLabel():String { return getLabelBefore(this.cachedTime + 0.00000001); } } }",12341,False,2104.9939945955243,median "/* * VERSION:3.0 * DATE:2014-10-15 * ACTIONSCRIPT VERSION: 3.0 * UPDATES AND DOCUMENTATION AT: http://www.wdmir.net * MAIL:mir3@163.com */ package com.greensock { import com.greensock.core.*; import com.greensock.events.TweenEvent; import flash.events.*; import flash.utils.*; /** * TimelineMax extends TimelineLite, offering exactly the same functionality plus useful * (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, * currentLabel, addCallback(), removeCallback(), tweenTo(), tweenFromTo(), getLabelAfter(), getLabelBefore(), * and getActive() (and probably more in the future). It is the ultimate sequencing tool. * Think of a TimelineMax instance like a virtual MovieClip timeline or a container where * you place tweens (or other timelines) over the course of time. You can: * *
      *
    • build sequences easily by adding tweens with the append(), prepend(), insert(), appendMultiple(), * prependMultiple(), and insertMultiple() methods. Tweens can overlap as much as you want and you have * complete control over where they get placed on the timeline.
    • * *
    • add labels, play(), stop(), gotoAndPlay(), gotoAndStop(), restart(), tweenTo() and even reverse()!
    • * *
    • nest timelines within timelines as deeply as you want.
    • * *
    • set the progress of the timeline using its currentProgress property. For example, to skip to * the halfway point, set myTimeline.currentProgress = 0.5.
    • * *
    • tween the currentTime, totalTime, currentProgress, or totalProgress * property to fastforward/rewind the timeline. You could * even attach a slider to one of these properties to give the user the ability to drag * forwards/backwards through the whole timeline.
    • * *
    • add onStart, onUpdate, onComplete, onReverseComplete, and/or onRepeat callbacks using the * constructor's vars object.
    • * *
    • speed up or slow down the entire timeline with its timeScale property. You can even tween * this property to gradually speed up or slow down the timeline.
    • * *
    • use the insertMultiple(), appendMultiple(), or prependMultiple() methods to create * complex sequences including various alignment modes and staggering capabilities. * Works great in conjunction with TweenMax.allTo() too.
    • * *
    • base the timing on frames instead of seconds if you prefer. Please note, however, that * the timeline's timing mode dictates its childrens' timing mode as well.
    • * *
    • kill the tweens of a particular object inside the timeline with killTweensOf() or get the tweens of an object * with getTweensOf() or get all the tweens/timelines in the timeline with getChildren()
    • * *
    • set the timeline to repeat any number of times or indefinitely. You can even set a delay * between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse * every other cycle.
    • * *
    • listen for START, UPDATE, REPEAT, REVERSE_COMPLETE, and COMPLETE events.
    • * *
    • get the active tweens in the timeline with getActive().
    • * *
    • add callbacks (function calls) anywhere in the timeline that call a function of your choosing when * the ""virtual playhead"" passes a particular spot.
    • * *
    • Get the currentLabel or find labels at various positions in the timeline * using getLabelAfter() and getLabelBefore()
    • *
    * * EXAMPLE:

    * * import com.greensock.~~;

    * * //create the timeline and add an onComplete call to myFunction when the timeline completes
    * var myTimeline:TimelineMax = new TimelineMax({onComplete:myFunction});

    * * //add a tween
    * myTimeline.append(new TweenLite(mc, 1, {x:200, y:100}));

    * * //add another tween at the end of the timeline (makes sequencing easy)
    * myTimeline.append(new TweenLite(mc, 0.5, {alpha:0}));

    * * //repeat the entire timeline twice
    * myTimeline.repeat = 2;

    * * //delay the repeat by 0.5 seconds each time.
    * myTimeline.repeatDelay = 0.5;

    * * //pause the timeline (stop() works too)
    * myTimeline.pause();

    * * //reverse it anytime...
    * myTimeline.reverse();

    * * //Add a ""spin"" label 3-seconds into the timeline.
    * myTimeline.addLabel(""spin"", 3);

    * * //insert a rotation tween at the ""spin"" label (you could also define the insert point as the time instead of a label)
    * myTimeline.insert(new TweenLite(mc, 2, {rotation:""360""}), ""spin"");

    * * //go to the ""spin"" label and play the timeline from there...
    * myTimeline.gotoAndPlay(""spin"");

    * * //call myCallbackwhen the ""virtual playhead"" travels past the 1.5-second point. * myTimeline.addCallback(myCallback, 1.5); * * //add a tween to the beginning of the timeline, pushing all the other existing tweens back in time
    * myTimeline.prepend(new TweenMax(mc, 1, {tint:0xFF0000}));

    * * //nest another TimelineMax inside your timeline...
    * var nestedTimeline:TimelineMax = new TimelineMax();
    * nestedTimeline.append(new TweenLite(mc2, 1, {x:200}));
    * myTimeline.append(nestedTimeline);

    * * * insertMultiple() and appendMultiple() provide some very powerful sequencing tools as well, * allowing you to add an Array of tweens/timelines and optionally align them with SEQUENCE or START * modes, and even stagger them if you want. For example, to insert 3 tweens into the timeline, aligning their start times but * staggering them by 0.2 seconds,

    * * myTimeline.insertMultiple([new TweenLite(mc, 1, {y:""100""}), * new TweenLite(mc2, 1, {x:120}), * new TweenLite(mc3, 1, {alpha:0.5})], * 0, * TweenAlign.START, * 0.2);

    * * You can use the constructor's vars object to do all the setup too, like:

    * * var myTimeline:TimelineMax = new TimelineMax({tweens:[new TweenLite(mc1, 1, {y:""100""}), TweenMax.to(mc2, 1, {tint:0xFF0000})], align:TweenAlign.SEQUENCE, onComplete:myFunction, repeat:2, repeatDelay:1});

    * * If that confuses you, don't worry. Just use the append(), insert(), and prepend() methods to build your * sequence. But power users will likely appreciate the quick, compact way they can set up sequences now.

    * * * NOTES: *
      *
    • TimelineMax automatically inits the OverwriteManager class to prevent unexpected overwriting behavior in sequences. * The default mode is AUTO, but you can set it to whatever you want with OverwriteManager.init() * (see http://www.greensock.com/overwritemanager/)
    • *
    • TimelineMax adds about 4.9k to your SWF (not including OverwriteManager).
    • *
    * * Copyright 2010, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com **/ public class TimelineMax extends TimelineLite implements IEventDispatcher { /** @private **/ public static const version:Number = 1.381; /** @private **/ protected var _repeat:int; /** @private **/ protected var _repeatDelay:Number; /** @private **/ protected var _cyclesComplete:uint; /** @private **/ protected var _dispatcher:EventDispatcher; /** @private **/ protected var _hasUpdateListener:Boolean; /** * Works in conjunction with the repeat property, determining the behavior of each cycle; when yoyo is true, * the timeline will go back and forth, appearing to reverse every other cycle (this has no affect on the reversed property though). * So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. * But if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. **/ public var yoyo:Boolean; /** * Constructor.

    * * SPECIAL PROPERTIES
    * The following special properties may be passed in via the constructor's vars parameter, like * new TimelineMax({paused:true, onComplete:myFunction, repeat:2, yoyo:true}) * *
      *
    • delay : Number Amount of delay in seconds (or frames for frames-based timelines) before the timeline should begin.
    • * *
    • useFrames : Boolean If useFrames is set to true, the timeline's timing mode will be based on frames. * Otherwise, it will be based on seconds/time. NOTE: a TimelineLite's timing mode is * always determined by its parent timeline.
    • * *
    • paused : Boolean Sets the initial paused state of the timeline (by default, timelines automatically begin playing immediately)
    • * *
    • reversed : Boolean If true, the timeline will be reversed initially. This does NOT force it to the very end and start * playing backwards. It simply affects the orientation of the timeline, so if reversed is set to * true initially, it will appear not to play because it is already at the beginning. To cause it to * play backwards from the end, set reversed to true and then set the currentProgress property to 1 immediately * after creating the timeline.
    • * *
    • tweens : Array To immediately insert several tweens into the timeline, use the tweens special property * to pass in an Array of TweenLite/TweenMax/TimelineLite/TimelineMax instances. You can use this in conjunction * with the align and stagger special properties to set up complex sequences with minimal code. * These values simply get passed to the insertMultiple() method.
    • * *
    • align : String Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately through the constructor. The value simply gets passed to the * insertMultiple() method. The default is TweenAlign.NORMAL. Options are: *
        *
      • TweenAlign.SEQUENCE: aligns the tweens one-after-the-other in a sequence
      • *
      • TweenAlign.START: aligns the start times of all of the tweens (ignores delays)
      • *
      • TweenAlign.NORMAL: aligns the start times of all the tweens (honors delays)
      • *
      The align special property does not force all child tweens/timelines to maintain * relative positioning, so for example, if you use TweenAlign.SEQUENCE and then later change the duration * of one of the nested tweens, it does not force all subsequent timelines to change their position * on the timeline. The align special property only affects the alignment of the tweens that are * initially placed into the timeline through the tweens special property of the vars object.
    • * *
    • stagger : Number Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately. It staggers the tweens by a set amount of time (in seconds) (or * in frames if useFrames is true). For example, if the stagger value is 0.5 and the align * property is set to TweenAlign.START, the second tween will start 0.5 seconds after the first one * starts, then 0.5 seconds later the third one will start, etc. If the align property is * TweenAlign.SEQUENCE, there would be 0.5 seconds added between each tween. This value simply gets * passed to the insertMultiple() method. Default is 0.
    • * *
    • onStart : Function A function that should be called when the timeline begins (the currentProgress won't necessarily * be zero when onStart is called. For example, if the timeline is created and then its currentProgress * property is immediately set to 0.5 or if its currentTime property is set to something other than zero, * onStart will still get fired because it is the first time the timeline is getting rendered.)
    • * *
    • onStartParams : Array An Array of parameters to pass the onStart function.
    • * *
    • onUpdate : Function A function that should be called every time the timeline's time/position is updated * (on every frame while the timeline is active)
    • * *
    • onUpdateParams : Array An Array of parameters to pass the onUpdate function
    • * *
    • onComplete : Function A function that should be called when the timeline has finished
    • * *
    • onCompleteParams : Array An Array of parameters to pass the onComplete function
    • * *
    • onReverseComplete : Function A function that should be called when the timeline has reached its starting point again after having been reversed
    • * *
    • onReverseCompleteParams : Array An Array of parameters to pass the onReverseComplete functions
    • * *
    • onRepeat : Function A function that should be called every time the timeline repeats
    • * *
    • onRepeatParams : Array An Array of parameters to pass the onRepeat function
    • * *
    • autoRemoveChildren : Boolean If autoRemoveChildren is set to true, as soon as child tweens/timelines complete, * they will automatically get killed/removed. This is normally undesireable because * it prevents going backwards in time (like if you want to reverse() or set the * currentProgress value to a lower value, etc.). It can, however, improve speed and memory * management. TweenLite's root timelines use autoRemoveChildren:true.
    • * *
    • repeat : int Number of times that the timeline should repeat. To repeat indefinitely, use -1.
    • * *
    • repeatDelay : Number Amount of time in seconds (or frames for frames-based timelines) between repeats.
    • * *
    • yoyo : Boolean Works in conjunction with the repeat property, determining the behavior of each * cycle. When yoyo is true, the timeline will go back and forth, appearing to reverse * every other cycle (this has no affect on the reversed property though). So if repeat is * 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But * if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
    • * *
    • onStartListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it begins. * This is the same as doing myTimeline.addEventListener(TweenEvent.START, myFunction);
    • * *
    • onUpdateListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent every time it * updates values. This is the same as doing myTimeline.addEventListener(TweenEvent.UPDATE, myFunction);
    • * *
    • onCompleteListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it completes. * This is the same as doing myTimeline.addEventListener(TweenEvent.COMPLETE, myFunction);
    • *
    * * @param vars optionally pass in special properties like useFrames, onComplete, onCompleteParams, onUpdate, onUpdateParams, onStart, onStartParams, tweens, align, stagger, delay, autoRemoveChildren, onCompleteListener, onStartListener, onUpdateListener, repeat, repeatDelay, and/or yoyo. */ public function TimelineMax(vars:Object=null) { super(vars); _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; _cyclesComplete = 0; this.yoyo = Boolean(this.vars.yoyo == true); this.cacheIsDirty = true; if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } } /** * If you want a function to be called at a particular time or label, use addCallback. When you add * a callback, it is technically considered a zero-duration tween, so if you getChildren() there will be * a tween returned for each callback. You can discern a callback from other tweens by the fact that * their target is a function and the duration is zero. * * @param function the function to be called * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label at which the callback should be inserted. For example, myTimeline.addCallback(myFunction, 3) would call myFunction() 3-seconds into the timeline, and myTimeline.addCallback(myFunction, ""myLabel"") would call it at the ""myLabel"" label. * @param params an Array of parameters to pass the callback * @return TweenLite instance */ public function addCallback(callback:Function, timeOrLabel:*, params:Array=null):TweenLite { var cb:TweenLite = new TweenLite(callback, 0, {onComplete:callback, onCompleteParams:params, overwrite:0, immediateRender:false}); insert(cb, timeOrLabel); return cb; } /** * Removes a callback from a particular time or label. If timeOrLabel is null, all callbacks of that * particular function are removed from the timeline. * * @param function callback function to be removed * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label from which the callback should be removed. For example, myTimeline.removeCallback(myFunction, 3) would remove the callback from 3-seconds into the timeline, and myTimeline.removeCallback(myFunction, ""myLabel"") would remove it from the ""myLabel"" label, and myTimeline.removeCallback(myFunction, null) would remove ALL callbacks of that function regardless of where they are on the timeline. * @return true if any callbacks were successfully found and removed. false otherwise. */ public function removeCallback(callback:Function, timeOrLabel:*=null):Boolean { if (timeOrLabel == null) { return killTweensOf(callback, false); } else { if (typeof(timeOrLabel) == ""string"") { if (!(timeOrLabel in _labels)) { return false; } timeOrLabel = _labels[timeOrLabel]; } var a:Array = getTweensOf(callback, false), success:Boolean; var i:int = a.length; while (--i > -1) { if (a[i].cachedStartTime == timeOrLabel) { remove(a[i] as TweenCore); success = true; } } return success; } } /** * Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops. For * example, to make the TimelineMax play to the ""myLabel2"" label, simply do:

    * * myTimeline.tweenTo(""myLabel2"");

    * * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween to the 5-second point on the * timeline and then call a function named myFunction and pass in a parameter that's references this * TimelineMax and use a Strong.easeOut ease, you'd do:

    * * myTimeline.tweenTo(5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

    * * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method.

    * * If you plan to sequence multiple playhead tweens one-after-the-other, it is typically better to use * tweenFromTo() so that you can define the starting point and ending point, allowing the * duration to be accurately determined immediately. * * @see #tweenFromTo() * @param timeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(5) would play from wherever the timeline is currently to the 5-second point whereas myTimeline.tweenTo(""myLabel"") would play to wherever ""myLabel"" is on the timeline. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenTo() sets it internally) * @return TweenLite instance that handles tweening the timeline to the desired time/label. */ public function tweenTo(timeOrLabel:*, vars:Object=null):TweenLite { var varsCopy:Object = {ease:easeNone, overwrite:2, useFrames:this.useFrames, immediateRender:false}; for (var p:String in vars) { varsCopy[p] = vars[p]; } varsCopy.onInit = onInitTweenTo; varsCopy.onInitParams = [null, this, NaN]; varsCopy.currentTime = parseTimeOrLabel(timeOrLabel); var tl:TweenLite = new TweenLite(this, (Math.abs(Number(varsCopy.currentTime) - this.cachedTime) / this.cachedTimeScale) || 0.001, varsCopy); tl.vars.onInitParams[0] = tl; return tl; } /** * Creates a linear tween that essentially scrubs the playhead from a particular time or label to another * time or label and then stops. If you plan to sequence multiple playhead tweens one-after-the-other, * tweenFromTo() is better to use than tweenTo() because it allows the duration * to be determined immediately, ensuring that subsequent tweens that are appended to a sequence are * positioned appropriately. For example, to make the TimelineMax play from the label ""myLabel1"" to the ""myLabel2"" * label, and then from ""myLabel2"" back to the beginning (a time of 0), simply do:

    * * var playheadTweens:TimelineMax = new TimelineMax();
    * playheadTweens.append( myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") );
    * playheadTweens.append( myTimeline.tweenFromTo(""myLabel2"", 0);

    * * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween from the start (0) to the * 5-second point on the timeline and then call a function named myFunction and pass in a parameter * that's references this TimelineMax and use a Strong.easeOut ease, you'd do:

    * * myTimeline.tweenFromTo(0, 5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

    * * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenFromTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenFromTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method. * * @see #tweenTo() * @param fromTimeOrLabel The beginning time in seconds (or frame if the timeline is frames-based) or label from which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param toTimeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenFromTo() sets it internally) * @return TweenLite instance that handles tweening the timeline between the desired times/labels. */ public function tweenFromTo(fromTimeOrLabel:*, toTimeOrLabel:*, vars:Object=null):TweenLite { var tl:TweenLite = tweenTo(toTimeOrLabel, vars); tl.vars.onInitParams[2] = parseTimeOrLabel(fromTimeOrLabel); tl.duration = Math.abs(Number(tl.vars.currentTime) - tl.vars.onInitParams[2]) / this.cachedTimeScale; return tl; } /** @private **/ private static function onInitTweenTo(tween:TweenLite, timeline:TimelineMax, fromTime:Number):void { timeline.paused = true; if (!isNaN(fromTime)) { timeline.currentTime = fromTime; } if (tween.vars.currentTime != timeline.currentTime) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. tween.duration = Math.abs(Number(tween.vars.currentTime) - timeline.currentTime) / timeline.cachedTimeScale; } } /** @private **/ private static function easeNone(t:Number, b:Number, c:Number, d:Number):Number { return t / d; } /** @private **/ override public function renderTime(time:Number, suppressEvents:Boolean=false, force:Boolean=false):void { if (this.gc) { this.setEnabled(true, false); } else if (!this.active && !this.cachedPaused) { this.active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. } var totalDur:Number = (this.cacheIsDirty) ? this.totalDuration : this.cachedTotalDuration, prevTime:Number = this.cachedTime, prevStart:Number = this.cachedStartTime, prevTimeScale:Number = this.cachedTimeScale, tween:TweenCore, isComplete:Boolean, rendered:Boolean, repeated:Boolean, next:TweenCore, dur:Number, prevPaused:Boolean = this.cachedPaused; if (time >= totalDur) { if (_rawPrevTime <= totalDur && _rawPrevTime != time) { if (!this.cachedReversed && this.yoyo && _repeat % 2 != 0) { forceChildrenToBeginning(0, suppressEvents); this.cachedTime = 0; } else { forceChildrenToEnd(this.cachedDuration, suppressEvents); this.cachedTime = this.cachedDuration; } this.cachedTotalTime = totalDur; isComplete = !this.hasPausedChild(); rendered = true; if (this.cachedDuration == 0 && isComplete && (time == 0 || _rawPrevTime < 0)) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; } } } else if (time <= 0) { if (time < 0) { this.active = false; if (this.cachedDuration == 0 && _rawPrevTime > 0) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; isComplete = true; } } if (_rawPrevTime >= 0 && _rawPrevTime != time) { this.cachedTotalTime = 0; forceChildrenToBeginning(0, suppressEvents); this.cachedTime = 0; rendered = true; if (this.cachedReversed) { isComplete = true; } } } else { this.cachedTotalTime = this.cachedTime = time; } _rawPrevTime = time; if (_repeat != 0) { var cycleDuration:Number = this.cachedDuration + _repeatDelay; if (isComplete) { if (this.yoyo && _repeat % 2) { this.cachedTime = 0; } } else if (time > 0) { var prevCycles:int = _cyclesComplete; _cyclesComplete = int(this.cachedTotalTime / cycleDuration); if (_cyclesComplete == this.cachedTotalTime / cycleDuration) { _cyclesComplete--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } if (prevCycles != _cyclesComplete) { repeated = true; } this.cachedTime = ((this.cachedTotalTime / cycleDuration) - _cyclesComplete) * cycleDuration; //originally this.cachedTotalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!) if (this.yoyo && _cyclesComplete % 2) { this.cachedTime = this.cachedDuration - this.cachedTime; } else if (this.cachedTime >= this.cachedDuration) { this.cachedTime = this.cachedDuration; } if (this.cachedTime < 0) { this.cachedTime = 0; } } if (repeated && !isComplete && (this.cachedTime != prevTime || force)) { /* make sure children at the end/beginning of the timeline are rendered properly. If, for example, a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So we need to push the timeline to the end (and/or beginning depending on its yoyo value). */ var forward:Boolean = Boolean(!this.yoyo || (_cyclesComplete % 2 == 0)); var prevForward:Boolean = Boolean(!this.yoyo || (prevCycles % 2 == 0)); var wrap:Boolean = Boolean(forward == prevForward); if (prevCycles > _cyclesComplete) { prevForward = !prevForward; } if (prevForward) { prevTime = forceChildrenToEnd(this.cachedDuration, suppressEvents); if (wrap) { prevTime = forceChildrenToBeginning(0, true); } } else { prevTime = forceChildrenToBeginning(0, suppressEvents); if (wrap) { prevTime = forceChildrenToEnd(this.cachedDuration, true); } } rendered = false; } } if (this.cachedTime == prevTime && !force) { return; } else if (!this.initted) { this.initted = true; } if (prevTime == 0 && this.cachedTotalTime != 0 && !suppressEvents) { if (this.vars.onStart) { this.vars.onStart.apply(null, this.vars.onStartParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START)); } } if (rendered) { //already rendered, so ignore } else if (this.cachedTime - prevTime > 0) { tween = _firstChild; while (tween) { next = tween.nextNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= this.cachedTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } else { tween = _lastChild; while (tween) { next = tween.prevNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= prevTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } if (_hasUpdate && !suppressEvents) { this.vars.onUpdate.apply(null, this.vars.onUpdateParams); } if (_hasUpdateListener && !suppressEvents) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE)); } if (isComplete && (prevStart == this.cachedStartTime || prevTimeScale != this.cachedTimeScale) && (totalDur >= this.totalDuration || this.cachedTime == 0)) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline) or if it added more tweens to the timeline, we shouldn't run complete() because it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would have called complete() if it was necessary at the new time. The only exception is the timeScale property. complete(true, suppressEvents); } else if (repeated && !suppressEvents) { if (this.vars.onRepeat) { this.vars.onRepeat.apply(null, this.vars.onRepeatParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REPEAT)); } } } /** * Forces the timeline to completion. * * @param skipRender to skip rendering the final state of the timeline, set skipRender to true. * @param suppressEvents If true, no events or callbacks will be triggered for this render (like onComplete, onUpdate, onReverseComplete, etc.) */ override public function complete(skipRender:Boolean=false, suppressEvents:Boolean=false):void { super.complete(skipRender, suppressEvents); if (_dispatcher && !suppressEvents) { if (this.cachedReversed && this.cachedTotalTime == 0 && this.cachedDuration != 0) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REVERSE_COMPLETE)); } else { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE)); } } } /** * Returns the tweens/timelines that are currently active in the timeline. * * @param nested determines whether or not tweens and/or timelines that are inside nested timelines should be returned. If you only want the ""top level"" tweens/timelines, set this to false. * @param tweens determines whether or not tweens (TweenLite and TweenMax instances) should be included in the results * @param timelines determines whether or not timelines (TimelineLite and TimelineMax instances) should be included in the results * @return an Array of active tweens/timelines */ public function getActive(nested:Boolean=true, tweens:Boolean=true, timelines:Boolean=false):Array { var a:Array = [], all:Array = getChildren(nested, tweens, timelines), i:int; var l:uint = all.length; var cnt:uint = 0; for (i = 0; i < l; i++) { if (TweenCore(all[i]).active) { a[cnt++] = all[i]; } } return a; } /** @inheritDoc **/ override public function invalidate():void { _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; this.yoyo = Boolean(this.vars.yoyo == true); if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } setDirtyCache(true); super.invalidate(); } /** * Returns the next label (if any) that occurs AFTER the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time after which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is after the time passed to getLabelAfter() */ public function getLabelAfter(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var l:uint = labels.length; for (var i:int = 0; i < l; i++) { if (labels[i].time > time) { return labels[i].name; } } return null; } /** * Returns the previous label (if any) that occurs BEFORE the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time before which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is before the time passed to getLabelBefore() */ public function getLabelBefore(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var i:int = labels.length; while (--i > -1) { if (labels[i].time < time) { return labels[i].name; } } return null; } /** @private Returns an Array of label objects, each with a ""time"" and ""name"" property, in the order that they occur in the timeline. **/ protected function getLabelsArray():Array { var a:Array = []; for (var p:String in _labels) { a[a.length] = {time:_labels[p], name:p}; } a.sortOn(""time"", Array.NUMERIC); return a; } //---- EVENT DISPATCHING ---------------------------------------------------------------------------------------------------------- /** @private **/ protected function initDispatcher():void { if (_dispatcher == null) { _dispatcher = new EventDispatcher(this); } if (this.vars.onStartListener is Function) { _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true); } if (this.vars.onUpdateListener is Function) { _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true); _hasUpdateListener = true; } if (this.vars.onCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true); } if (this.vars.onRepeatListener is Function) { _dispatcher.addEventListener(TweenEvent.REPEAT, this.vars.onRepeatListener, false, 0, true); } if (this.vars.onReverseCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.REVERSE_COMPLETE, this.vars.onReverseCompleteListener, false, 0, true); } } /** @private **/ public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { if (_dispatcher == null) { initDispatcher(); } if (type == TweenEvent.UPDATE) { _hasUpdateListener = true; } _dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** @private **/ public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { if (_dispatcher != null) { _dispatcher.removeEventListener(type, listener, useCapture); } } /** @private **/ public function hasEventListener(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.hasEventListener(type); } /** @private **/ public function willTrigger(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.willTrigger(type); } /** @private **/ public function dispatchEvent(e:Event):Boolean { return (_dispatcher == null) ? false : _dispatcher.dispatchEvent(e); } //---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- /** * Value between 0 and 1 indicating the overall progress of the timeline according to its totalDuration * where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished. currentProgress, * by contrast, describes the progress according to the timeline's duration which does not * include repeats and repeatDelays. For example, if a TimelineMax instance is set * to repeat once, at the end of the first cycle totalProgress would only be 0.5 * whereas currentProgress would be 1. If you tracked both properties over the course of the * tween, you'd see currentProgress go from 0 to 1 twice (once for each cycle) in the same * time it takes the totalProgress property to go from 0 to 1 once. **/ public function get totalProgress():Number { return this.cachedTotalTime / this.totalDuration; } public function set totalProgress(n:Number):void { setTotalTime(this.totalDuration * n, false); } /** * Duration of the timeline in seconds (or frames for frames-based timelines) including any repeats * or repeatDelays. ""duration"", by contrast, does NOT include repeats and repeatDelays. **/ override public function get totalDuration():Number { if (this.cacheIsDirty) { var temp:Number = super.totalDuration; //just forces refresh //Instead of Infinity, we use 999999999999 so that we can accommodate reverses. this.cachedTotalDuration = (_repeat == -1) ? 999999999999 : this.cachedDuration * (_repeat + 1) + (_repeatDelay * _repeat); } return this.cachedTotalDuration; } /** @inheritDoc **/ override public function set currentTime(n:Number):void { if (_cyclesComplete == 0) { setTotalTime(n, false); } else if (this.yoyo && (_cyclesComplete % 2 == 1)) { setTotalTime((this.duration - n) + (_cyclesComplete * (this.cachedDuration + _repeatDelay)), false); } else { setTotalTime(n + (_cyclesComplete * (this.duration + _repeatDelay)), false); } } /** Number of times that the timeline should repeat; -1 repeats indefinitely. **/ public function get repeat():int { return _repeat; } public function set repeat(n:int):void { _repeat = n; setDirtyCache(true); } /** Amount of time in seconds (or frames for frames-based timelines) between repeats **/ public function get repeatDelay():Number { return _repeatDelay; } public function set repeatDelay(n:Number):void { _repeatDelay = n; setDirtyCache(true); } /** The closest label that is at or before the current time. **/ public function get currentLabel():String { return getLabelBefore(this.cachedTime + 0.00000001); } } } ",12062,False,2050.8697539535656,median "//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2006-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package mx.controls { import flash.events.KeyboardEvent; import flash.filesystem.File; import mx.controls.dataGridClasses.DataGridColumn; import mx.controls.fileSystemClasses.FileSystemControlHelper; import mx.controls.fileSystemClasses.FileSystemDataGridNameColumnRenderer; import mx.core.ClassFactory; import mx.core.IUITextField; import mx.core.ScrollPolicy; import mx.core.mx_internal; import mx.events.ListEvent; import mx.formatters.DateFormatter; use namespace mx_internal; //-------------------------------------- // Events //-------------------------------------- /** * Dispatched when the selected directory displayed by this control * changes for any reason. * * @eventType mx.events.FileEvent.DIRECTORY_CHANGE * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""directoryChange"", type=""mx.events.FileEvent"")] /** * Dispatched when the user tries to change * the directory displayed by this control. * *

    The user can try to change the directory * by double-clicking a subdirectory, * by pressing Enter or Ctrl-Down when a subdirectory is selected, * by pressing Ctrl-Up when the control isn't displaying * the COMPUTER directory, * by pressing Ctrl-Left when there is a previous directory * in the history list to navigate back to, * or by pressing Ctrl-Right when there is a next directory * in the history list to navigate forward to.

    * *

    This event is cancelable. * If you call event.preventDefault(), * the directory is not changed.

    * *

    After the directory property has changed * and the dataProvider contains File instances * for the items in the new directory, * the directoryChange event is dispatched.

    * * @eventType mx.events.FileEvent.DIRECTORY_OPENING * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""directoryChanging"", type=""mx.events.FileEvent"")] /** * Dispatched when the user chooses a file by double-clicking it * or by selecting it and pressing Enter. * * @eventType mx.events.FileEvent.FILE_CHOOSE * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""fileChoose"", type=""mx.events.FileEvent"")] //-------------------------------------- // Styles //-------------------------------------- /** * Specifies the icon that indicates a directory. * The default icon is located in the Assets.swf file. * In MXML, you can use the following syntax to set this property: * directoryIcon=""@Embed(source='directoryIcon.jpg');"" * * @default TreeNodeIcon * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""directoryIcon"", type=""Class"", format=""EmbeddedFile"", inherit=""no"")] /** * Specifies the icon that indicates a file. * The default icon is located in the Assets.swf file. * In MXML, you can use the following syntax to set this property: * fileIcon=""@Embed(source='fileIcon.jpg');"" * * @default TreeNodeIcon * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Style(name=""fileIcon"", type=""Class"", format=""EmbeddedFile"", inherit=""no"")] //-------------------------------------- // Other metadata //-------------------------------------- [IconFile(""FileSystemDataGrid.png"")] [ResourceBundle(""aircontrols"")] /** * The FileSystemDataGrid control lets you display the contents of a * single file system directory in a data grid format. * *

    The information displayed for each item consists of its name * (with optional generic icon), type, size, creation date, * and modification date. * To do this, FileSystemDataGrid automatically creates five columns * (DataGridColumn instances) -- nameColumn, typeColumn, * sizeColumn, creationDateColumn, * and modificationDateColumn -- and sets * the columns property to an array of these five instances. * Each column instance is automatically configured to have an * appropriate labelFunction, * sortCompareFunction, etc. * If you don't want all five columns, or if you want to change the * order, reset the columns property. * If you want to customize a column, such as by changing its * labelFunction, simply reassign that property * on the appropriate column object.

    * *

    To change the displayed data, rather than using the dataProvider property, * you set the directory property. * The control then automatically populates the dataProvider * property by enumerating the contents of that directory. * You should not set the dataProvider yourself.

    * *

    You set the directory property to a File instance, * as the following example shows:

    *
    <mx:FileSystemDataGrid directory=""{File.desktopDirectory}""/>
    * *

    You can set the enumerationMode property to specify * whether to show files, subdirectories, or both. * There are three ways to show both: directories first, * files first, or intermixed.

    * *

    You can set the extensions property * to filter the displayed items so that only files * with the specified extensions appear. * The showHidden property determines whether the control * displays files and subdirectories that the operating system * normally hides. * You can specify an additional filterFunction * to perform custom filtering, and a nameCompareFunction * to perform custom sorting.

    * *

    Because AIR does not support file system notifications, * this control does not automatically refresh if a file or * subdirectory is created, deleted, moved, or renamed; * in other words, it can display an out-of-date view of the file system. * However, you can call refresh() to re-enumerate * the current directory. * You could, for example, choose to do this when you have * performed a file operation that you know causes the control's * view to become out-of-date, or when the user deactivates * and reactivates your application.

    * *

    You can use the showIcons property * to show or hide icons, and the showExtensions * property to show or hide file extensions.

    * *

    The control provides two methods, findItem() * and findIndex(), which you can use to search the * displayed files and subdirectories to find the one * with a specified nativePath.

    * *

    Two properties, selectedPath * and selectedPaths, work similarly * to selectedItem and selectedItems * or selectedIndex and selectedIndices, * but let you specify the selection via nativePath * strings. * These are very useful if you need to display a directory * with particular items preselected, since in this case * you don't yet have the File items that the control will create * when it enumerates the directory, and you don't know what * their indices will be.

    * *

    The control allows the user to navigate to other directories * using the mouse or keyboard. * The user can try to change the directory * by double-clicking a subdirectory, * by pressing Enter or Ctrl-Down when a subdirectory is selected, * by pressing Ctrl-Up when the control isn't displaying * the COMPUTER directory, by pressing Ctrl-Left when there is * a ""previous"" directory to navigate back to, or by pressing Ctrl-Right * when there is a ""next"" directory to navigate forward to. * If the user attempts to change the directory being displayed, * the control dispatches a cancelable directoryChanging event. * If you don't cancel this event by calling * event.preventDefault(), the control displays the * contents of the new directory and the directory * property changes. * Whenever the directory property changes, for any reason, * the controls dispatches a directoryChange event * to let you know.

    * *

    In order to support ""Up"" and ""Down"" controls, the FileSystemList * has canNavigateUp and canNavigateDown * properties and navigateUp() and navigateDown() * methods. There is also a navigateTo() for navigating * to an arbitrary directory.

    * *

    The control keeps track of the directories to which the user * has navigated, in order to make it easy for you to support * ""Back"" and ""Forward"" controls. * For more information, see the backHistory, * forwardHistory, canNavigateBack, * and canNavigateForward properties, and the * navigateBack() and navigateForward() methods.

    * *

    Note: The icons displayed for each item are generic file and directory * icons which you can set using the fileIcon * and directoryIcon styles. * Flex's list-based controls currently support displaying * only embedded icons, not icons read at runtime. * Therefore the actual file system icons displayed in the operating system * are not displayed in a FileSystemDataGrid, even though they are * accessible in AIR via the icon property of a File.

    * * @mxml * *

    The <mx:FileSystemDataGrid> tag inherits all of the tag * attributes of its superclass and adds the following tag attributes:

    * *
     *  <mx:FileSystemDataGrid
     *    Properties
     *    dateFormatString=""""
     *    directory=""null""
     *    enumerationMode=""directoriesFirst""
     *    extensions=""null""
     *    filterFunction=""null""
     *    nameCompareFunction=""null""
     *    selectedPath=""null""
     *    selectedPaths=""null""
     *    showExtensions=""true""
     *    showHidden=""false""
     *    showIcons=""true""
     * 
     *    Styles
     *    directoryIcon=""TreeNodeIcon""
     *    fileIcon=""TreeNodeIcon""
     * 
     *    Events
     *    directoryChange=""No default""
     *    directoryChanging=""No default""
     *    fileChoose=""No default""
     *  />
     *  
    * * @see flash.filesystem.File * * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class FileSystemDataGrid extends DataGrid { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @copy mx.controls.FileSystemList#COMPUTER * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const COMPUTER:File = FileSystemControlHelper.COMPUTER; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function FileSystemDataGrid() { super(); helper = new FileSystemControlHelper(this, false); doubleClickEnabled = true; horizontalScrollPolicy = ScrollPolicy.AUTO; iconFunction = helper.fileIconFunction; addEventListener(ListEvent.ITEM_DOUBLE_CLICK, itemDoubleClickHandler); dateFormatter.formatString = dateFormatString; // Set the initial dataProvider by enumerating the root directories. directory = COMPUTER; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * An undocumented class that implements functionality * shared by various file system components. */ mx_internal var helper:FileSystemControlHelper; /** * The DateFormatter object used to format the dates * in the Created and Modified columns. * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ mx_internal var dateFormatter:DateFormatter = new DateFormatter(); //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // backHistory //---------------------------------- [Bindable(""historyChanged"")] /** * An Array of File objects representing directories * to which the user can navigate backward. * *

    The first item in this Array is the next directory backward * in the history list. * The last item is the directory furthest backward * in the history list.

    * *

    This Array may contain a null item, which represents * the non-existent directory whose contents are root directories * such as C:\\ and D:\\ on Microsoft Windows.

    * *

    The following example shows how to use this property * along with the FileSystemHistoryButton control * to implement a back button:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:FileSystemHistoryButton label=""Back""
         *     enabled=""{fileSystemViewer.canNavigateBack}""
         *     dataProvider=""{fileSystemViewer.backHistory}""
         *     click=""fileSystemViewer.navigateBack();""
         *     itemClick=""fileSystemViewer.navigateBack(event.index);""/>
    * * @default [] * * @see #canNavigateBack * @see #navigateBack() * @see mx.controls.FileSystemHistoryButton * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get backHistory():Array { return helper.backHistory; } //---------------------------------- // canNavigateBack //---------------------------------- [Bindable(""historyChanged"")] /** * A flag which is true if there is at least one directory * in the history list to which the user can navigate backward. * *

    The following example shows how to use this property * along with the FileSystemHistoryButton control * to implement a back button:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:FileSystemHistoryButton label=""Back""
         *      enabled=""{fileSystemViewer.canNavigateBack}""
         *      dataProvider=""{fileSystemViewer.backHistory}""
         *      click=""fileSystemViewer.navigateBack();""
         *      itemClick=""fileSystemViewer.navigateBack(event.index);""/>
    * * @default false * * @see #backHistory * @see #navigateBack() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get canNavigateBack():Boolean { return helper.canNavigateBack; } //---------------------------------- // canNavigateDown //---------------------------------- [Bindable(""change"")] [Bindable(""directoryChanged"")] /** * A flag which is true if the user can navigate down * into a selected directory. * This flag is false when there is no selected item * or when the selected item is a file rather than a directory. * *

    The following example shows how to use this property * along with the Button control:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:Button label=""Open""
         *      enabled=""{fileSystemViewer.canNavigateDown}""
         *      click=""fileSystemViewer.navigateDown();""/>
    * * @default false * * @see #navigateDown() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get canNavigateDown():Boolean { return helper.canNavigateDown; } //---------------------------------- // canNavigateForward //---------------------------------- [Bindable(""historyChanged"")] /** * A flag which is true if there is at least one directory * in the history list to which the user can navigate forward. * *

    The following example shows how to use this property * along with the FileSystemHistoryButton control * to implement a forward button:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:FileSystemHistoryButton label=""Forward""
         *      enabled=""{fileSystemViewer.canNavigateForward}""
         *      dataProvider=""{fileSystemViewer.forwardHistory}""
         *      click=""fileSystemViewer.navigateForward();""
         *      itemClick=""fileSystemViewer.navigateForward(event.index);""/>
    * * @default false * * @see #forwardHistory * @see #navigateForward() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get canNavigateForward():Boolean { return helper.canNavigateForward; } //---------------------------------- // canNavigateUp //---------------------------------- [Bindable(""directoryChanged"")] /** * A flag which is true if the user can navigate up * to a parent directory. * This flag is only false when this control is * displaying the root directories such as C:\\ and D:\\ on Microsoft Windows. * (This is the case in which the directory * property is COMPUTER.) * *

    The following example shows how to use this property * along with the Button control:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:Button label=""Up""
         *      enabled=""{fileSystemViewer.canNavigateUp}""
         *      click=""fileSystemViewer.navigateUp();""/>
    * * @default false * * @see #navigateUp() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get canNavigateUp():Boolean { return helper.canNavigateUp; } //---------------------------------- // creationDateColumn //---------------------------------- /** * The DataGridColumn representing the Created column. * The FileSystemDataGrid control automatically creates this column. * *

    You can set properties such as * creationDateColumn.width to customize this column. * To remove this column entirely, or to change the column order, * set the columns property to an array such as * [ nameColumn, modificationDateColumn, sizeColumn ].

    * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var creationDateColumn:DataGridColumn; //---------------------------------- // dateFormatString //---------------------------------- /** * @private * Storage for the dateFormatString property. */ private var _dateFormatString:String; /** * @private */ private var dateFormatStringOverride:String; /** * A String that determines how dates in the Created and Modified * columns are formatted. * Setting this property sets the formatString * of an internal DateFormatter that this control creates. * * @see mx.formatters.DateFormatter#formatString * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dateFormatString():String { return _dateFormatString; } /** * @private */ public function set dateFormatString(value:String):void { dateFormatStringOverride = value; _dateFormatString = value != null ? value : resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_dateFormatString""); dateFormatter.formatString = _dateFormatString != null ? _dateFormatString : """"; invalidateList(); } //---------------------------------- // directory //---------------------------------- [Bindable(""directoryChanged"")] /** * @copy mx.controls.FileSystemList#directory * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get directory():File { return helper.directory; } /** * @private */ public function set directory(value:File):void { helper.directory = value; } //---------------------------------- // enumerationMode //---------------------------------- /** * @copy mx.controls.FileSystemList#enumerationMode * * @default FileSystemEnumerationMode.DIRECTORIES_FIRST * * @see mx.controls.FileSystemEnumerationMode * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get enumerationMode():String { return helper.enumerationMode; } /** * @private */ public function set enumerationMode(value:String):void { helper.enumerationMode = value; } //---------------------------------- // extensions //---------------------------------- /** * @copy mx.controls.FileSystemList#extensions * * @default null * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get extensions():Array /* of String */ { return helper.extensions; } /** * @private */ public function set extensions(value:Array /* of String */):void { helper.extensions = value; } //---------------------------------- // filterFunction //---------------------------------- /** * @copy mx.controls.FileSystemList#filterFunction * * @default null * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get filterFunction():Function { return helper.filterFunction; } /** * @private */ public function set filterFunction(value:Function):void { helper.filterFunction = value; } //---------------------------------- // forwardHistory //---------------------------------- [Bindable(""historyChanged"")] /** * An Array of File objects representing directories * to which the user can navigate forward. * *

    The first item in this Array is the next directory forward * in the history list. * The last item is the directory furthest forward * in the history list.

    * *

    This Array may contain a null item, which represents * the non-existent directory whose contents are root directories * such as C:\\ and D:\\ on Windows.

    * *

    The following example shows how to use this property * along with the FileSystemHistoryButton control to implement a forward button:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:FileSystemHistoryButton label=""Forward""
         *      enabled=""{fileSystemViewer.canNavigateForward}""
         *      dataProvider=""{fileSystemViewer.forwardHistory}""
         *      click=""fileSystemViewer.navigateForward();""
         *      itemClick=""fileSystemViewer.navigateForward(event.index);""/>
    * * @default [] * * @see mx.controls.FileSystemHistoryButton * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get forwardHistory():Array { return helper.forwardHistory; } //---------------------------------- // modificationDateColumn //---------------------------------- /** * The DataGridColumn representing the Modified column. * The FileSystemDataGrid control automatically creates this column. * *

    You can set properties such as * modificationDateColumn.width to customize this column. * To remove this column entirely, or to change the column order, * set the columns property to an array such as * [ nameColumn, modificationDateColumn, sizeColumn ].

    * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var modificationDateColumn:DataGridColumn; //---------------------------------- // nameColumn //---------------------------------- /** * The DataGridColumn representing the Name column. * The FileSystemDataGrid control automatically creates this column. * *

    You can set properties such as nameColumn.width * to customize this column. * To remove this column entirely, or to change the column order, * set the columns property to an array such as * [ nameColumn, modificationDateColumn, sizeColumn ].

    * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var nameColumn:DataGridColumn; //---------------------------------- // nameCompareFunction //---------------------------------- /** * @copy mx.controls.FileSystemList#nameCompareFunction * * @default null * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get nameCompareFunction():Function { return helper.nameCompareFunction; } /** * @private */ public function set nameCompareFunction(value:Function):void { helper.nameCompareFunction = value; } //---------------------------------- // selectedPath //---------------------------------- [Bindable(""change"")] [Bindable(""directoryChanged"")] /** * @copy mx.controls.FileSystemList#selectedPath * * @default null * * @see mx.controls.listClasses.ListBase#selectedIndex * @see mx.controls.listClasses.ListBase#selectedItem * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedPath():String { return helper.selectedPath; } /** * @private */ public function set selectedPath(value:String):void { helper.selectedPath = value; } //---------------------------------- // selectedPaths //---------------------------------- [Bindable(""change"")] [Bindable(""directoryChanged"")] /** * @copy mx.controls.FileSystemList#selectedPaths * * @default [] * * @see mx.controls.listClasses.ListBase#selectedIndex * @see mx.controls.listClasses.ListBase#selectedItem * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedPaths():Array /* of String */ { return helper.selectedPaths; } /** * @private */ public function set selectedPaths(value:Array /* of String */):void { helper.selectedPaths = value; } //---------------------------------- // showExtensions //---------------------------------- /** * @copy mx.controls.FileSystemList#showExtensions * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showExtensions():Boolean { return helper.showExtensions; } /** * @private */ public function set showExtensions(value:Boolean):void { helper.showExtensions = value; } //---------------------------------- // showHidden //---------------------------------- /** * @copy mx.controls.FileSystemList#showHidden * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showHidden():Boolean { return helper.showHidden; } /** * @private */ public function set showHidden(value:Boolean):void { helper.showHidden = value; } //---------------------------------- // showIcons //---------------------------------- /** * @copy mx.controls.FileSystemList#showIcons * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showIcons():Boolean { return helper.showIcons; } /** * @private */ public function set showIcons(value:Boolean):void { helper.showIcons = value; } //---------------------------------- // sizeColumn //---------------------------------- /** * The DataGridColumn representing the Size column. * The FileSystemDataGrid control automatically creates this column. * *

    You can set properties such as sizeColumn.width * to customize this column. * To remove this column entirely, or to change the column order, * set the columns property to an array such as * [ nameColumn, modificationDateColumn, sizeColumn ].

    * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var sizeColumn:DataGridColumn; //---------------------------------- // sizeDisplayMode //---------------------------------- /** * @private * Storage for the sizeDisplayMode property. */ private var _sizeDisplayMode:String = FileSystemSizeDisplayMode.KILOBYTES; /** * A String specifying whether the Size column displays file sizes * in bytes or rounded up to the nearest kilobyte, * where a kilobyte is 1024 bytes. * The possible values are specified * by the FileSystemSizeDisplayMode class. * * @see mx.controls.FileSystemSizeDisplayMode * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get sizeDisplayMode():String { return _sizeDisplayMode; } /** * @private */ public function set sizeDisplayMode(value:String):void { _sizeDisplayMode = value; invalidateList(); } //---------------------------------- // typeColumn //---------------------------------- /** * The DataGridColumn representing the Type column. * The FileSystemDataGrid control automatically creates this column. * *

    You can set properties such as typeColumn.width * to customize this column. * To remove this column entirely, or to change the column order, * set the columns property to an array such as * [ nameColumn, modificationDateColumn, sizeColumn ].

    * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var typeColumn:DataGridColumn; //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override protected function childrenCreated():void { super.childrenCreated(); var measuredText:String; nameColumn = new CustomDataGridColumn(); nameColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_nameColumnHeader""); nameColumn.itemRenderer = new ClassFactory(FileSystemDataGridNameColumnRenderer); nameColumn.labelFunction = helper.fileLabelFunction; nameColumn.sortCompareFunction = nameSortCompareFunction; measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_nameColumnMeasuredText""); nameColumn.width = determineWidthToDisplay(measuredText); typeColumn = new CustomDataGridColumn(); typeColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_typeColumnHeader""); typeColumn.labelFunction = typeLabelFunction; typeColumn.sortCompareFunction = typeSortCompareFunction; measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_typeColumnMeasuredText""); typeColumn.width = determineWidthToDisplay(measuredText); sizeColumn = new CustomDataGridColumn(); sizeColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_sizeColumnHeader""); sizeColumn.labelFunction = sizeLabelFunction; sizeColumn.public::setStyle(""textAlign"", ""right""); sizeColumn.sortCompareFunction = sizeSortCompareFunction; measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_sizeColumnMeasuredText""); sizeColumn.width = determineWidthToDisplay(measuredText); creationDateColumn = new CustomDataGridColumn(); creationDateColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_creationDateColumnHeader""); creationDateColumn.labelFunction = creationDateLabelFunction; measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_creationDateColumnMeasuredText""); creationDateColumn.width = determineWidthToDisplay(measuredText); modificationDateColumn = new CustomDataGridColumn(); modificationDateColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_modificationDateColumnHeader""); modificationDateColumn.labelFunction = modificationDateLabelFunction; measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_modificationDateColumnMeasuredText""); modificationDateColumn.width = determineWidthToDisplay(measuredText); // If DataGridColumns haven't already been defined, // use the five ones we just created. if (!columns || columns.length == 0) { columns = [ nameColumn, typeColumn, sizeColumn, creationDateColumn, modificationDateColumn ]; } } /** * @private */ override protected function commitProperties():void { // Call this before the supermethod // because it sets the dataProvider superproperty. helper.commitProperties(); super.commitProperties(); } /** * @private */ override protected function measure():void { super.measure(); measuredWidth += 16; } /** * @private */ override public function styleChanged(styleProp:String):void { super.styleChanged(styleProp); helper.styleChanged(styleProp); } /** * @private */ override protected function resourcesChanged():void { super.resourcesChanged(); var measuredText:String; if (nameColumn) { nameColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_nameColumnHeader""); measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_nameColumnMeasuredText""); nameColumn.width = determineWidthToDisplay(measuredText); } if (typeColumn) { typeColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_typeColumnHeader""); measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_typeColumnMeasuredText""); typeColumn.width = determineWidthToDisplay(measuredText); } if (sizeColumn) { sizeColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_sizeColumnHeader""); measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_sizeColumnMeasuredText""); sizeColumn.width = determineWidthToDisplay(measuredText); } if (creationDateColumn) { creationDateColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_creationDateColumnHeader""); measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_creationDateColumnMeasuredText""); creationDateColumn.width = determineWidthToDisplay(measuredText); } if (modificationDateColumn) { modificationDateColumn.headerText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_modificationDateColumnHeader""); measuredText = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_modificationDateColumnMeasuredText""); modificationDateColumn.width = determineWidthToDisplay(measuredText); } dateFormatString = dateFormatStringOverride; invalidateList(); invalidateSize(); } /** * @private */ override protected function itemToUID(data:Object):String { return helper.itemToUID(data); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @copy mx.controls.FileSystemList#findIndex() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function findIndex(nativePath:String):int { return helper.findIndex(nativePath); } /** * @copy mx.controls.FileSystemList#findItem() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function findItem(nativePath:String):File { return helper.findItem(nativePath); } /** * Changes this control to display the contents * of the selected subdirectory. * *

    If a subdirectory is not selected, this method does nothing.

    * *

    When this method returns, the directory property * contains the File instance for the new directory. * The dataProvider property is temporarily * null until the new directory has been enumerated. * After the enumeration, the dataProvider property * contains an ArrayCollection of File instances * for the new directory's contents.

    * *

    The following example shows how to use this method * along with the Button control to create an open button:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:Button label=""Open""
         *      enabled=""{fileSystemViewer.canNavigateDown}""
         *      click=""fileSystemViewer.navigateDown();""/>
    * * @see #canNavigateDown * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function navigateDown():void { helper.navigateDown(); } /** * Changes this control to display the contents of the next directory * up in the hierarchy. * *

    If this control is currently displaying root directories * (such as C: and D: on Microsoft Windows), this method does nothing.

    * *

    When this method returns, the directory property * contains the File instance for the new directory. * The dataProvider property is temporarily * null until the new directory has been enumerated. * After the enumeration, the dataProvider property * contains an ArrayCollection of File instances * for the new directory's contents.

    * *

    The following example shows how to use this property * along with the Button control to create an up button:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:Button label=""Up""
         *      enabled=""{fileSystemViewer.canNavigateUp}""
         *      click=""fileSystemViewer.navigateUp();""/>
    * * @see #canNavigateUp * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function navigateUp():void { helper.navigateUp(); } /** * Changes this control to display the contents of a previously-visited * directory in the backHistory array. * *

    If the backHistory array is empty, or if you specify * an index that is not in that array, then this method does nothing.

    * *

    When this method returns, the directory property * contains the File instance for the new directory. * The dataProvider property is temporarily * null until the new directory has been enumerated. * After the enumeration, the dataProvider property * contains an ArrayCollection of File instances * for the new directory's contents.

    * *

    The history list is left unchanged. However, the current index * into it changes, which affects the backHistory * and forwardHistory properties. * They have new values as soon as this method returns.

    * *

    The following example shows how to use this method * along with the FileSystemHistoryButton control to create a back button:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:FileSystemHistoryButton label=""Back""
         *      enabled=""{fileSystemViewer.canNavigateBack}""
         *      dataProvider=""{fileSystemViewer.backHistory}""
         *      click=""fileSystemViewer.navigateBack();""
         *      itemClick=""fileSystemViewer.navigateBack(event.index);""/>
    * * @param index The index in the backHistory array * to navigate to. * The default is 0, indicating the directory that is ""closest back"". * * @see #backHistory * @see #canNavigateBack * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function navigateBack(index:int = 0):void { helper.navigateBack(index); } /** * Changes this control to display the contents of a previously-visited * directory in the forwardHistory array. * *

    If the forwardHistory array is empty, or if you specify * an index that is not in that array, then this method does nothing.

    * *

    When this method returns, the directory property * contains the File instance for the new directory. * The dataProvider property is temporarily * null until the new directory has been enumerated. * After the enumeration, the dataProvider property * contains an ArrayCollection of File instances * for the new directory's contents.

    * *

    The history list is left unchanged. However, the current index * into it changes, which affects the backHistory * and forwardHistory properties. * They have new values as soon as this method returns.

    * *

    The following example shows how to use this method * along with the FileSystemHistoryButton control to create a forward button:

    * *
         *  <mx:FileSystemDataGrid id=""fileSystemViewer"" directory=""{File.desktopDirectory}""/>
         *  <mx:FileSystemHistoryButton label=""Forward""
         *      enabled=""{fileSystemViewer.canNavigateForward}""
         *      dataProvider=""{fileSystemViewer.forwardHistory}""
         *      click=""fileSystemViewer.navigateForward();""
         *      itemClick=""fileSystemViewer.navigateForward(event.index);""/>
    * * @param index The index in the forwardHistory array * to navigate to. * The default is 0, indicating the directory that is ""closest forward"". * * @see #canNavigateForward * @see #forwardHistory * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function navigateForward(index:int = 0):void { helper.navigateForward(index); } /** * @copy mx.controls.FileSystemList#navigateTo() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function navigateTo(directory:File):void { helper.navigateTo(directory); } /** * @copy mx.controls.FileSystemList#refresh() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function refresh():void { helper.refresh(); } /** * @copy mx.controls.FileSystemList#clear() * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function clear():void { helper.clear(); } /** * @private */ public function resetHistory(dir:File):void { helper.resetHistory(dir); } /** * @private */ private function nameSortCompareFunction(item1:File, item2:File):int { return helper.directoryEnumeration.fileCompareFunction(item1, item2); } /** * @private */ private function typeLabelFunction(item:File, column:DataGridColumn = null):String { // If item is a directory, return ""Folder"". if (item.isDirectory) { return resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_typeFolder""); } // If item is a file without an extension, return ""File"". var extension:String = item.extension; if (!extension || extension == """") { return resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_typeFileWithoutExtension""); } // If item is a file with an extension, return a String like ""TXT File"". return resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_typeFileWithExtension"", [ extension.toUpperCase() ]); } /** * @private */ private function typeSortCompareFunction(item1:File, item2:File):int { var typeLabel1:String = typeLabelFunction(item1, null).toUpperCase(); var typeLabel2:String = typeLabelFunction(item2, null).toUpperCase(); if (typeLabel1 < typeLabel2) return -1; if (typeLabel1 > typeLabel2) return 1; return 0; } /** * @private */ private function sizeLabelFunction(item:File, column:DataGridColumn = null):String { var label:String; if (!item.exists) // item may have been deleted return """"; try { if (item.isDirectory) { label = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_sizeFolder""); } else if (sizeDisplayMode == FileSystemSizeDisplayMode.KILOBYTES) { var kb:int = Math.ceil(item.size / 1024); label = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_sizeKilobytes"", [ kb ]); } else if (sizeDisplayMode == FileSystemSizeDisplayMode.BYTES) { label = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_sizeBytes"", [ item.size ]); } } catch(e:Error) { // item.size throws a File I/O Error for some files, // such as /etc/master.passwd and /etc/sudoers on a Mac label = resourceManager.getString( ""aircontrols"", ""fileSystemDataGrid_sizeFolder""); } return label; } /** * @private */ private function sizeSortCompareFunction(item1:File, item2:File):int { var size1:Number; try { size1 = item1.isDirectory ? 0 : item1.size; } catch(e1:Error) { // item.size throws a File I/O Error for some files, // such as /etc/master.passwd and /etc/sudoers on a Mac size1 = 0; } var size2:Number; try { size2 = item2.isDirectory ? 0 : item2.size; } catch(e2:Error) { size2 = 0; } if (size1 < size2) return -1; if (size1 > size2) return 1; return 0; } /** * @private */ private function creationDateLabelFunction( item:File, column:DataGridColumn = null):String { if (!item.exists) // item may have been deleted return """"; return dateFormatter.format(item.creationDate); } /** * @private */ private function modificationDateLabelFunction( item:File, column:DataGridColumn = null):String { if (!item.exists) // item may have been deleted return """"; return dateFormatter.format(item.modificationDate); } /** * @private */ private function determineWidthToDisplay(s:String):Number { return measureText(s).width + 13; } //-------------------------------------------------------------------------- // // Overridden event handlers // //-------------------------------------------------------------------------- /** * @private */ override protected function keyDownHandler(event:KeyboardEvent):void { if (helper.handleKeyDown(event)) return; super.keyDownHandler(event); } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ protected function itemDoubleClickHandler(event:ListEvent):void { helper.itemDoubleClickHandler(event); } } } //////////////////////////////////////////////////////////////////////////////// // // Helper classes // //////////////////////////////////////////////////////////////////////////////// import flash.display.DisplayObject; import flash.filesystem.File; import mx.controls.dataGridClasses.DataGridColumn; import mx.controls.dataGridClasses.DataGridListData; import mx.controls.listClasses.BaseListData; import mx.controls.FileSystemDataGrid; import mx.controls.listClasses.IDropInListItemRenderer; import mx.controls.listClasses.IListItemRenderer; import mx.controls.listClasses.ListBase; import mx.core.IDataRenderer; import mx.core.IFlexDisplayObject; import mx.core.mx_internal; import mx.core.UIComponent; import mx.core.UITextField; import mx.events.FlexEvent; import mx.core.IUITextField; //////////////////////////////////////////////////////////////////////////////// // // Helper class: CustomDataGridColumn // //////////////////////////////////////////////////////////////////////////////// /** * @private */ class CustomDataGridColumn extends DataGridColumn { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function CustomDataGridColumn(columnName:String = null) { super(columnName); } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ override public function itemToDataTip(data:Object):String { return labelFunction(data); } }",12503,True,2758.0998721549536,median "[id=""deploymentconfig-apps-openshift-io-v1""] = DeploymentConfig [apps.openshift.io/v1] ifdef::product-title[] include::modules/common-attributes.adoc[] endif::[] toc::[] Description:: Deployment Configs define the template for a pod and manages deploying new images or configuration changes. A single deployment configuration is usually analogous to a single micro-service. Can support many different deployment patterns, including full restart, customizable rolling updates, and fully custom behaviors, as well as pre- and post- deployment hooks. Each individual deployment is represented as a replication controller. A deployment is ""triggered"" when its configuration is changed or a tag in an Image Stream is changed. Triggers can be disabled to allow manual control over a deployment. The ""strategy"" determines how the deployment is carried out and may be changed at any time. The `latestVersion` field is updated when a new deployment is triggered by any means. Type:: `object` Required:: - `spec` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `.apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `.kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `.metadata` | xref:../objects/index.adoc#objectmeta-meta-v1[`ObjectMeta meta/v1`] | | `.spec` | `object` | DeploymentConfigSpec represents the desired state of the deployment. | `.status` | `object` | DeploymentConfigStatus represents the current deployment state. |=== ..spec Description:: DeploymentConfigSpec represents the desired state of the deployment. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `minReadySeconds` | `integer` | MinReadySeconds is the minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready) | `paused` | `boolean` | Paused indicates that the deployment config is paused resulting in no new deployments on template changes or changes in the template caused by other triggers. | `replicas` | `integer` | Replicas is the number of desired replicas. | `revisionHistoryLimit` | `integer` | RevisionHistoryLimit is the number of old ReplicationControllers to retain to allow for rollbacks. This field is a pointer to allow for differentiation between an explicit zero and not specified. Defaults to 10. (This only applies to DeploymentConfigs created via the new group API resource, not the legacy resource.) | `selector` | `object (string)` | Selector is a label query over pods that should match the Replicas count. | `strategy` | `object` | DeploymentStrategy describes how to perform a deployment. | `template` | xref:../objects/index.adoc#podtemplatespec-core-v1[`PodTemplateSpec core/v1`] | Template is the object that describes the pod that will be created if insufficient replicas are detected. | `test` | `boolean` | Test ensures that this deployment config will have zero replicas except while a deployment is running. This allows the deployment config to be used as a continuous deployment test - triggering on images, running the deployment, and then succeeding or failing. Post strategy hooks and After actions can be used to integrate successful deployment with an action. | `triggers` | `array` | Triggers determine how updates to a DeploymentConfig result in new deployments. If no triggers are defined, a new deployment can only occur as a result of an explicit client update to the DeploymentConfig with a new LatestVersion. If null, defaults to having a config change trigger. | `triggers[]` | `object` | DeploymentTriggerPolicy describes a policy for a single trigger that results in a new deployment. |=== ..spec.strategy Description:: DeploymentStrategy describes how to perform a deployment. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `activeDeadlineSeconds` | `integer` | ActiveDeadlineSeconds is the duration in seconds that the deployer pods for this deployment config may be active on a node before the system actively tries to terminate them. | `annotations` | `object (string)` | Annotations is a set of key, value pairs added to custom deployer and lifecycle pre/post hook pods. | `customParams` | `object` | CustomDeploymentStrategyParams are the input to the Custom deployment strategy. | `labels` | `object (string)` | Labels is a set of key, value pairs added to custom deployer and lifecycle pre/post hook pods. | `recreateParams` | `object` | RecreateDeploymentStrategyParams are the input to the Recreate deployment strategy. | `resources` | xref:../objects/index.adoc#resourcerequirements-core-v1[`ResourceRequirements core/v1`] | Resources contains resource requirements to execute the deployment and any hooks. | `rollingParams` | `object` | RollingDeploymentStrategyParams are the input to the Rolling deployment strategy. | `type` | `string` | Type is the name of a deployment strategy. |=== ..spec.strategy.customParams Description:: CustomDeploymentStrategyParams are the input to the Custom deployment strategy. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is optional and overrides CMD in the container Image. | `environment` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Environment holds the environment which will be given to the container for Image. | `image` | `string` | Image specifies a container image which can carry out a deployment. |=== ..spec.strategy.recreateParams Description:: RecreateDeploymentStrategyParams are the input to the Recreate deployment strategy. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `mid` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `post` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `pre` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `timeoutSeconds` | `integer` | TimeoutSeconds is the time to wait for updates before giving up. If the value is nil, a default will be used. |=== ..spec.strategy.recreateParams.mid Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.recreateParams.mid.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.recreateParams.mid.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.recreateParams.mid.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.strategy.recreateParams.post Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.recreateParams.post.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.recreateParams.post.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.recreateParams.post.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.strategy.recreateParams.pre Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.recreateParams.pre.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.recreateParams.pre.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.recreateParams.pre.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.strategy.rollingParams Description:: RollingDeploymentStrategyParams are the input to the Rolling deployment strategy. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `intervalSeconds` | `integer` | IntervalSeconds is the time to wait between polling deployment status after update. If the value is nil, a default will be used. | `maxSurge` | xref:../objects/index.adoc#intorstring-util-intstr[`IntOrString util/intstr`] | MaxSurge is the maximum number of pods that can be scheduled above the original number of pods. Value can be an absolute number (ex: 5) or a percentage of total pods at the start of the update (ex: 10%). Absolute number is calculated from percentage by rounding up. This cannot be 0 if MaxUnavailable is 0. By default, 25% is used. Example: when this is set to 30%, the new RC can be scaled up by 30% immediately when the rolling update starts. Once old pods have been killed, new RC can be scaled up further, ensuring that total number of pods running at any time during the update is atmost 130% of original pods. | `maxUnavailable` | xref:../objects/index.adoc#intorstring-util-intstr[`IntOrString util/intstr`] | MaxUnavailable is the maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of total pods at the start of update (ex: 10%). Absolute number is calculated from percentage by rounding down. This cannot be 0 if MaxSurge is 0. By default, 25% is used. Example: when this is set to 30%, the old RC can be scaled down by 30% immediately when the rolling update starts. Once new pods are ready, old RC can be scaled down further, followed by scaling up the new RC, ensuring that at least 70% of original number of pods are available at all times during the update. | `post` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `pre` | `object` | LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. | `timeoutSeconds` | `integer` | TimeoutSeconds is the time to wait for updates before giving up. If the value is nil, a default will be used. | `updatePeriodSeconds` | `integer` | UpdatePeriodSeconds is the time to wait between individual pod updates. If the value is nil, a default will be used. |=== ..spec.strategy.rollingParams.post Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.rollingParams.post.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.rollingParams.post.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.rollingParams.post.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.strategy.rollingParams.pre Description:: LifecycleHook defines a specific deployment lifecycle action. Only one type of action may be specified at any time. Type:: `object` Required:: - `failurePolicy` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `execNewPod` | `object` | ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. | `failurePolicy` | `string` | FailurePolicy specifies what action to take if the hook fails. | `tagImages` | `array` | TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. | `tagImages[]` | `object` | TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. |=== ..spec.strategy.rollingParams.pre.execNewPod Description:: ExecNewPodHook is a hook implementation which runs a command in a new pod based on the specified container which is assumed to be part of the deployment template. Type:: `object` Required:: - `command` - `containerName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `command` | `array (string)` | Command is the action command and its arguments. | `containerName` | `string` | ContainerName is the name of a container in the deployment pod template whose container image will be used for the hook pod's container. | `env` | xref:../objects/index.adoc#envvar-core-v1[`array (EnvVar core/v1)`] | Env is a set of environment variables to supply to the hook pod's container. | `volumes` | `array (string)` | Volumes is a list of named volumes from the pod template which should be copied to the hook pod. Volumes names not found in pod spec are ignored. An empty list means no volumes will be copied. |=== ..spec.strategy.rollingParams.pre.tagImages Description:: TagImages instructs the deployer to tag the current image referenced under a container onto an image stream tag. Type:: `array` ..spec.strategy.rollingParams.pre.tagImages[] Description:: TagImageHook is a request to tag the image in a particular container onto an ImageStreamTag. Type:: `object` Required:: - `containerName` - `to` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `containerName` | `string` | ContainerName is the name of a container in the deployment config whose image value will be used as the source of the tag. If there is only a single container this value will be defaulted to the name of that container. | `to` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | To is the target ImageStreamTag to set the container's image onto. |=== ..spec.triggers Description:: Triggers determine how updates to a DeploymentConfig result in new deployments. If no triggers are defined, a new deployment can only occur as a result of an explicit client update to the DeploymentConfig with a new LatestVersion. If null, defaults to having a config change trigger. Type:: `array` ..spec.triggers[] Description:: DeploymentTriggerPolicy describes a policy for a single trigger that results in a new deployment. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `imageChangeParams` | `object` | DeploymentTriggerImageChangeParams represents the parameters to the ImageChange trigger. | `type` | `string` | Type of the trigger |=== ..spec.triggers[].imageChangeParams Description:: DeploymentTriggerImageChangeParams represents the parameters to the ImageChange trigger. Type:: `object` Required:: - `from` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `automatic` | `boolean` | Automatic means that the detection of a new tag value should result in an image update inside the pod template. | `containerNames` | `array (string)` | ContainerNames is used to restrict tag updates to the specified set of container names in a pod. If multiple triggers point to the same containers, the resulting behavior is undefined. Future API versions will make this a validation error. If ContainerNames does not point to a valid container, the trigger will be ignored. Future API versions will make this a validation error. | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | From is a reference to an image stream tag to watch for changes. From.Name is the only required subfield - if From.Namespace is blank, the namespace of the current deployment trigger will be used. | `lastTriggeredImage` | `string` | LastTriggeredImage is the last image to be triggered. |=== ..status Description:: DeploymentConfigStatus represents the current deployment state. Type:: `object` Required:: - `latestVersion` - `observedGeneration` - `replicas` - `updatedReplicas` - `availableReplicas` - `unavailableReplicas` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `availableReplicas` | `integer` | AvailableReplicas is the total number of available pods targeted by this deployment config. | `conditions` | `array` | Conditions represents the latest available observations of a deployment config's current state. | `conditions[]` | `object` | DeploymentCondition describes the state of a deployment config at a certain point. | `details` | `object` | DeploymentDetails captures information about the causes of a deployment. | `latestVersion` | `integer` | LatestVersion is used to determine whether the current deployment associated with a deployment config is out of sync. | `observedGeneration` | `integer` | ObservedGeneration is the most recent generation observed by the deployment config controller. | `readyReplicas` | `integer` | Total number of ready pods targeted by this deployment. | `replicas` | `integer` | Replicas is the total number of pods targeted by this deployment config. | `unavailableReplicas` | `integer` | UnavailableReplicas is the total number of unavailable pods targeted by this deployment config. | `updatedReplicas` | `integer` | UpdatedReplicas is the total number of non-terminated pods targeted by this deployment config that have the desired template spec. |=== ..status.conditions Description:: Conditions represents the latest available observations of a deployment config's current state. Type:: `array` ..status.conditions[] Description:: DeploymentCondition describes the state of a deployment config at a certain point. Type:: `object` Required:: - `type` - `status` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `lastTransitionTime` | xref:../objects/index.adoc#time-meta-v1[`Time meta/v1`] | The last time the condition transitioned from one status to another. | `lastUpdateTime` | xref:../objects/index.adoc#time-meta-v1[`Time meta/v1`] | The last time this condition was updated. | `message` | `string` | A human readable message indicating details about the transition. | `reason` | `string` | The reason for the condition's last transition. | `status` | `string` | Status of the condition, one of True, False, Unknown. | `type` | `string` | Type of deployment condition. |=== ..status.details Description:: DeploymentDetails captures information about the causes of a deployment. Type:: `object` Required:: - `causes` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `causes` | `array` | Causes are extended data associated with all the causes for creating a new deployment | `causes[]` | `object` | DeploymentCause captures information about a particular cause of a deployment. | `message` | `string` | Message is the user specified change message, if this deployment was triggered manually by the user |=== ..status.details.causes Description:: Causes are extended data associated with all the causes for creating a new deployment Type:: `array` ..status.details.causes[] Description:: DeploymentCause captures information about a particular cause of a deployment. Type:: `object` Required:: - `type` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `imageTrigger` | `object` | DeploymentCauseImageTrigger represents details about the cause of a deployment originating from an image change trigger | `type` | `string` | Type of the trigger that resulted in the creation of a new deployment |=== ..status.details.causes[].imageTrigger Description:: DeploymentCauseImageTrigger represents details about the cause of a deployment originating from an image change trigger Type:: `object` Required:: - `from` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `from` | xref:../objects/index.adoc#objectreference-core-v1[`ObjectReference core/v1`] | From is a reference to the changed object which triggered a deployment. The field may have the kinds DockerImage, ImageStreamTag, or ImageStreamImage. |=== == API endpoints The following API endpoints are available: * `/apis/apps.openshift.io/v1/deploymentconfigs` - `GET`: list or watch objects of kind DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs` - `DELETE`: delete collection of DeploymentConfig - `GET`: list or watch objects of kind DeploymentConfig - `POST`: create a DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}` - `DELETE`: delete a DeploymentConfig - `GET`: read the specified DeploymentConfig - `PATCH`: partially update the specified DeploymentConfig - `PUT`: replace the specified DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/log` - `GET`: read log of the specified DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/scale` - `GET`: read scale of the specified DeploymentConfig - `PATCH`: partially update scale of the specified DeploymentConfig - `PUT`: replace scale of the specified DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/status` - `GET`: read status of the specified DeploymentConfig - `PATCH`: partially update status of the specified DeploymentConfig - `PUT`: replace status of the specified DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/rollback` - `POST`: create rollback of a DeploymentConfig * `/apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/instantiate` - `POST`: create instantiate of a DeploymentConfig === /apis/apps.openshift.io/v1/deploymentconfigs .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: list or watch objects of kind DeploymentConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentconfiglist-apps-openshift-io-v1[`DeploymentConfigList apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deleteoptions-meta-v1[`DeleteOptions meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list or watch objects of kind DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentconfiglist-apps-openshift-io-v1[`DeploymentConfigList apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 201 - Created | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 202 - Accepted | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentConfig | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deleteoptions-meta-v1[`DeleteOptions meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 202 - Accepted | xref:../objects/index.adoc#status-meta-v1[`Status meta/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `exact` | `boolean` | Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. | `export` | `boolean` | Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 201 - Created | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/log .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentLog | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `container` | `string` | The container for which to stream logs. Defaults to only container if there is one container in the pod. | `follow` | `boolean` | Follow if true indicates that the build log should be streamed until the build terminates. | `limitBytes` | `integer` | If set, the number of bytes to read from the server before terminating the log output. This may not display a complete final line of logging, and may return slightly more or slightly less than the specified limit. | `nowait` | `boolean` | NoWait if true causes the call to return immediately even if the deployment is not available yet. Otherwise the server will wait until the deployment has started. | `pretty` | `string` | If 'true', then the output is pretty printed. | `previous` | `boolean` | Return previous deployment logs. Defaults to false. | `sinceSeconds` | `integer` | A relative time in seconds before the current time from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified. | `tailLines` | `integer` | If set, the number of lines from the end of the logs to show. If not specified, logs are shown from the creation of the container or sinceSeconds or sinceTime | `timestamps` | `boolean` | If true, add an RFC3339 or RFC3339Nano timestamp at the beginning of every line of log output. Defaults to false. | `version` | `integer` | Version of the deployment for which to view logs. |=== HTTP method:: `GET` Description:: read log of the specified DeploymentConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentlog-apps-openshift-io-v1[`DeploymentLog apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/scale .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Scale | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read scale of the specified DeploymentConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update scale of the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace scale of the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | 201 - Created | xref:../objects/index.adoc#scale-extensions-v1beta1[`Scale extensions/v1beta1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentConfig | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified DeploymentConfig .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified DeploymentConfig .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 201 - Created | xref:../workloads_apis/deploymentconfig-apps-openshift-io-v1.adoc#deploymentconfig-apps-openshift-io-v1[`DeploymentConfig apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/rollback .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentConfigRollback | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `POST` Description:: create rollback of a DeploymentConfig .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deploymentconfigrollback-apps-openshift-io-v1[`DeploymentConfigRollback apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentconfigrollback-apps-openshift-io-v1[`DeploymentConfigRollback apps.openshift.io/v1`] | 201 - Created | xref:../objects/index.adoc#deploymentconfigrollback-apps-openshift-io-v1[`DeploymentConfigRollback apps.openshift.io/v1`] | 202 - Accepted | xref:../objects/index.adoc#deploymentconfigrollback-apps-openshift-io-v1[`DeploymentConfigRollback apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== === /apis/apps.openshift.io/v1/namespaces/{namespace}/deploymentconfigs/{name}/instantiate .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the DeploymentRequest | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `POST` Description:: create instantiate of a DeploymentConfig .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deploymentrequest-apps-openshift-io-v1[`DeploymentRequest apps.openshift.io/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#deploymentrequest-apps-openshift-io-v1[`DeploymentRequest apps.openshift.io/v1`] | 201 - Created | xref:../objects/index.adoc#deploymentrequest-apps-openshift-io-v1[`DeploymentRequest apps.openshift.io/v1`] | 202 - Accepted | xref:../objects/index.adoc#deploymentrequest-apps-openshift-io-v1[`DeploymentRequest apps.openshift.io/v1`] | 401 - Unauthorized | Empty |=== ",16345,True,3225.556925011504,median "// ================================================================================================= // // MyFLashLab Team www.myflashlabs.com // Copyright 2014 All Rights Reserved. // // Based on Starling Framework BitmapFont TextField // // This program is free software. You can redistribute and/or modify it // in accordance with the terms of the accompanying license agreement. // // ================================================================================================= package starling.extensions.RTL_BitmapFont { import flash.display.BitmapData; import flash.geom.Rectangle; import flash.utils.ByteArray; import starling.textures.Texture; /** @private * This class contains constants for the 'MINI' bitmap font. It's done that way to avoid * a dependency on the 'mx.core' library (which is required for the 'Embed' statement). * *

    The font is based on ""uni05_53.ttf"" from Craig Kroeger (http://www.miniml.com) and was * converted to a Bitmap Font with ""GlyphDesigner"" from 71squared (http://www.71squared.com). *

    */ internal class MiniBitmapFont { private static const BITMAP_WIDTH:int = 128; private static const BITMAP_HEIGHT:int = 64; private static const BITMAP_DATA:Array = [ 2027613533, 3413039936, 202148514, 2266925598, 4206886452, 4286853117, 2034947, 3202703399, 352977282, 2957757964, 3113652880, 2158068882, 1468709156, 2268063717, 2779310143, 2101025806, 3416509055, 4215794539, 3602168838, 1038056207, 1932393374, 3182285627, 3086802234, 1741291262, 2017257123, 3395280843, 984074419, 3049693147, 3986077023, 1055013549, 1806563255, 1754714962, 1577746187, 1124058786, 3888759258, 2482229043, 2916583666, 3743065328, 866060213, 1695195001, 2401582068, 3113347901, 2616521596, 1053798161, 2093370968, 4229025683, 560451479, 854767518, 2610241322, 4279041348, 4181572480, 4031244973, 587139110, 1081376765, 962217926, 783603325, 3605526425, 4102001916, 289204733, 2635140255, 3453981695, 3487854373, 2132197241, 3164775074, 4257640328, 770238970, 144664537, 707141570, 2934433071, 871272893, 512964596, 808491899, 481894297, 3095982481, 3598364156, 1710636358, 2904016319, 1751040139, 596966466, 1363963692, 465815609, 315567311, 4290666159, 4086022551, 179721458, 2221734970, 3942224988, 1519355876, 3292323782, 3933427230, 3314199893, 3736227348, 3846038425, 603088884, 2677349227, 3207069327, 3555275967, 3063054283, 3064577213, 3412044179, 693642210, 4280513949, 762928717, 1802215333, 3774849674, 4221155330, 970959395, 557220237, 2107226136, 3509822982, 3403284788, 4265820019, 898597576, 991077243, 2091615904, 3334716888, 633599866, 4218780109, 2216000376, 834870947, 2118009742, 1362731961, 236280636, 1274945142, 1458729366, 797960805, 3289369720, 2103717340, 3946406003, 2676522889, 1624104606, 1156993903, 3186170404, 2254499071, 1204911924, 1314218830, 3307086392, 2824275959, 3839865679, 2073394964, 1873329433, 1754205930, 1528429545, 1631106062, 2263272465, 4220497047, 3522893765, 3641376303, 707451487, 3452496787, 1390653868, 2620555793, 1027328684, 3419683476, 3662193703, 765701986, 3808279132, 786403271, 3824435837, 713234896, 4261856399, 3471930731, 3993492879, 1447960461, 1398434593, 1914230187, 2398643285, 4156374464, 3859339207, 3220700061, 3373248762, 3186030434, 1315917060, 2809852481, 4008553903, 4105611953, 1599499652, 3513857591, 877854499, 4198259455, 3648560077, 2838035419, 3255594190, 2465578457, 4263505201, 534904657, 2889261598, 1358214576, 1069250354, 3870010557, 2628896583, 3448610878, 442343309, 1024736866, 4015119133, 3250867279, 1513359261, 2442089596, 1944476762, 735490552, 426990058, 4234106111, 1204305707, 3330995265, 2398649368, 4221048123, 1724669255, 3801115709, 3489328790, 3896402933, 3696936939, 2836983295, 3656750393, 3349724512, 3810416287, 3654997608, 4284455103, 2294939563, 4207697932, 642748805, 2476981639, 2319419898, 572956615, 3833238940, 964924880, 2081600351, 3572458416, 2056247513, 1951368808, 2133449703, 2783728628, 512866577, 913279200, 1678129016, 3488578991, 3373952929, 2562996951, 3666058925, 1664169178, 1943591935, 750675303, 154399903, 2571590890, 852654952, 4117307766, 1971649621, 4180195820, 1222535348, 4283953215, 2880662236, 2717410980, 1175907705, 1157322027, 505963121, 2631540616, 3661227656, 3591803353, 2624126821, 1948662907, 3596065103, 1147387734, 256773959, 1173572460, 2361957471, 4210876076, 3080180620, 3464801210, 3821654259, 1465302035, 2851185457, 3143266144, 3793180414, 3368833103, 4274670712, 3473819108, 3487569332, 773123355, 1618635668, 2570176190, 2075248691, 1740805534, 288646743, 1837597401, 603556968, 3182536872, 673184603, 3088757053, 2897054404, 3192651316, 2885335802, 1057233368, 1118437241, 4182126463, 3110464775, 3313191614, 2360987274, 735505357, 2992631425, 2360928811, 4187834527, 279183208, 1586420003, 1174008423, 4062987589, 1162167621, 1162167621, 1162167621, 1162167621, 1174119799, 787274608 ]; private static const XML_DATA:XML = ; public static function get texture():Texture { var bmpData:BitmapData = new BitmapData(BITMAP_WIDTH, BITMAP_HEIGHT); var bmpBytes:ByteArray = new ByteArray(); var numBytes:int = BITMAP_DATA.length; for (var i:int=0; i = new []; private static const LOCATION_HELPER_VECTOR:Vector. = new []; public function TreeDataViewPort() { super(); } private var _viewPortBounds:ViewPortBounds = new ViewPortBounds(); private var _layoutResult:LayoutBoundsResult = new LayoutBoundsResult(); private var _actualMinVisibleWidth:Number = 0; private var _explicitMinVisibleWidth:Number; public function get minVisibleWidth():Number { if(this._explicitMinVisibleWidth !== this._explicitMinVisibleWidth) //isNaN { return this._actualMinVisibleWidth; } return this._explicitMinVisibleWidth; } public function set minVisibleWidth(value:Number):void { if(this._explicitMinVisibleWidth == value) { return; } var valueIsNaN:Boolean = value !== value; //isNaN if(valueIsNaN && this._explicitMinVisibleWidth !== this._explicitMinVisibleWidth) //isNaN { return; } var oldValue:Number = this._explicitMinVisibleWidth; this._explicitMinVisibleWidth = value; if(valueIsNaN) { this._actualMinVisibleWidth = 0; this.invalidate(INVALIDATION_FLAG_SIZE); } else { this._actualMinVisibleWidth = value; if(this._explicitVisibleWidth !== this._explicitVisibleWidth && //isNaN (this._actualVisibleWidth < value || this._actualVisibleWidth == oldValue)) { //only invalidate if this change might affect the visibleWidth this.invalidate(INVALIDATION_FLAG_SIZE); } } } private var _maxVisibleWidth:Number = Number.POSITIVE_INFINITY; public function get maxVisibleWidth():Number { return this._maxVisibleWidth; } public function set maxVisibleWidth(value:Number):void { if(this._maxVisibleWidth == value) { return; } if(value !== value) //isNaN { throw new ArgumentError(""maxVisibleWidth cannot be NaN""); } var oldValue:Number = this._maxVisibleWidth; this._maxVisibleWidth = value; if(this._explicitVisibleWidth !== this._explicitVisibleWidth && //isNaN (this._actualVisibleWidth > value || this._actualVisibleWidth == oldValue)) { //only invalidate if this change might affect the visibleWidth this.invalidate(INVALIDATION_FLAG_SIZE); } } private var _actualVisibleWidth:Number = NaN; private var _explicitVisibleWidth:Number = NaN; public function get visibleWidth():Number { return this._actualVisibleWidth; } public function set visibleWidth(value:Number):void { if(this._explicitVisibleWidth == value || (value !== value && this._explicitVisibleWidth !== this._explicitVisibleWidth)) //isNaN { return; } this._explicitVisibleWidth = value; if(this._actualVisibleWidth != value) { this.invalidate(INVALIDATION_FLAG_SIZE); } } private var _actualMinVisibleHeight:Number = 0; private var _explicitMinVisibleHeight:Number; public function get minVisibleHeight():Number { if(this._explicitMinVisibleHeight !== this._explicitMinVisibleHeight) //isNaN { return this._actualMinVisibleHeight; } return this._explicitMinVisibleHeight; } public function set minVisibleHeight(value:Number):void { if(this._explicitMinVisibleHeight == value) { return; } var valueIsNaN:Boolean = value !== value; //isNaN if(valueIsNaN && this._explicitMinVisibleHeight !== this._explicitMinVisibleHeight) //isNaN { return; } var oldValue:Number = this._explicitMinVisibleHeight; this._explicitMinVisibleHeight = value; if(valueIsNaN) { this._actualMinVisibleHeight = 0; this.invalidate(INVALIDATION_FLAG_SIZE); } else { this._actualMinVisibleHeight = value; if(this._explicitVisibleHeight !== this._explicitVisibleHeight && //isNaN (this._actualVisibleHeight < value || this._actualVisibleHeight == oldValue)) { //only invalidate if this change might affect the visibleHeight this.invalidate(INVALIDATION_FLAG_SIZE); } } } private var _maxVisibleHeight:Number = Number.POSITIVE_INFINITY; public function get maxVisibleHeight():Number { return this._maxVisibleHeight; } public function set maxVisibleHeight(value:Number):void { if(this._maxVisibleHeight == value) { return; } if(value !== value) //isNaN { throw new ArgumentError(""maxVisibleHeight cannot be NaN""); } var oldValue:Number = this._maxVisibleHeight; this._maxVisibleHeight = value; if(this._explicitVisibleHeight !== this._explicitVisibleHeight && //isNaN (this._actualVisibleHeight > value || this._actualVisibleHeight == oldValue)) { //only invalidate if this change might affect the visibleHeight this.invalidate(INVALIDATION_FLAG_SIZE); } } private var _actualVisibleHeight:Number; private var _explicitVisibleHeight:Number = NaN; public function get visibleHeight():Number { return this._actualVisibleHeight; } public function set visibleHeight(value:Number):void { if(this._explicitVisibleHeight == value || (value !== value && this._explicitVisibleHeight !== this._explicitVisibleHeight)) //isNaN { return; } this._explicitVisibleHeight = value; if(this._actualVisibleHeight != value) { this.invalidate(INVALIDATION_FLAG_SIZE); } } protected var _contentX:Number = 0; public function get contentX():Number { return this._contentX; } protected var _contentY:Number = 0; public function get contentY():Number { return this._contentY; } public function get horizontalScrollStep():Number { var itemRenderer:DisplayObject = null; var virtualLayout:IVirtualLayout = this._layout as IVirtualLayout; if(virtualLayout === null || !virtualLayout.useVirtualLayout) { if(this._layoutItems.length > 0) { itemRenderer = this._layoutItems[0] as DisplayObject; } } if(itemRenderer === null) { itemRenderer = this._typicalItemRenderer as DisplayObject; } if(itemRenderer === null) { return 0; } var itemRendererWidth:Number = itemRenderer.width; var itemRendererHeight:Number = itemRenderer.height; if(itemRendererWidth < itemRendererHeight) { return itemRendererWidth; } return itemRendererHeight; } public function get verticalScrollStep():Number { var itemRenderer:DisplayObject = null; var virtualLayout:IVirtualLayout = this._layout as IVirtualLayout; if(virtualLayout === null || !virtualLayout.useVirtualLayout) { if(this._layoutItems.length > 0) { itemRenderer = this._layoutItems[0] as DisplayObject; } } if(itemRenderer === null) { itemRenderer = this._typicalItemRenderer as DisplayObject; } if(itemRenderer === null) { return 0; } var itemRendererWidth:Number = itemRenderer.width; var itemRendererHeight:Number = itemRenderer.height; if(itemRendererWidth < itemRendererHeight) { return itemRendererWidth; } return itemRendererHeight; } private var _owner:Tree = null; public function get owner():Tree { return this._owner; } public function set owner(value:Tree):void { this._owner = value; } private var _updateForDataReset:Boolean = false; private var _dataProvider:IHierarchicalCollection = null; public function get dataProvider():IHierarchicalCollection { return this._dataProvider; } public function set dataProvider(value:IHierarchicalCollection):void { if(this._dataProvider == value) { return; } if(this._dataProvider) { this._dataProvider.removeEventListener(Event.CHANGE, dataProvider_changeHandler); /*this._dataProvider.removeEventListener(CollectionEventType.RESET, dataProvider_resetHandler); this._dataProvider.removeEventListener(CollectionEventType.ADD_ITEM, dataProvider_addItemHandler); this._dataProvider.removeEventListener(CollectionEventType.REMOVE_ITEM, dataProvider_removeItemHandler); this._dataProvider.removeEventListener(CollectionEventType.REPLACE_ITEM, dataProvider_replaceItemHandler); this._dataProvider.removeEventListener(CollectionEventType.UPDATE_ITEM, dataProvider_updateItemHandler); this._dataProvider.removeEventListener(CollectionEventType.UPDATE_ALL, dataProvider_updateAllHandler);*/ } this._dataProvider = value; if(this._dataProvider) { this._dataProvider.addEventListener(Event.CHANGE, dataProvider_changeHandler); /*this._dataProvider.addEventListener(CollectionEventType.RESET, dataProvider_resetHandler); this._dataProvider.addEventListener(CollectionEventType.ADD_ITEM, dataProvider_addItemHandler); this._dataProvider.addEventListener(CollectionEventType.REMOVE_ITEM, dataProvider_removeItemHandler); this._dataProvider.addEventListener(CollectionEventType.REPLACE_ITEM, dataProvider_replaceItemHandler); this._dataProvider.addEventListener(CollectionEventType.UPDATE_ITEM, dataProvider_updateItemHandler); this._dataProvider.addEventListener(CollectionEventType.UPDATE_ALL, dataProvider_updateAllHandler);*/ } if(this._layout is IVariableVirtualLayout) { IVariableVirtualLayout(this._layout).resetVariableVirtualCache(); } this._updateForDataReset = true; this.invalidate(INVALIDATION_FLAG_DATA); } private var _ignoreLayoutChanges:Boolean = false; private var _ignoreRendererResizing:Boolean = false; private var _layout:ILayout = null; public function get layout():ILayout { return this._layout; } public function set layout(value:ILayout):void { if(this._layout == value) { return; } if(this._layout) { this._layout.removeEventListener(Event.CHANGE, layout_changeHandler); } this._layout = value; if(this._layout) { if(this._layout is IVariableVirtualLayout) { var variableVirtualLayout:IVariableVirtualLayout = IVariableVirtualLayout(this._layout); variableVirtualLayout.resetVariableVirtualCache(); } this._layout.addEventListener(Event.CHANGE, layout_changeHandler); } this.invalidate(INVALIDATION_FLAG_LAYOUT); } private var _horizontalScrollPosition:Number = 0; public function get horizontalScrollPosition():Number { return this._horizontalScrollPosition; } public function set horizontalScrollPosition(value:Number):void { if(this._horizontalScrollPosition == value) { return; } this._horizontalScrollPosition = value; this.invalidate(INVALIDATION_FLAG_SCROLL); } private var _verticalScrollPosition:Number = 0; public function get verticalScrollPosition():Number { return this._verticalScrollPosition; } public function set verticalScrollPosition(value:Number):void { if(this._verticalScrollPosition == value) { return; } this._verticalScrollPosition = value; this.invalidate(INVALIDATION_FLAG_SCROLL); } public function get requiresMeasurementOnScroll():Boolean { return this._layout.requiresLayoutOnScroll && (this._explicitVisibleWidth !== this._explicitVisibleWidth || //isNaN this._explicitVisibleHeight !== this._explicitVisibleHeight); //isNaN } private var _ignoreSelectionChanges:Boolean = false; private var _isSelectable:Boolean = true; public function get isSelectable():Boolean { return this._isSelectable; } public function set isSelectable(value:Boolean):void { if(this._isSelectable == value) { return; } this._isSelectable = value; if(!this._isSelectable) { this.selectedItem = null; } this.invalidate(INVALIDATION_FLAG_SELECTED); } private var _selectedItem:Object = null; public function get selectedItem():Object { return this._selectedItem; } public function set selectedItem(value:Object):void { if(this._selectedItem == value) { return; } this._selectedItem = value; this.invalidate(INVALIDATION_FLAG_SELECTED); this.dispatchEventWith(Event.CHANGE); } private var _typicalItem:Object = null; public function get typicalItem():Object { return this._typicalItem; } public function set typicalItem(value:Object):void { if(this._typicalItem == value) { return; } this._typicalItem = value; this.invalidate(INVALIDATION_FLAG_DATA); } private var _itemRendererType:Class; public function get itemRendererType():Class { return this._itemRendererType; } public function set itemRendererType(value:Class):void { if(this._itemRendererType == value) { return; } this._itemRendererType = value; this.invalidate(INVALIDATION_FLAG_ITEM_RENDERER_FACTORY); } private var _itemRendererFactory:Function; public function get itemRendererFactory():Function { return this._itemRendererFactory; } public function set itemRendererFactory(value:Function):void { if(this._itemRendererFactory === value) { return; } this._itemRendererFactory = value; this.invalidate(INVALIDATION_FLAG_ITEM_RENDERER_FACTORY); } private var _itemRendererFactories:Object; public function get itemRendererFactories():Object { return this._itemRendererFactories; } public function set itemRendererFactories(value:Object):void { if(this._itemRendererFactories === value) { return; } this._itemRendererFactories = value; this.invalidate(INVALIDATION_FLAG_ITEM_RENDERER_FACTORY); } private var _factoryIDFunction:Function; public function get factoryIDFunction():Function { return this._factoryIDFunction; } public function set factoryIDFunction(value:Function):void { if(this._factoryIDFunction === value) { return; } this._factoryIDFunction = value; this.invalidate(INVALIDATION_FLAG_ITEM_RENDERER_FACTORY); } private var _customItemRendererStyleName:String; public function get customItemRendererStyleName():String { return this._customItemRendererStyleName; } public function set customItemRendererStyleName(value:String):void { if(this._customItemRendererStyleName == value) { return; } this._customItemRendererStyleName = value; this.invalidate(INVALIDATION_FLAG_ITEM_RENDERER_FACTORY); } private var _openBranches:IListCollection; public function get openBranches():IListCollection { return this._openBranches; } public function set openBranches(value:IListCollection):void { if(this._openBranches == value) { return; } if(this._openBranches !== null) { this._openBranches.removeEventListener(Event.CHANGE, openBranches_changeHandler); } this._openBranches = value; if(this._openBranches !== null) { this._openBranches.addEventListener(Event.CHANGE, openBranches_changeHandler); } this.invalidate(INVALIDATION_FLAG_DATA); } private var _typicalItemIsInDataProvider:Boolean = false; private var _typicalItemRenderer:ITreeItemRenderer; private var _layoutItems:Vector. = new []; private var _unrenderedItems:Array = []; private var _defaultItemRendererStorage:ItemRendererFactoryStorage = new ItemRendererFactoryStorage(); private var _itemStorageMap:Object = {}; private var _itemRendererMap:Dictionary = new Dictionary(true); private var _minimumItemCount:int; public function calculateNavigationDestination(location:Vector., keyCode:uint, result:Vector.):void { var displayIndex:int = this.locationToDisplayIndex(location, false); if(displayIndex == -1) { throw new ArgumentError(""Cannot calculate navigation destination for location: "" + location); } var newDisplayIndex:int = this._layout.calculateNavigationDestination(this._layoutItems, displayIndex, keyCode, this._layoutResult); this.displayIndexToLocation(newDisplayIndex, result); } public function getScrollPositionForLocation(location:Vector., result:Point = null):Point { if(!result) { result = new Point(); } var displayIndex:int = this.locationToDisplayIndex(location, true); if(displayIndex == -1) { throw new ArgumentError(""Cannot calculate scroll position for location: "" + location); } return this._layout.getScrollPositionForIndex(displayIndex, this._layoutItems, 0, 0, this._actualVisibleWidth, this._actualVisibleHeight, result); } public function getNearestScrollPositionForIndex(location:Vector., result:Point = null):Point { if(!result) { result = new Point(); } var displayIndex:int = this.locationToDisplayIndex(location, true); if(displayIndex == -1) { throw new ArgumentError(""Cannot calculate nearest scroll position for location: "" + location); } return this._layout.getNearestScrollPositionForIndex(displayIndex, this._horizontalScrollPosition, this._verticalScrollPosition, this._layoutItems, 0, 0, this._actualVisibleWidth, this._actualVisibleHeight, result); } public function itemToItemRenderer(item:Object):ITreeItemRenderer { if(item is XML || item is XMLList) { return ITreeItemRenderer(this._itemRendererMap[item.toXMLString()]); } return ITreeItemRenderer(this._itemRendererMap[item]); } override public function dispose():void { this.refreshInactiveItemRenderers(null, true); if(this._itemStorageMap) { for(var factoryID:String in this._itemStorageMap) { this.refreshInactiveItemRenderers(factoryID, true); } } this.owner = null; this.dataProvider = null; this.layout = null; super.dispose(); } override protected function draw():void { var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var scrollInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SCROLL); var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); var selectionInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SELECTED); var itemRendererInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_ITEM_RENDERER_FACTORY); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); var layoutInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_LAYOUT); //scrolling only affects the layout is requiresLayoutOnScroll is true if(!layoutInvalid && scrollInvalid && this._layout && this._layout.requiresLayoutOnScroll) { layoutInvalid = true; } var basicsInvalid:Boolean = sizeInvalid || dataInvalid || layoutInvalid || itemRendererInvalid; var oldIgnoreRendererResizing:Boolean = this._ignoreRendererResizing; this._ignoreRendererResizing = true; var oldIgnoreLayoutChanges:Boolean = this._ignoreLayoutChanges; this._ignoreLayoutChanges = true; if(scrollInvalid || sizeInvalid) { this.refreshViewPortBounds(); } if(basicsInvalid) { this.refreshInactiveItemRenderers(null, itemRendererInvalid); if(this._itemStorageMap) { for(var factoryID:String in this._itemStorageMap) { this.refreshInactiveItemRenderers(factoryID, itemRendererInvalid); } } } if(dataInvalid || layoutInvalid || itemRendererInvalid) { this.refreshLayoutTypicalItem(); } if(basicsInvalid) { this.refreshItemRenderers(); } if(selectionInvalid || basicsInvalid) { //unlike resizing renderers and layout changes, we only want to //stop listening for selection changes when we're forcibly //updating selection. other property changes on item renderers //can validly change selection, and we need to detect that. var oldIgnoreSelectionChanges:Boolean = this._ignoreSelectionChanges; this._ignoreSelectionChanges = true; this.refreshSelection(); this._ignoreSelectionChanges = oldIgnoreSelectionChanges; } if(stateInvalid || basicsInvalid) { this.refreshEnabled(); } this._ignoreLayoutChanges = oldIgnoreLayoutChanges; if(stateInvalid || selectionInvalid || stylesInvalid || basicsInvalid) { this._layout.layout(this._layoutItems, this._viewPortBounds, this._layoutResult); } this._ignoreRendererResizing = oldIgnoreRendererResizing; this._contentX = this._layoutResult.contentX; this._contentY = this._layoutResult.contentY; this.saveMeasurements(this._layoutResult.contentWidth, this._layoutResult.contentHeight, this._layoutResult.contentWidth, this._layoutResult.contentHeight); this._actualVisibleWidth = this._layoutResult.viewPortWidth; this._actualVisibleHeight = this._layoutResult.viewPortHeight; this._actualMinVisibleWidth = this._layoutResult.viewPortWidth; this._actualMinVisibleHeight = this._layoutResult.viewPortHeight; //final validation to avoid juggler next frame issues this.validateRenderers(); } private function displayIndexToLocation(displayIndex:int, result:Vector.):void { } private var _displayIndex:int; private function locationToDisplayIndex(location:Vector., returnNearestIfBranchNotOpen:Boolean):int { this._displayIndex = -1; var result:Object = this.locationToDisplayIndexAtBranch(new [], location, returnNearestIfBranchNotOpen); if(result !== null) { return this._displayIndex; } return -1; } private function locationToDisplayIndexAtBranch(locationOfBranch:Vector., locationToFind:Vector., returnNearestIfBranchNotOpen:Boolean):Object { var childCount:int = this._dataProvider.getLengthAtLocation(locationOfBranch); for(var i:int = 0; i < childCount; i++) { this._displayIndex++; locationOfBranch[locationOfBranch.length] = i; var child:Object = this._dataProvider.getItemAtLocation(locationOfBranch); if(locationOfBranch.length == locationToFind.length) { var every:Boolean = locationOfBranch.every(function(item:int, index:int, source:Vector.):Boolean { return item === locationToFind[index]; }); if(every) { return child; } } if(this._dataProvider.isBranch(child)) { if(this.owner.isBranchOpen(child)) { var result:Object = this.locationToDisplayIndexAtBranch(locationOfBranch, locationToFind, returnNearestIfBranchNotOpen); if(result) { return result; } } else if(returnNearestIfBranchNotOpen) { //if the location is inside a closed branch //return that branch every = locationOfBranch.every(function(item:int, index:int, source:Vector.):Boolean { return item === locationToFind[index]; }); if(every) { return child; } } } locationOfBranch.length--; } //location was not found! return null; } private function refreshViewPortBounds():void { var needsMinWidth:Boolean = this._explicitMinVisibleWidth !== this._explicitMinVisibleWidth; //isNaN var needsMinHeight:Boolean = this._explicitMinVisibleHeight !== this._explicitMinVisibleHeight; //isNaN this._viewPortBounds.x = 0; this._viewPortBounds.y = 0; this._viewPortBounds.scrollX = this._horizontalScrollPosition; this._viewPortBounds.scrollY = this._verticalScrollPosition; this._viewPortBounds.explicitWidth = this._explicitVisibleWidth; this._viewPortBounds.explicitHeight = this._explicitVisibleHeight; if(needsMinWidth) { this._viewPortBounds.minWidth = 0; } else { this._viewPortBounds.minWidth = this._explicitMinVisibleWidth; } if(needsMinHeight) { this._viewPortBounds.minHeight = 0; } else { this._viewPortBounds.minHeight = this._explicitMinVisibleHeight; } this._viewPortBounds.maxWidth = this._maxVisibleWidth; this._viewPortBounds.maxHeight = this._maxVisibleHeight; } private function refreshLayoutTypicalItem():void { var virtualLayout:IVirtualLayout = this._layout as IVirtualLayout; if(virtualLayout === null || !virtualLayout.useVirtualLayout) { //the old layout was virtual, but this one isn't if(!this._typicalItemIsInDataProvider && this._typicalItemRenderer !== null) { //it's safe to destroy this renderer this.destroyItemRenderer(this._typicalItemRenderer); this._typicalItemRenderer = null; } return; } var typicalItemLocation:Vector. = null; var newTypicalItemIsInDataProvider:Boolean = false; var typicalItem:Object = this._typicalItem; if(typicalItem !== null) { if(this._dataProvider !== null) { typicalItemLocation = this._dataProvider.getItemLocation(typicalItem); newTypicalItemIsInDataProvider = typicalItemLocation !== null && typicalItemLocation.length > 0; } } else { if(this._dataProvider !== null && this._dataProvider.getLengthAtLocation() > 0) { newTypicalItemIsInDataProvider = true; typicalItem = this._dataProvider.getItemAt(0); typicalItemLocation = new [0]; } } //#1645 The typicalItem can be null if the data provider contains //a null value at index 0. this is the only time we allow null. if(typicalItem !== null || newTypicalItemIsInDataProvider) { var typicalItemRenderer:ITreeItemRenderer = this.itemToItemRenderer(typicalItem); if(typicalItemRenderer !== null) { //at this point, the item already has an item renderer. //(this doesn't necessarily mean that the current typical //item was the typical item last time this function was //called) //the location may have changed if items were added, //removed or reordered in the data provider typicalItemRenderer.location = typicalItemLocation; } if(typicalItemRenderer === null && this._typicalItemRenderer !== null) { //the typical item has changed, and doesn't have an item //renderer yet. the previous typical item had an item //renderer, so we will try to reuse it. //we can reuse the existing typical item renderer if the old //typical item wasn't in the data provider. otherwise, it //may still be needed for the same item. var canReuse:Boolean = !this._typicalItemIsInDataProvider; var oldTypicalItemRemoved:Boolean = this._typicalItemIsInDataProvider && this._dataProvider !== null && this._dataProvider.getItemLocation(this._typicalItemRenderer.data) === null; if(!canReuse && oldTypicalItemRemoved) { //special case: if the old typical item was in the data //provider, but it has been removed, it's safe to reuse. canReuse = true; } if(canReuse) { //we can't reuse if the factoryID has changed, though! var factoryID:String = null; if(this._factoryIDFunction !== null) { factoryID = this.getFactoryID(typicalItem, typicalItemLocation); } if(this._typicalItemRenderer.factoryID !== factoryID) { canReuse = false; } } if(canReuse) { //we can reuse the item renderer used for the old //typical item! //if the old typical item was in the data provider, //remove it from the renderer map. if(this._typicalItemIsInDataProvider) { var oldData:Object = this._typicalItemRenderer.data; if(oldData is XML || oldData is XMLList) { delete this._itemRendererMap[oldData.toXMLString()]; } else { delete this._itemRendererMap[oldData]; } } typicalItemRenderer = this._typicalItemRenderer; typicalItemRenderer.data = typicalItem; typicalItemRenderer.location = typicalItemLocation; //if the new typical item is in the data provider, add it //to the renderer map. if(newTypicalItemIsInDataProvider) { if(typicalItem is XML || typicalItem is XMLList) { this._itemRendererMap[typicalItem.toXMLString()] = typicalItemRenderer; } else { this._itemRendererMap[typicalItem] = typicalItemRenderer; } } } } if(typicalItemRenderer === null) { //if we still don't have a typical item renderer, we need to //create a new one. typicalItemRenderer = this.createItemRenderer(typicalItem, typicalItemLocation, 0, false, !newTypicalItemIsInDataProvider); if(!this._typicalItemIsInDataProvider && this._typicalItemRenderer !== null) { //get rid of the old typical item renderer if it isn't //needed anymore. since it was not in the data //provider, we don't need to mess with the renderer map //dictionary or dispatch any events. this.destroyItemRenderer(this._typicalItemRenderer); this._typicalItemRenderer = null; } } } virtualLayout.typicalItem = DisplayObject(typicalItemRenderer); this._typicalItemRenderer = typicalItemRenderer; this._typicalItemIsInDataProvider = newTypicalItemIsInDataProvider; if(this._typicalItemRenderer !== null && !this._typicalItemIsInDataProvider) { //we need to know if this item renderer resizes to adjust the //layout because the layout may use this item renderer to resize //the other item renderers this._typicalItemRenderer.addEventListener(FeathersEventType.RESIZE, itemRenderer_resizeHandler); } } private function refreshItemRenderers():void { if(this._typicalItemRenderer !== null && this._typicalItemIsInDataProvider) { var storage:ItemRendererFactoryStorage = this.factoryIDToStorage(this._typicalItemRenderer.factoryID); var inactiveItemRenderers:Vector. = storage.inactiveItemRenderers; var activeItemRenderers:Vector. = storage.activeItemRenderers; //this renderer is already is use by the typical item, so we //don't want to allow it to be used by other items. var inactiveIndex:int = inactiveItemRenderers.indexOf(this._typicalItemRenderer); if(inactiveIndex >= 0) { inactiveItemRenderers[inactiveIndex] = null; } //if refreshLayoutTypicalItem() was called, it will have already //added the typical item renderer to the active renderers. if //not, we need to do it here. var activeRendererCount:int = activeItemRenderers.length; if(activeRendererCount == 0) { activeItemRenderers[activeRendererCount] = this._typicalItemRenderer; } } this.findUnrenderedData(); this.recoverInactiveItemRenderers(this._defaultItemRendererStorage); if(this._itemStorageMap) { for(var factoryID:String in this._itemStorageMap) { storage = ItemRendererFactoryStorage(this._itemStorageMap[factoryID]); this.recoverInactiveItemRenderers(storage); } } this.renderUnrenderedData(); this.freeInactiveItemRenderers(this._defaultItemRendererStorage, this._minimumItemCount); if(this._itemStorageMap) { for(factoryID in this._itemStorageMap) { storage = ItemRendererFactoryStorage(this._itemStorageMap[factoryID]); this.freeInactiveItemRenderers(storage, 1); } } this._updateForDataReset = false; } private function findTotalLayoutCount(location:Vector.):int { var itemCount:int = 0; if(this._dataProvider !== null) { itemCount = this._dataProvider.getLengthAtLocation(location); } var result:int = itemCount; for(var i:int = 0; i < itemCount; i++) { location[location.length] = i; var item:Object = this._dataProvider.getItemAtLocation(location); if(this._dataProvider.isBranch(item) && this._openBranches.contains(item)) { result += this.findTotalLayoutCount(location); } location.length--; } return result; } private function findUnrenderedDataForLocation(location:Vector., currentIndex:int):int { var virtualLayout:IVirtualLayout = this._layout as IVirtualLayout; var useVirtualLayout:Boolean = virtualLayout !== null && virtualLayout.useVirtualLayout; var itemCount:int = 0; if(this._dataProvider !== null) { itemCount = this._dataProvider.getLengthAtLocation(location); } for(var i:int = 0; i < itemCount; i++) { location[location.length] = i; var item:Object = this._dataProvider.getItemAtLocation(location); if(useVirtualLayout && HELPER_VECTOR.indexOf(currentIndex) == -1) { if(this._typicalItemRenderer !== null && this._typicalItemIsInDataProvider && this._typicalItemRenderer.data === item) { //the index may have changed if items were added, removed, //or reordered in the data provider this._typicalItemRenderer.layoutIndex = currentIndex; } this._layoutItems[currentIndex] = null; } else { this.findRendererForItem(item, location.slice(), currentIndex); } currentIndex++; if(this._dataProvider.isBranch(item) && this._openBranches.contains(item)) { currentIndex = this.findUnrenderedDataForLocation(location, currentIndex); } location.length--; } return currentIndex; } private function findUnrenderedData():void { LOCATION_HELPER_VECTOR.length = 0; var totalLayoutCount:int = this.findTotalLayoutCount(LOCATION_HELPER_VECTOR); LOCATION_HELPER_VECTOR.length = 0; this._layoutItems.length = totalLayoutCount; var virtualLayout:IVirtualLayout = this._layout as IVirtualLayout; var useVirtualLayout:Boolean = virtualLayout !== null && virtualLayout.useVirtualLayout; if(useVirtualLayout) { var point:Point = Pool.getPoint(); virtualLayout.measureViewPort(totalLayoutCount, this._viewPortBounds, point); var viewPortWidth:Number = point.x; var viewPortHeight:Number = point.y; Pool.putPoint(point); virtualLayout.getVisibleIndicesAtScrollPosition(this._horizontalScrollPosition, this._verticalScrollPosition, viewPortWidth, viewPortHeight, totalLayoutCount, HELPER_VECTOR); if(this._typicalItemRenderer !== null) { var minimumTypicalItemEdge:Number = this._typicalItemRenderer.height; if(this._typicalItemRenderer.width < minimumTypicalItemEdge) { minimumTypicalItemEdge = this._typicalItemRenderer.width; } var maximumViewPortEdge:Number = viewPortWidth; if(viewPortHeight > viewPortWidth) { maximumViewPortEdge = viewPortHeight; } this._minimumItemCount = Math.ceil(maximumViewPortEdge / minimumTypicalItemEdge) + 1; } else { this._minimumItemCount = 1; } } LOCATION_HELPER_VECTOR.length = 0; this.findUnrenderedDataForLocation(LOCATION_HELPER_VECTOR, 0); LOCATION_HELPER_VECTOR.length = 0; //update the typical item renderer's visibility if(this._typicalItemRenderer !== null) { if(useVirtualLayout && this._typicalItemIsInDataProvider) { var index:int = HELPER_VECTOR.indexOf(this._typicalItemRenderer.layoutIndex); if(index >= 0) { this._typicalItemRenderer.visible = true; } else { this._typicalItemRenderer.visible = false; //uncomment these lines to see a hidden typical item for //debugging purposes... /*this._typicalItemRenderer.visible = true; this._typicalItemRenderer.x = this._horizontalScrollPosition; this._typicalItemRenderer.y = this._verticalScrollPosition;*/ } } else { this._typicalItemRenderer.visible = this._typicalItemIsInDataProvider; } } HELPER_VECTOR.length = 0; } private function findRendererForItem(item:Object, location:Vector., layoutIndex:int):void { var itemRenderer:ITreeItemRenderer = this.itemToItemRenderer(item); if(this._factoryIDFunction !== null && itemRenderer !== null) { var newFactoryID:String = this.getFactoryID(itemRenderer.data, location); if(newFactoryID !== itemRenderer.factoryID) { itemRenderer = null; if(item is XML || item is XMLList) { delete this._itemRendererMap[item.toXMLString()]; } else { delete this._itemRendererMap[item]; } } } if(itemRenderer !== null) { //the indices may have changed if items were added, removed, //or reordered in the data provider itemRenderer.location = location; itemRenderer.layoutIndex = layoutIndex; itemRenderer.isOpen = this._dataProvider.isBranch(item) && this._openBranches.contains(item); if(this._updateForDataReset) { //similar to calling updateItemAt(), replacing the data //provider or resetting its source means that we should //trick the item renderer into thinking it has new data. //many developers seem to expect this behavior, so while //it's not the most optimal for performance, it saves on //support time in the forums. thankfully, it's still //somewhat optimized since the same item renderer will //receive the same data, and the children generally //won't have changed much, if at all. itemRenderer.data = null; itemRenderer.data = item; } //the typical item renderer is a special case, and we will //have already put it into the active renderers, so we don't //want to do it again! if(this._typicalItemRenderer !== itemRenderer) { var storage:ItemRendererFactoryStorage = this.factoryIDToStorage(itemRenderer.factoryID); var activeItemRenderers:Vector. = storage.activeItemRenderers; var inactiveItemRenderers:Vector. = storage.inactiveItemRenderers; activeItemRenderers[activeItemRenderers.length] = itemRenderer; var inactiveIndex:int = inactiveItemRenderers.indexOf(itemRenderer); if(inactiveIndex >= 0) { inactiveItemRenderers.removeAt(inactiveIndex); } else { throw new IllegalOperationError(""TreeDataViewPort: item renderer map contains bad data. This may be caused by duplicate items in the data provider, which is not allowed.""); } } itemRenderer.visible = true; this._layoutItems[layoutIndex] = DisplayObject(itemRenderer); } else { var pushIndex:int = this._unrenderedItems.length; this._unrenderedItems[pushIndex] = location; pushIndex++; this._unrenderedItems[pushIndex] = layoutIndex; } } private function renderUnrenderedData():void { LOCATION_HELPER_VECTOR.length = 2; var rendererCount:int = this._unrenderedItems.length; for(var i:int = 0; i < rendererCount; i += 2) { var location:Vector. = this._unrenderedItems.shift(); var layoutIndex:int = this._unrenderedItems.shift(); var item:Object = this._dataProvider.getItemAtLocation(location); var itemRenderer:ITreeItemRenderer = this.createItemRenderer( item, location, layoutIndex, true, false); itemRenderer.visible = true; this._layoutItems[layoutIndex] = DisplayObject(itemRenderer); } LOCATION_HELPER_VECTOR.length = 0; } private function refreshInactiveItemRenderers(factoryID:String, itemRendererTypeIsInvalid:Boolean):void { if(factoryID !== null) { var storage:ItemRendererFactoryStorage = ItemRendererFactoryStorage(this._itemStorageMap[factoryID]); } else { storage = this._defaultItemRendererStorage; } var temp:Vector. = storage.inactiveItemRenderers; storage.inactiveItemRenderers = storage.activeItemRenderers; storage.activeItemRenderers = temp; if(storage.activeItemRenderers.length > 0) { throw new IllegalOperationError(""TreeDataViewPort: active renderers should be empty.""); } if(itemRendererTypeIsInvalid) { this.recoverInactiveItemRenderers(storage); this.freeInactiveItemRenderers(storage, 0); if(this._typicalItemRenderer && this._typicalItemRenderer.factoryID === factoryID) { if(this._typicalItemIsInDataProvider) { var item:Object = this._typicalItemRenderer.data; if(item is XML || item is XMLList) { delete this._itemRendererMap[item.toXMLString()]; } else { delete this._itemRendererMap[item]; } } this.destroyItemRenderer(this._typicalItemRenderer); this._typicalItemRenderer = null; this._typicalItemIsInDataProvider = false; } } this._layoutItems.length = 0; } private function recoverInactiveItemRenderers(storage:ItemRendererFactoryStorage):void { var inactiveItemRenderers:Vector. = storage.inactiveItemRenderers; var itemCount:int = inactiveItemRenderers.length; for(var i:int = 0; i < itemCount; i++) { var itemRenderer:ITreeItemRenderer = inactiveItemRenderers[i]; if(itemRenderer === null || itemRenderer.data === null) { continue; } this._owner.dispatchEventWith(FeathersEventType.RENDERER_REMOVE, false, itemRenderer); var item:Object = itemRenderer.data; if(item is XML || item is XMLList) { delete this._itemRendererMap[item.toXMLString()]; } else { delete this._itemRendererMap[item]; } } } private function freeInactiveItemRenderers(storage:ItemRendererFactoryStorage, minimumItemCount:int):void { var inactiveItemRenderers:Vector. = storage.inactiveItemRenderers; var activeItemRenderers:Vector. = storage.activeItemRenderers; var activeItemRenderersCount:int = activeItemRenderers.length; //we may keep around some extra renderers to avoid too much //allocation and garbage collection. they'll be hidden. var itemCount:int = inactiveItemRenderers.length; var keepCount:int = minimumItemCount - activeItemRenderersCount; if(keepCount > itemCount) { keepCount = itemCount; } for(var i:int = 0; i < keepCount; i++) { var itemRenderer:ITreeItemRenderer = inactiveItemRenderers.shift(); if(!itemRenderer) { keepCount++; if(itemCount < keepCount) { keepCount = itemCount; } continue; } itemRenderer.data = null; itemRenderer.location = null; itemRenderer.visible = false; activeItemRenderers[activeItemRenderersCount] = itemRenderer; activeItemRenderersCount++; } itemCount -= keepCount; for(i = 0; i < itemCount; i++) { itemRenderer = inactiveItemRenderers.shift(); if(!itemRenderer) { continue; } this.destroyItemRenderer(itemRenderer); } } private function createItemRenderer(item:Object, location:Vector., layoutIndex:int, useCache:Boolean, isTemporary:Boolean):ITreeItemRenderer { var factoryID:String = null; if(this._factoryIDFunction !== null) { factoryID = this.getFactoryID(item, location); } var itemRendererFactory:Function = this.factoryIDToFactory(factoryID); var storage:ItemRendererFactoryStorage = this.factoryIDToStorage(factoryID); var inactiveItemRenderers:Vector. = storage.inactiveItemRenderers; var activeItemRenderers:Vector. = storage.activeItemRenderers; var itemRenderer:ITreeItemRenderer; do { if(!useCache || isTemporary || inactiveItemRenderers.length == 0) { if(itemRendererFactory !== null) { itemRenderer = ITreeItemRenderer(itemRendererFactory()); } else { itemRenderer = ITreeItemRenderer(new this._itemRendererType()); } if(this._customItemRendererStyleName && this._customItemRendererStyleName.length > 0) { itemRenderer.styleNameList.add(this._customItemRendererStyleName); } this.addChild(DisplayObject(itemRenderer)); } else { itemRenderer = inactiveItemRenderers.shift(); } //wondering why this all is in a loop? //_inactiveRenderers.shift() may return null because we're //storing null values instead of calling splice() to improve //performance. } while(!itemRenderer) itemRenderer.data = item; itemRenderer.owner = this._owner; itemRenderer.factoryID = factoryID; itemRenderer.location = location; itemRenderer.layoutIndex = layoutIndex; var isBranch:Boolean = this._dataProvider !== null && this._dataProvider.isBranch(item); itemRenderer.isBranch = isBranch; itemRenderer.isOpen = isBranch && this._openBranches.contains(item); if(!isTemporary) { if(item is XML || item is XMLList) { this._itemRendererMap[item.toXMLString()] = itemRenderer; } else { this._itemRendererMap[item] = itemRenderer; } activeItemRenderers[activeItemRenderers.length] = itemRenderer; itemRenderer.addEventListener(Event.TRIGGERED, itemRenderer_triggeredHandler); itemRenderer.addEventListener(Event.CHANGE, itemRenderer_changeHandler); itemRenderer.addEventListener(FeathersEventType.RESIZE, itemRenderer_resizeHandler); this._owner.dispatchEventWith(FeathersEventType.RENDERER_ADD, false, itemRenderer); } return itemRenderer; } private function destroyItemRenderer(itemRenderer:ITreeItemRenderer):void { itemRenderer.removeEventListener(Event.TRIGGERED, itemRenderer_triggeredHandler); itemRenderer.removeEventListener(Event.CHANGE, itemRenderer_changeHandler); itemRenderer.removeEventListener(FeathersEventType.RESIZE, itemRenderer_resizeHandler); itemRenderer.owner = null; itemRenderer.data = null; itemRenderer.location = null; itemRenderer.layoutIndex = -1; itemRenderer.factoryID = null; this.removeChild(DisplayObject(itemRenderer), true); } private function getFactoryID(item:Object, location:Vector.):String { if(this._factoryIDFunction === null) { return null; } if(this._factoryIDFunction.length == 2) { return this._factoryIDFunction(item, location); } return this._factoryIDFunction(item); } private function factoryIDToFactory(id:String):Function { if(id !== null) { if(id in this._itemRendererFactories) { return this._itemRendererFactories[id] as Function; } else { throw new ReferenceError(""Cannot find item renderer factory for ID \\"""" + id + ""\\""."") } } return this._itemRendererFactory; } private function factoryIDToStorage(id:String):ItemRendererFactoryStorage { if(id !== null) { if(id in this._itemStorageMap) { return ItemRendererFactoryStorage(this._itemStorageMap[id]); } var storage:ItemRendererFactoryStorage = new ItemRendererFactoryStorage(); this._itemStorageMap[id] = storage; return storage; } return this._defaultItemRendererStorage; } private function invalidateParent(flag:String = INVALIDATION_FLAG_ALL):void { Scroller(this.parent).invalidate(flag); } private function refreshSelection():void { for each(var item:DisplayObject in this._layoutItems) { var itemRenderer:ITreeItemRenderer = item as ITreeItemRenderer; if(itemRenderer !== null) { itemRenderer.isSelected = itemRenderer.data === this._selectedItem; } } } private function refreshEnabled():void { for each(var item:DisplayObject in this._layoutItems) { var control:IFeathersControl = item as IFeathersControl; if(control !== null) { control.isEnabled = this._isEnabled; } } } private function validateRenderers():void { var itemCount:int = this._layoutItems.length; for(var i:int = 0; i < itemCount; i++) { var item:IValidating = this._layoutItems[i] as IValidating; if(item !== null) { item.validate(); } } } private function layout_changeHandler(event:Event):void { if(this._ignoreLayoutChanges) { return; } this.invalidate(INVALIDATION_FLAG_LAYOUT); this.invalidateParent(INVALIDATION_FLAG_LAYOUT); } private function dataProvider_changeHandler(event:Event):void { this.invalidate(INVALIDATION_FLAG_DATA); } private function itemRenderer_triggeredHandler(event:Event):void { var itemRenderer:ITreeItemRenderer = ITreeItemRenderer(event.currentTarget); this.parent.dispatchEventWith(Event.TRIGGERED, false, itemRenderer.data); } private function itemRenderer_changeHandler(event:Event):void { if(this._ignoreSelectionChanges) { return; } var itemRenderer:ITreeItemRenderer = ITreeItemRenderer(event.currentTarget); if(!this._isSelectable || this._owner.isScrolling) { itemRenderer.isSelected = false; return; } var isSelected:Boolean = itemRenderer.isSelected; if(isSelected) { this.selectedItem = itemRenderer.data; } else { this.selectedItem = null; } } private function itemRenderer_resizeHandler(event:Event):void { if(this._ignoreRendererResizing) { return; } this.invalidate(INVALIDATION_FLAG_LAYOUT); this.invalidateParent(INVALIDATION_FLAG_LAYOUT); if(event.currentTarget === this._typicalItemRenderer && !this._typicalItemIsInDataProvider) { return; } var layout:IVariableVirtualLayout = this._layout as IVariableVirtualLayout; if(!layout || !layout.hasVariableItemDimensions) { return; } var itemRenderer:ITreeItemRenderer = ITreeItemRenderer(event.currentTarget); layout.resetVariableVirtualCacheAtIndex(itemRenderer.layoutIndex, DisplayObject(itemRenderer)); } private function openBranches_changeHandler(event:Event):void { this.invalidate(INVALIDATION_FLAG_DATA); } } } import feathers.controls.renderers.ITreeItemRenderer; class ItemRendererFactoryStorage { public function ItemRendererFactoryStorage() { } public var activeItemRenderers:Vector. = new []; public var inactiveItemRenderers:Vector. = new []; }",12495,False,2450.4773280955455,median "== WAN [blue]*Hazelcast IMDG Enterprise Feature* === WAN Replication There could be cases where you need to synchronize multiple Hazelcast clusters to the same state. Hazelcast WAN Replication allows you to keep multiple Hazelcast clusters in sync by replicating their state over WAN environments such as the Internet. Imagine you have different data centers in New York, London and Tokyo each running an independent Hazelcast cluster. Every cluster would be operating at native speed in their own LAN (Local Area Network), but you also want some or all record sets in these clusters to be replicated to each other: updates in the Tokyo cluster should also replicate to London and New York and updates in the New York cluster are to be synchronized to the Tokyo and London clusters. This section explains how you can replicate the state of your clusters over Wide Area Network (WAN) through Hazelcast WAN Replication. NOTE: You can download the white paper **Hazelcast on AWS: Best Practices for Deployment** at link:https://hazelcast.com/resources/amazon-ec2-deployment-guide/[Hazelcast.com^]. NOTE: To be able to use the REST calls related to WAN Replication mentioned in the following sections, you need to enable the `WAN` REST endpoint group. See the <> for details. ==== Defining WAN Replication Hazelcast supports two different operation modes of WAN Replication: * **Active-Passive:** This mode is mostly used for failover scenarios where you want to replicate an active cluster to one or more passive clusters, for the purpose of maintaining a backup. * **Active-Active:** Every cluster is equal, each cluster replicates to all other clusters. This is normally used to connect different clients to different clusters for the sake of the shortest path between client and server. There are two different ways of defining the WAN replication endpoints: * Static endpoints * Discovery SPI You can use at most one of these when defining a single WAN publisher. ===== Defining WAN Replication Using Static Endpoints Below is an example of declarative configuration of WAN Replication from New York cluster to target the London cluster: [source,xml,options=""nowrap""] ---- ... london THROW_EXCEPTION 1000 500 1000 false 60000 ACK_ON_OPERATION_COMPLETE 10.3.5.1:5701, 10.3.5.2:5701 20 com.hazelcast.enterprise.wan.replication.YourWanConsumer false 192.168.2.66 YOUR_VPN_NAME admin YOUR_PASSWORD Q/hz/clusterA ... ---- The `wan-replication` configuration element has the following sub-elements and attributes: * `name`: Name of your WAN replication scheme. This name is referenced in IMap or ICache configuration when you add WAN Replication for these data structures (using the element `wan-replication-ref` in the configuration of IMap or ICache). * `batch-publisher`: WAN publisher which uses the built-in WAN replication implementation in the Hazelcast Enterprise Edition. It waits until a batch size is reached or a delay time is passed. * `custom-publisher`: Custom implementation of a WAN publisher implementing `WanReplicationPublisher`. * `consumer`: Configuration for processing the WAN events received from a target cluster. You can configure a certain behavior when processing the incoming WAN events or even configure your own implementation for a WAN consumer. A custom WAN consumer allows you to define custom processing logic and is usually used in combination with a custom WAN publisher. A custom consumer is optional and you may simply omit defining it which causes the default processing logic to be used. A single WAN replication scheme can contain multiple `batch-publisher` and `custom-publisher` WAN replication publishers. The `batch-publisher` element is used to configure the built-in WAN replication implementation in the Hazelcast Enterprise Edition. It defines how to connect to the target cluster and how WAN events are sent to a specific target endpoint. As mentioned above, just before the configuration example, the target endpoints can be a different cluster defined by static IPs or discovered using a cloud discovery mechanism. The `batch-publisher` configuration element has the following sub-elements: * `cluster-name`: Sets the cluster name used as an endpoint cluster name for authentication on the target endpoint. If there is no separate publisher ID element defined, this cluster name is also used as a WAN publisher ID. This ID is then used for identifying the publisher in a WAN replication scheme. It is mandatory to set this attribute. * `publisher-id`: Sets the publisher ID used to identify the publisher in a WAN replication scheme. Setting this ID may be useful when the `wan-replication` element contains multiple WAN publishers and the cluster names are not unique for all of the WAN replication publishers in a single WAN replication scheme. It is optional to set this attribute. If this ID is not specified, the `cluster-name` is used as a publisher ID. * `batch-size`: Changes the maximum size of events that are sent to the target cluster in a single batch. The batch of events is not sent until this size is reached or enough time has elapsed. Its default value is 500. See the <>. * `batch-max-delay-millis`: If the number of events generated does not reach the `batch-size`, they are sent to the target cluster after a certain amount of time is passed. You can set this time in milliseconds using this element. Its default value is 1000 milliseconds. See the <>. * `response-timeout-millis`: After a replication event batch is sent to the target cluster, the source member waits for a confirmation that says the event has reached the target. If confirmation is not received for a period of `response-timeout-millis`, the event is resent to the target cluster. The default value is 60000 milliseconds. See the <>. * `acknowledge-type`: Acknowledgment type for each target cluster when the events are replicated. See the <>. * `snapshot-enabled`: Sets if key-based coalescing is configured for this WAN publisher. When enabled, only the latest event for a key is sent to target. Its default value is `false`. * `idle-max-park-ns`: Sets the maximum duration in nanoseconds that the WAN replication thread is parked if there are no events to replicate. * `idle-min-park-ns`: Sets the minimum duration in nanoseconds that the WAN replication thread is parked if there are no events to replicate. * `max-concurrent-invocations`: Sets the maximum number of WAN event batches being sent to the target cluster concurrently. Setting this element to anything less than 2 only allows a single batch of events to be sent to each target endpoint and will maintain causality of events for a single partition. + Setting this element to 2 or higher allows multiple batches of WAN events to be sent to each target endpoint. Since this allows reordering or batches due to network conditions, causality and ordering of events for a single partition is lost and batches for a single partition are now sent randomly to any available target endpoint. + This, however, does present faster WAN replication for certain scenarios such as replicating immutable, independent map entries which are only added once and where ordering of when these entries are added is not necessary. + Keep in mind that if you set this element to a value which is less than the target endpoint count, you will lose performance as not all target endpoints are used at any point in time to process the WAN event batches. So, for instance, if you have a target cluster with 3 members (target endpoints) and you want to use this element, it makes sense to set it to a value higher than 3. Otherwise, you can simply disable it by setting it to less than 2 in which case WAN will use the default replication strategy and adapt to the target endpoint count while maintaining causality. * `queue-full-behavior`: Policy to be applied when the WAN Replication event queues are full. See the <>. * `queue-capacity`: Size of the queue of events. Its default value is 10000. If you exceed this queue size, then the oldest, not yet replicated updates might get lost. Therefore, if you have a large rate of put/update/remove operations, you should increase the queue capacity. See the <>. * `target-endpoints`: IP addresses and ports of the cluster members for which the WAN replication is implemented. It is enough to specify some of the member IP/ports available in the target cluster, i.e., you don’t need to provide the IP/ports of all members in there. WAN does not perform the discovery of other members in the target cluster; it only expects that the IP addresses you provide are available. * `wan-sync`: Configuration for the WAN sync mechanism. * `aws`: Configuration for discovery strategy for Amazon EC2 discovery plugin. * `gcp`: Configuration for discovery strategy for Google cloud platform discovery plugin. * `azure`: Configuration for discovery strategy for Microsoft Azure discovery plugin. * `kubernetes`: Configuration for discovery strategy for Kubernetes discovery plugin. * `eureka`: Configuration for discovery strategy for Eureka discovery plugin. * `discovery-strategies`: Set its `enabled` attribute to true for discovery in various cloud infrastructures. You can define multiple discovery strategies using the `discovery-strategy` sub-element and its elements. The `custom-publisher` is used to configure a custom implementation of a WAN replication implementing `WanReplicationPublisher`. For example, you might implement replication to Kafka or some JMS queue or even write out map and cache event changes to a log on disk. It has the following sub-elements: * `class-name`: Mandatory configuration value defining the fully qualified class name of the WAN publisher implementation. * `publisher-id`: Mandatory configuration value for the publisher ID used for identifying the publisher in a `WanReplicationConfig`. The `consumer` is used to configure the processing of the WAN events received from a source cluster. You can configure a certain behavior when processing the incoming WAN events or even configure your own implementation for a WAN consumer. A custom WAN consumer allows you to define a custom processing logic and is usually used in combination with a custom WAN publisher. A custom consumer is optional and you may simply omit defining it which causes the default processing logic to be used. It has the following sub-elements: * `class-name`: Name of the class implementing a custom WAN consumer (`WanReplicationConsumer`). If you don't define a class name, the default processing logic for incoming WAN events is used. * `properties`: Properties for the custom WAN consumer. These properties are accessible when initializing the WAN consumer. You can define the host, username and password for the host, name of the queue to be polled by the consumer, etc. * `persist-wan-replicated-data`: When set to `true`, an incoming event over WAN replication can be persisted to a database for example, otherwise it is not persisted. Default value is `true`. And the following is the equivalent programmatic configuration snippet: [source,java] ---- include::{javasource}/wan/ExampleWANReplicationConfiguration.java[tag=wrc] ---- Using this configuration, the cluster replicates to a cluster with the name ""london"". The ""london"" cluster should have a similar configuration if you want to run in Active-Active mode. You can achieve various WAN topologies using different configurations on different clusters. For instance, if the New York and London cluster configurations contain the `wan-replication` element and the Tokyo cluster does not, it might mean that the New York and London clusters are active endpoints and Tokyo is a passive endpoint. ===== Defining WAN Replication Using Discovery SPI In addition to defining target cluster endpoints with static IP addresses, you can configure WAN to work with the discovery SPI and determine the endpoint IP addresses at runtime. This allows you to use WAN with endpoints on various cloud infrastructures (such as Amazon EC2 or GCP Compute) where the IP address is not known in advance. Typically you use a readily available discovery SPI plugin such as link:https://github.com/hazelcast/hazelcast-aws[Hazelcast AWS EC2 discovery plugin^], link:https://github.com/hazelcast/hazelcast-gcp[Hazelcast GCP discovery plugin^], or similar. For more advanced cases, you can provide your own discovery SPI implementation with custom logic for determining the WAN target endpoints such as looking up the endpoints in some service registry or even reading the endpoint addresses from a file. NOTE: When using the discovery SPI, WAN always connects to the public address of the members returned by the discovery SPI implementation. This is opposite to the cluster membership mechanism using the discovery SPI where a member connects to a different member in the same cluster through its private address. Should you prefer for WAN to use the private address of the discovered member as well, please use the `use-endpoint-private-address` publisher element (see below). Following is an example of setting up the WAN replication with the EC2 discovery plugin. You must have the link:https://github.com/hazelcast/hazelcast-aws[Hazelcast AWS EC2 discovery plugin^] on the classpath. [source,xml] ---- ... london THROW_EXCEPTION 1000 500 1000 false 60000 ACK_ON_OPERATION_COMPLETE 20 5 test-access-key test-secret-key test-region test-iam-role ec2.test-host-header test-security-group-name test-tag-key test-tag-value 10 5701 ... ---- The `hz-port` property defines the port or the port range on which the target endpoint is running. The default port range 5701-5708 is used if this property is not defined. This is needed because the Amazon API which the AWS plugin uses does not provide the port on which Hazelcast is running, only the IP address. For some other discovery SPI implementations, this might not be necessary and it might discover the port as well, e.g., by looking up in a service registry. The other properties are the same as when using the `aws` element. In case of EC2 discovery you can configure the WAN replication using the `aws` element. You may use either of these, but not both at the same time. [source,xml] ---- ... london THROW_EXCEPTION 1000 500 1000 false 60000 ACK_ON_OPERATION_COMPLETE 20 false 5 my-access-key my-secret-key us-west-1 hazelcast-sg type hz-members 5701 ... ---- See the <> and the <> sections for the descriptions of above AWS configuration elements. The following are the definitions of additional configuration elements: * `discovery-period-seconds`: Sets the period in seconds in which WAN tries to discover new target endpoints and reestablish connections to failed endpoints. * `max-target-endpoints`: Returns the maximum number of endpoints that WAN connects to when a discovery mechanism is used to define the endpoints. This element has no effect when static endpoint addresses are defined using `target-endpoints`. Default is `Integer.MAX_VALUE`. * `use-endpoint-private-address`: Sets whether the WAN connection manager should connect to the endpoint on the private address returned by the discovery SPI. By default this element is `false` which means the WAN connection manager always uses the public address. You can also define the WAN publisher with discovery SPI using the programmatic configuration: [source,java] ---- include::{javasource}/wan/ExampleWANReplicationDiscoveryConfiguration.java[tag=wrdc] ---- [[wanbatchreplication-implementation]] ==== WAN Batch Publisher Implementation Hazelcast IMDG Enterprise Edition offers the WAN batch publisher implementation for WAN replication. As you see in the above configuration examples, this implementation is specified simply by using the `batch-publisher` element (in the declarative configuration) or the `WanBatchReplicationPublisherConfig` class (in the programmatic configuration) when defining a WAN replication publisher. The WAN batch publisher implementation waits until: * a pre-defined number of replication events are generated, (see the <>) * or a pre-defined amount of time is passed (see the <>). NOTE: `WanNoDelayReplication` implementation has been removed. You can still achieve this behavior by setting the batch size to `1` while configuring your WAN replication. ==== Configuring WAN Replication for IMap and ICache You can configure WAN replication for Hazelcast's IMap and ICache data structures. To enable WAN replication for an IMap or ICache instance, you can use the `wan-replication-ref` element. Each IMap and ICache instance can have a different WAN replication configuration. **Enabling WAN Replication for IMap:** Imagine you have different distributed maps, however only one of those maps should be replicated to a target cluster. To achieve this, configure the map that you want to be replicated by adding the `wan-replication-ref` element in the map configuration as shown below. [source,xml] ---- ... ... com.hazelcast.spi.merge.PassThroughMergePolicy false ... ---- The following is the equivalent programmatic configuration: [source,java] ---- include::{javasource}/wan/EnablingWRforMap.java[tag=wrmap] ---- You see that we have `my-shared-map` configured to replicate itself to the cluster targets defined in the earlier `wan-replication` element. `wan-replication-ref` has the following elements; * `name`: Name of `wan-replication` configuration. IMap or ICache instance uses this `wan-replication` configuration. * `merge-policy`: Resolve conflicts that occur when the target cluster already has the replicated entry key. * `republishing-enabled`: When enabled, an incoming event to a member is forwarded to target cluster of that member. Enabling the event republishing is useful in a scenario where cluster A replicates to cluster B and cluster B replicates to cluster C. You do not need to enable republishing when all your clusters replicate to each other. When using Active-Active Replication, multiple clusters can simultaneously update the same entry in a distributed data structure. You can configure a merge policy to resolve these potential conflicts, as shown in the above example configuration (using the `merge-policy` sub-element under the `wan-replication-ref` element). Hazelcast provides the following merge policies for IMap: * `com.hazelcast.spi.merge.PutIfAbsentMergePolicy`: Incoming entry merges from the source map to the target map if it does not exist in the target map. * `com.hazelcast.spi.merge.HigherHitsMergePolicy`: Incoming entry merges from the source map to the target map if the source entry has more hits than the target one. * `com.hazelcast.spi.merge.PassThroughMergePolicy`: Incoming entry merges from the source map to the target map unless the incoming entry is not null. * `com.hazelcast.spi.merge.ExpirationTimeMergePolicy`: Incoming entry merges from the source map to the target map if the source entry will expire later than the destination entry. Please note that this merge policy can only be used when the clusters' clocks are in sync. * `com.hazelcast.spi.merge.LatestAccessMergePolicy`: Incoming entry merges from the source map to the target map if the source entry has been accessed more recently than the destination entry. Please note that this merge policy can only be used when the clusters' clocks are in sync. * `com.hazelcast.spi.merge.LatestUpdateMergePolicy`: Incoming entry merges from the source map to the target map if the source entry has been updated more recently than the target entry. Please note that this merge policy can only be used when the clusters' clocks are in sync. NOTE: When using WAN replication, please note that only key based events are replicated to the target cluster. Operations like `clear`, `destroy`, `evict` and `evictAll` are NOT replicated. **Enabling WAN Replication for ICache:** The following is a declarative configuration example for enabling WAN Replication for ICache: [source,xml] ---- ... ... com.hazelcast.spi.merge.PassThroughMergePolicy true ... ---- The following is the equivalent programmatic configuration: [source,java] ---- include::{javasource}/wan/EnablingWRforCache.java[tag=wrcache] ---- NOTE: Caches that are created dynamically do not support WAN replication functionality. Cache configurations should be defined either declaratively (by XML) or programmatically on both source and target clusters. Hazelcast provides the following merge policies for ICache: * `com.hazelcast.spi.merge.PutIfAbsentMergePolicy`: Incoming entry merges from the source cache to the target cache if it does not exist in the target cache. * `com.hazelcast.spi.merge.HigherHitsMergePolicy`: Incoming entry merges from the source cache to the target cache if the source entry has more hits than the target one. * `com.hazelcast.spi.merge.PassThroughMergePolicy`: Incoming entry merges from the source cache to the target cache unless the incoming entry is not null. * `com.hazelcast.spi.merge.ExpirationTimeMergePolicy`: Incoming entry merges from the source cache to the target cache if the source entry will expire later than the destination entry. Please note that this merge policy can only be used when the clusters' clocks are in sync. * `com.hazelcast.spi.merge.LatestAccessMergePolicy`: Incoming entry merges from the source cache to the target cache if the source entry has been accessed more recently than the destination entry. Please note that this merge policy can only be used when the clusters' clocks are in sync. * `com.hazelcast.spi.merge.LatestUpdateMergePolicy`: Incoming entry merges from the source cache to the target cache if the source entry has been updated more recently than the target entry. Please note that this merge policy can only be used when the clusters' clocks are in sync. ==== Batch Size The maximum size of events that are sent in a single batch can be changed depending on your needs. Default value for batch size is `500`. Batch size can be set for each target cluster by modifying related `WanBatchReplicationPublisherConfig`. Below is the declarative configuration for changing the value of the element: [source,xml] ---- ... london 1000 ... ---- And, following is the equivalent programmatic configuration: [source,java] ---- WanReplicationConfig wanConfig = config.getWanReplicationConfig(""my-wan-cluster""); WanBatchReplicationPublisherConfig publisherConfig = new WanBatchReplicationPublisherConfig() .setClusterName(""london"") .setBatchSize(1000); wanConfig.addWanPublisherConfig(publisherConfig); ---- NOTE: `WanNoDelayReplication` implementation has been removed. You can still achieve this behavior by setting the batch size to `1` while configuring your WAN replication. ==== Batch Maximum Delay When using the built-in WAN batch replication, if the number of WAN replication events generated does not reach <>, they are sent to the target cluster after a certain amount of time is passed. You can set this duration in milliseconds using this batch maximum delay configuration. Default value of for this duration is 1 second (1000 milliseconds). Maximum delay can be set for each target cluster by modifying related `WanBatchReplicationPublisherConfig`. You can change this element using the declarative configuration as shown below. [source,xml] ---- ... london 2000 ... ---- And, the following is the equivalent programmatic configuration: [source,java] ---- WanReplicationConfig wanConfig = config.getWanReplicationConfig(""my-wan-cluster""); WanBatchReplicationPublisherConfig publisherConfig = new WanBatchReplicationPublisherConfig() .setClusterName(""london"") .setBatchMaxDelayMillis(2000); wanConfig.addWanPublisherConfig(publisherConfig); ---- ==== Response Timeout After a replication event is sent to the target cluster, the source member waits for an acknowledgement of the delivery of the event to the target. If the confirmation is not received inside a timeout duration window, the event is resent to the target cluster. Default value of this duration is `60000` milliseconds. You can change this duration depending on your network latency for each target cluster by modifying related `WanBatchReplicationPublisherConfig`. Below is an example of declarative configuration: [source,xml] ---- ... london 5000 ... ---- And, the following is the equivalent programmatic configuration: [source,java] ---- WanReplicationConfig wanConfig = config.getWanReplicationConfig(""my-wan-cluster""); WanBatchReplicationPublisherConfig publisherConfig = new WanBatchReplicationPublisherConfig() .setClusterName(""london"") .setResponseTimeoutMillis(5000); wanConfig.addWanPublisherConfig(publisherConfig); ---- ==== Queue Capacity For huge clusters or high data mutation rates, you might need to increase the replication queue size. The default queue size for replication queues is `10000`. This means, if you have heavy put/update/remove rates, you might exceed the queue size so that the oldest, not yet replicated, updates might get lost. Note that a separate queue is used for each WAN Replication configured for IMap and ICache. Queue capacity can be set for each target cluster by modifying related `WanBatchReplicationPublisherConfig`. You can change this element using the declarative configuration as shown below. [source,xml] ---- ... london 15000 ... ---- And, the following is the equivalent programmatic configuration: [source,java] ---- WanReplicationConfig wanConfig = config.getWanReplicationConfig(""my-wan-cluster""); WanBatchReplicationPublisherConfig publisherConfig = new WanBatchReplicationPublisherConfig() .setClusterName(""london"") .setQueueCapacity(15000); wanConfig.addWanPublisherConfig(publisherConfig); ---- Note that you can clear a member's WAN replication event queue. It can be initiated through Management Center's link:https://docs.hazelcast.org/docs/management-center/latest/manual/html/index.html#monitoring-wan-replication[Clear Queues action^] or Hazelcast’s REST API. Below is the URL for its REST call: ``` http://member_ip:port/hazelcast/rest/mancenter/wan/clearWanQueues ``` This may be useful, for instance, to release the consumed heap if you know that the target cluster is being shut down, decommissioned, put out of use and it will never come back. Or, when a failure happens and queues are not replicated anymore, you could clear the queues using this clearing action. ==== Queue Full Behavior In the previous Hazelcast releases, WAN replication was dropping the new events if WAN replication event queues are full. This behavior is configurable. The following behaviors are supported: * `DISCARD_AFTER_MUTATION`: If you select this option, the new WAN events generated by the member are dropped and not replicated to the target cluster when the WAN event queues are full. * `THROW_EXCEPTION`: If you select this option, the WAN queue size is checked before each supported mutating operation (like `IMap.put()`, `ICache.put()`). If one the queues of target cluster is full, `WanReplicationQueueFullException` is thrown and the operation is not allowed. * `THROW_EXCEPTION_ONLY_IF_REPLICATION_ACTIVE`: Its effect is similar to that of `THROW_EXCEPTION`. But, it throws exception only when WAN replication is active. It discards the new events if WAN replication is stopped. The following is an example configuration: [source,xml] ---- ... test-cluster-1 DISCARD_AFTER_MUTATION ... ---- NOTE: `queue-full-behavior` configuration is optional. Its default value is `DISCARD_AFTER_MUTATION`. ==== Event Filtering API Starting with Hazelcast 3.6, WAN replication allows you to intercept WAN replication events before they are placed to WAN event replication queues by providing a filtering API. Using this API, you can monitor WAN replication events of each data structure separately. You can attach filters to your data structures using the `filter` element of `wan-replication-ref` configuration inside `hazelcast.xml` as shown below. You can also configure it using the programmatic configuration. [source,xml] ---- ... com.example.MyFilter com.example.MyFilter2 ... ---- As shown in the above configuration, you can define more than one filter. Filters are called in the order that they are introduced. A WAN replication event is only eligible to publish if it passes all the filters. Map and Cache have different filter interfaces: `MapWanEventFilter` and `CacheWanEventFilter`. Both of these interfaces have the method `filter` which takes the following parameters: * `mapName`/`cacheName`: Name of the related data structure. * `entryView`: link:https://docs.hazelcast.org/docs/latest/javadoc/com/hazelcast/core/EntryView.html[EntryView^] or link:https://docs.hazelcast.org/docs/latest/javadoc/com/hazelcast/cache/CacheEntryView.html[CacheEntryView^] depending on the data structure. * `eventType`: Enum type - `UPDATED(1)`, `REMOVED(2)` or `LOADED(3)` - depending on the event. NOTE: `LOADED` events are filtered out and not replicated to target cluster. ==== Acknowledgment Types Starting with Hazelcast 3.6, WAN replication supports different acknowledgment (ACK) types for each target cluster. You can choose from 2 different ACK type depending on your consistency requirements. The following ACK types are supported: * `ACK_ON_RECEIPT`: A batch of replication events is considered successful as soon as it is received by the target cluster. This option does not guarantee that the received event is actually applied but it is faster. * `ACK_ON_OPERATION_COMPLETE`: This option guarantees that the event is received by the target cluster and it is applied. It is more time consuming. But it is the best way if you have strong consistency requirements. The following is an example configuration: [source,xml] ---- ... test-cluster-1 ACK_ON_OPERATION_COMPLETE ... ---- NOTE: `acknowledge-type` configuration is optional. Its default value is `ACK_ON_OPERATION_COMPLETE`. ==== Synchronizing WAN Target Cluster Starting with Hazelcast 3.7 you can initiate a synchronization operation on an IMap for a specific target cluster. Synchronization operation sends all the data of an IMap to a target cluster to align the state of target IMap with source IMap. Synchronization is useful if two remote clusters lost their synchronization due to WAN queue overflow or in restart scenarios. Synchronization can be initiated through link:https://docs.hazelcast.org/docs/management-center/latest/manual/html/index.html#wan-sync[Management Center^] and Hazelcast’s REST API. Below is the URL for the REST call; ``` http://member_ip:port/hazelcast/rest/mancenter/wan/sync/map ``` You need to add parameters to the request in the following order separated by ""&""; * Name of the WAN replication configuration * Target cluster name * Map name to be synchronized Assume that you have configured an IMap with a WAN replication configuration as follows: [source,xml] ---- ... istanbul com.hazelcast.spi.merge.PassThroughMergePolicy ... ---- Then, an example CURL command to initiate the synchronization for ""my-map"" would be as follows: ``` curl -H ""Content-type: text/plain"" -X POST -d ""my-wan-cluster&istanbul&my-map"" --URL http://127.0.0.1:5701/hazelcast/rest/mancenter/wan/sync/map ``` [NOTE] .Synchronizing All Maps ==== You can also use the following URL in your REST call if you want to synchronize all the maps in source and target cluster: `+http://member_ip:port/hazelcast/rest/mancenter/wan/sync/allmaps+` ==== NOTE: Synchronization for a target cluster operates only with the data residing in the memory. Therefore, evicted entries are not synchronized, not even if `MapLoader` is configured. ==== Dynamically Adding WAN Publishers When running clusters for an extensive period, you might need to dynamically change the configuration while the cluster is running. This includes dynamically adding new WAN replication publishers (new target clusters) and replicating the subsequent map and cache updates to the new publishers without any manual intervention. You can add new WAN publishers to an existing WAN replication using almost all of the configuration options that are available when configuring the WAN publishers in the static configuration (including using Discovery SPI). The new configuration is not persisted but it is replicated to all existing and new members. Once the cluster is completely restarted, the dynamically added publisher configuration is lost and the updates are not replicated to the target cluster anymore until added again. If you wish to preserve the new configuration over cluster restarts, you must add the exact same configuration to the static configuration file after dynamically adding the publisher configuration to a running cluster. You cannot remove the existing configurations but can put the publishers into a STOPPED state which prevents the WAN events from being enqueued in the WAN queues and prevents the replication, rendering the publisher idle. The configurations also cannot be changed. Synchronization can be initiated through link:https://docs.hazelcast.org/docs/management-center/latest/manual/html/index.html#wan-sync[Management Center^] and Hazelcast’s REST API. Below is the URL for the REST call: ``` http://member_ip:port/hazelcast/rest/mancenter/wan/addWanConfig ``` You need to add the configuration for the WAN publishers as a JSON parameter. You can, at any point, even when maps and caches are concurrently mutated, add a new WAN publisher to an existing WAN replication configuration. The limitation is that there must be an existing WAN replication configuration but it can be empty, without any publishers (target clusters). For instance, this is an example of an XML configuration to which you can dynamically add new publishers: [source,xml] ---- ... com.hazelcast.spi.merge.PassThroughMergePolicy false ... ---- Note that the map has defined WAN replication but there is no target cluster yet. You can then add the new WAN replication publishers (target clusters) by performing an HTTP POST as shown below: ``` curl -H ""Content-type: text/plain"" -X POST -d ""{...}"" --URL http://127.0.0.1:5701/hazelcast/rest/mancenter/wan/addWanConfig ``` You can provide the full configuration as JSON as a parameter. Any WAN configuration supported in the XML and programmatic configurations is also supported in this JSON format. Below are some examples of JSON configuration for a WAN publisher using the Discovery SPI and static IP configuration. Here are the integer values for `initialPublisherState`, `queueFullBehavior` and `consistencyCheckStrategy`: * `initialPublisherState`: ** 0: REPLICATING ** 1: PAUSED ** 2: STOPPED * `queueFullBehavior`: ** 0: DISCARD_AFTER_MUTATION ** 1: THROW_EXCEPTION ** 2: THROW_EXCEPTION_ONLY_IF_REPLICATION_ACTIVE * `consistencyCheckStrategy`: ** 0: NONE ** 1: MERKLE_TREES Below is an example using Discovery SPI (AWS configuration): ``` { ""name"":""wanReplication"", ""publishers"":[ { ""clusterName"":""tokyo"", ""queueCapacity"":10000, ""queueFullBehavior"":0, ""initialPublisherState"":0, ""discovery"":{ ""nodeFilterClass"":null, ""discoveryStrategy"":[ { ""className"":""com.hazelcast.aws.AwsDiscoveryStrategy"", ""properties"":{ ""security-group-name"":""hazelcast"", ""tag-value"":""cluster1"", ""host-header"":""ec2.amazonaws.com"", ""tag-key"":""aws-test-cluster"", ""secret-key"":""my-secret-key"", ""iam-role"":""s3access"", ""access-key"":""my-access-key"", ""hz-port"":""5701-5708"", ""region"":""us-west-1"" } } ] } } ] } ``` Below is an example with Discovery SPI (the new AWS configuration) ``` { ""name"":""wanReplication"", ""publishers"":[ { ""clusterName"":""tokyo"", ""queueCapacity"":1000, ""queueFullBehavior"":0, ""initialPublisherState"":0, ""aws"":{ ""enabled"":true, ""usePublicIp"":false, ""properties"":{ ""security-group-name"":""hazelcast-sg"", ""tag-value"":""hz-nodes"", ""host-header"":""ec2.amazonaws.com"", ""tag-key"":""type"", ""secret-key"":""my-secret-key"", ""iam-role"":""dummy"", ""access-key"":""my-access-key"", ""region"":""us-west-1"" } }, ""sync"":{ ""consistencyCheckStrategy"":0 } } ] } ``` Below is an example with static IP configuration (with some optional attributes): ``` { ""name"":""wanReplication"", ""publishers"":[ { ""clusterName"":""tokyo"", ""queueCapacity"":1000, ""queueFullBehavior"":0, ""initialPublisherState"":0, ""responseTimeoutMillis"":5000, ""targetEndpoints"":""10.3.5.1:5701, 10.3.5.2:5701"", ""batchMaxDelayMillis"":3000, ""batchSize"":50, ""snapshotEnabled"":false, ""acknowledgeType"":1, ""sync"":{ ""consistencyCheckStrategy"":0 } } ] } ``` Below is an XML configuration with two publishers and several (disabled) discovery strategy configurations: ``` { ""name"":""wanReplication"", ""publishers"":[ { ""clusterName"":""tokyo"", ""queueCapacity"":1000, ""queueFullBehavior"":0, ""initialPublisherState"":0, ""aws"":{ ""enabled"":true, ""usePublicIp"":false, ""properties"":{ ""security-group-name"":""hazelcast-sg"", ""tag-value"":""hz-nodes"", ""host-header"":""ec2.amazonaws.com"", ""tag-key"":""type"", ""secret-key"":""my-secret-key"", ""iam-role"":""dummy"", ""access-key"":""my-access-key"", ""region"":""us-west-1"" } }, ""gcp"":{ ""enabled"":false, ""usePublicIp"":true, ""properties"":{ ""gcp-prop"":""gcp-val"" } }, ""azure"":{ ""enabled"":false, ""usePublicIp"":true, ""properties"":{ ""azure-prop"":""azure-val"" } }, ""kubernetes"":{ ""enabled"":false, ""usePublicIp"":true, ""properties"":{ ""k8s-prop"":""k8s-val"" } }, ""eureka"":{ ""enabled"":false, ""usePublicIp"":true, ""properties"":{ ""eureka-prop"":""eureka-val"" } }, ""discovery"":{ ""nodeFilterClass"":null, ""discoveryStrategy"":[ ] }, ""sync"":{ ""consistencyCheckStrategy"":0 } }, { ""clusterName"":""london"", ""queueCapacity"":1000, ""queueFullBehavior"":0, ""initialPublisherState"":0, ""responseTimeoutMillis"":5000, ""targetEndpoints"":""10.3.5.1:5701, 10.3.5.2:5701"", ""batchMaxDelayMillis"":3000, ""batchSize"":50, ""snapshotEnabled"":false, ""acknowledgeType"":1, ""aws"":{ ""enabled"":false, ""usePublicIp"":false }, ""gcp"":{ ""enabled"":false, ""usePublicIp"":false }, ""azure"":{ ""enabled"":false, ""usePublicIp"":false }, ""kubernetes"":{ ""enabled"":false, ""usePublicIp"":false }, ""eureka"":{ ""enabled"":false, ""usePublicIp"":false }, ""discovery"":{ ""nodeFilterClass"":null, ""discoveryStrategy"":[ ] }, ""sync"":{ ""consistencyCheckStrategy"":1 } } ] } ``` ==== WAN Replication Failure Detection and Recovery The failure detection and recovery mechanisms in WAN handle failures during WAN replication and they closely interact with the list of endpoints that WAN is replicating to. There might be some small differences when using static endpoints or the discovery SPI but here we will outline the general mechanism of failure detection and recovery. ===== WAN Target Endpoint List The WAN connection manager maintains a list of public addresses that it can replicate to at any moment. This list may change over time as failures are detected or as new addresses are discovered when using the discovery SPI. The connection manager does not eagerly create connections to these addresses as they are added to the list to avoid overloading the endpoint with connections from all members using the same configuration. It tries to connect to the endpoint just before WAN events are about to be transmitted. This means that if there are no updates on the map or cache using WAN replication, there are no WAN events and the connection will not be established to the endpoint. When more than one endpoint is configured, traffic is load balanced between them using the partition, so that the same partitions are always sent to the same target member, ensuring ordering by partition. ===== WAN Failure Detection If using the Hazelcast IMDG Enterprise edition class `WanBatchReplication` (see the <>), the WAN replication catches any exceptions when sending the WAN events to the endpoint. In the case of an exception, the endpoint is removed from the endpoint list to which WAN replicates and the WAN events are resent to a different address. The replication is retried until it is successful. ===== WAN Endpoint Recovery The WAN connection manager tries to ""rediscover"" new endpoints periodically. The period is 10 seconds by default but can be configured using the `discovery-period-seconds` element (see the <>). The discovered endpoints depend on the configuration used to define WAN replication. If using static WAN endpoints (by using the `target-endpoints` element), the discovered endpoints are always the same and are equal to the values defined in the configuration. If using discovery SPI with WAN, the discovered endpoints may be different each time. When the discovery returns a list of endpoints (addresses), the WAN target endpoint list is updated. Newly discovered endpoints are added and endpoints which are no longer in the discovered list are removed. Newly discovered endpoints may include addresses to which WAN replication has previously failed. This means that once a new WAN event is about to be sent, a connection is reestablished to the previously failed endpoint and WAN replication is retried. The endpoint can later be again removed from the target endpoint list if the replication again encounters failure. [[tune-wr]] ==== Tuning WAN Replication For Lower Latencies and Higher Throughput Starting with Hazelcast IMDG 3.12, we have redesigned the WAN replication mechanism to allow tuning for lower latencies of replication and higher throughput. In most cases, WAN replication is sufficient with out-of-the-box settings which cause WAN replication to replicate the map and cache events with little overhead. However, there might be some use cases where the latency between a map/cache mutation on one cluster and its visibility on the other cluster must be kept within some bounds. To achieve such demands, you can first try tuning the WAN replication mechanism using the following publisher elements: * `batch-size` * `batch-max-delay-millis` * `idle-min-park-ns` * `idle-max-park-ns` To understand the implications of these elements, let's first dive into how WAN replication works. WAN replication runs in a separate thread and tries to send map and cache mutation events in batches to the target endpoints for higher throughput. The target endpoints are usually members in a target Hazelcast cluster but different WAN implementations may have different target endpoints. The event batch is collected by iterating over the WAN queues for different partitions and, different maps and caches. WAN replication tries and collects a batch of a size which can be configured using the `batch-size` element. If enough time has passed and the WAN replication thread hasn't collected enough events to fill a batch, it sends what it has collected nevertheless. This is controlled by the `batch-max-delay-millis` element. The ""enough time"" precisely means that more than the configured amount of milliseconds has passed since the time the last batch was sent to any target endpoint. If there are no events in any of the WAN queues, the WAN replication thread goes into the idle state by parking the WAN replication thread. The minimum park time can be defined using the `idle-min-park-ns` element and the maximum park time can be controlled using the `idle-max-park-ns` element. If a WAN event is enqueued while the WAN replication thread is in the idle state, the latency for replication of that WAN event increases. An example WAN replication configuration using the default values of the above elements is shown below. [source,xml] ---- ... london 500 1000 10000000 250000000 ... ... ---- We will now discuss tuning these elements. Unfortunately, the exact tuning parameters heavily depend on the load, mutation rate, latency between the source and target clusters and even use cases. We will thus discuss some general approaches and pointers. When tuning for low latency, the first thing you might want to do is lower the `idle-min-park-ns` and `idle-max-park-ns` element values. This will affect the latencies that you see when having a low number of operations per second, since this is when the WAN replication thread will be mostly in idle state. Try lowering both elements but keep in mind that the lower the element value, the more time the WAN replication thread will spend consuming CPU in a quiescent state - when there is no mutation on the maps or caches. The next element you might lower is the `batch-max-delay-millis`. If you have a strict upper bound on the latency for WAN replication, this element must be below that limit. Setting this value too low might adversely affect the performance as well since then the WAN replication thread might be sending smaller batches than what it would if the element was higher and it had waited for some more time. You can even try setting this element to zero which instructs the WAN replication thread to send batches as soon as it is able to collect any events; but keep in mind this will result in many smaller batches instead of less bigger event batches. When tuning for lower latencies, configuring the `batch-size` usually has little effect, especially at lower mutation rates. At a low number of operations per second, the event batches will usually be very small since the WAN replication thread will not be able to collect the full batch and respect the required latencies for replication. The `batch-size` element might have more effect at higher mutation rates. Here, you will probably want to use bigger batches to avoid paying for the latencies when sending lots of smaller batches, so try increasing the batch size and benchmarking at high load. There are a couple of other configuration values that you might try changing but it depends on your use case. The first one is adding a separate configuration for a WAN replication executor. Collecting of WAN event batches and processing the responses from the target endpoints are done on a shared executor. This executor is shared between the other parts of the Hazelcast system and all of the WAN replication publishers will use the same executor. In some cases, you might want to create a dedicated executor for all WAN replication publishers. The name of this executor is `hz:wan`. Below is an example of a concrete, dedicated executor for WAN replication. See the <> for more information on the configuration options of the executor. [source,xml] ---- ... 16 ... ---- The last two elements that you might want to change are `acknowledge-type` and `max-concurrent-invocations`. Changing these elements allow you to get a greater throughput at the expense of event ordering. This means that these elements may only be changed if your application can tolerate WAN events to be received out-of-order. For instance, if you are updating or removing the existing map or cache entries, an out-of-order WAN event delivery would mean that the event for the entry removal or update might be processed by the target cluster before the event is received to create that entry. This does not causes exceptions but it causes the clusters to fall out-of-sync. In these cases, you most probably will not be able to use these elements. On the other hand, if you are only creating new, immutable entries (which are then removed by the expiration mechanism), you can use these elements to achieve a greater throughput. The `acknowledge-type` element controls at which time the target cluster will send a response for the received WAN event batch. The default value is `ACK_ON_OPERATION_COMPLETE` which will ensure that all events are processed before the response is sent to the source cluster. The value `ACK_ON_RECEIPT` instructs the target cluster to send a response as soon as it has received the WAN event batch but before it has been processed. This has two implications. One is that events can now be processed out-of-order (see the previous paragraph) and the other is that the exceptions thrown on processing the WAN event batch will not be received by the source cluster and the WAN event batch will not be retried. As such, some events might get lost in case of errors and the clusters may fall out-of-sync. WAN sync can help bring those clusters in-sync. The benefit of the `ACK_ON_RECEIPT` value is that now the source cluster can send a new batch sooner, without waiting for the previous batch to be processed fully. NOTE: WAN synchronization strategies (neither the default nor the <>) don't synchronize the deletions since they are not yet tracked under WAN. The `max-concurrent-invocations` element controls the maximum number of WAN event batches being sent to the target cluster concurrently. Setting this element to anything less than 2 will only allow a single batch of events to be sent to each target endpoint and will maintain causality of events for a single partition (events are not received out-of-order). Setting this element to 2 or higher will allow multiple batches of WAN events to be sent to each target endpoint. Since this allows reordering of batches due to the network conditions, causality and ordering of events for a single partition is lost and batches for a single partition are now sent randomly to any available target endpoint. This, however, does present a faster WAN replication for certain scenarios such as replicating immutable, independent map entries which are only added once and where ordering, when these entries are added, is not necessary. Keep in mind that if you set this element to a value which is less than the target endpoint count, you will lose performance as not all target endpoints will be used at any point in time to process the WAN event batches. So, for instance, if you have a target cluster with 3 members (target endpoints) and you want to use this element, it only makes sense to set it to a value higher than 3. Otherwise, you can simply disable it by setting it to less than 2 in which case WAN will use the default replication strategy and adapt to the target endpoint count while maintaining causality. An example WAN replication configuration using the default values of the aforementioned elements is shown below. [source,xml] ---- ... london ACK_ON_OPERATION_COMPLETE -1 ... ... ---- Finally, as we've mentioned, the exact values which will give you the optimal performance depend on your environment and use case. Please benchmark and try out different values to find out the right values for you. ==== WAN Replication Additional Information Each cluster in WAN topology has to have a unique `cluster-name` property for a proper handling of forwarded events. Starting with Hazelcast 3.6, WAN replication backs up its event queues to other members to prevent event loss in case of member failures. WAN replication's backup mechanism depends on the related data structures' backup operations. Note that, WAN replication is supported for IMap and ICache. That means, as far as you set a backup count for your IMap or ICache instances, WAN replication events generated by these instances are also replicated. There is no additional configuration to enable/disable WAN replication event backups. === Delta WAN Synchronization Hazelcast clusters connected over WAN can go out-of-sync because of various reasons such as member failures and concurrent updates. To overcome the out-of-sync issue, Hazelcast has the default <> feature, through which the maps in different clusters are synced by transferring all entries from the source to the target cluster. This may be not efficient since some of the entries have remained unchanged on both clusters and do not require to be transferred. Also, for the entries to be transferred, they need to be copied to on-heap on the source cluster. This may cause spikes in the heap usage, especially if using large off-heap stores. Besides the default WAN synchronization, Hazelcast provides Delta WAN Synchronization which uses link:https://en.wikipedia.org/wiki/Merkle_tree[Merkle tree^] for the same purpose. It is a data structure used for efficient comparison of the difference in the contents of large data structures. The precision of this comparison is defined by Merkle tree's depth. Merkle tree hash exchanges can detect inconsistencies in the map data and synchronize only the different entries when using WAN synchronization, instead of sending all the map entries. NOTE: Currently, Delta WAN Synchronization is implemented only for Hazelcast IMap. It will also be implemented for ICache in the future releases. ==== Requirements To be able to use Delta WAN synchronization, the following must be met: * Source and target cluster versions must be at least Hazelcast 3.11. * Both clusters must have the same number of partitions. * Both clusters must use the same partitioning strategy. * Both clusters must have the Merkle tree structure enabled. ==== Using Delta WAN Synchronization To be able to use Delta WAN synchronization for a Hazelcast data structure: . Configure the WAN synchronization mechanism for your WAN publisher so that it uses the Merkle tree: If configuring declaratively, you can use the `consistency-check-strategy` sub-element of the `wan-sync` element. If configuring programmatically, you can use the setter of the link:https://docs.hazelcast.org/docs/3.11/javadoc/com/hazelcast/config/WanSyncConfig.html[WanSyncConfig^] object. . Bind that WAN synchronization configuration to the data structure (currently IMap): Simply set the WAN replication reference of your map to the name of the WAN replication configuration which uses the Merkle tree. Following is a declarative configuration example of the above: [source,xml] ---- ... clusterName MERKLE_TREES ... ---- Here, the element `consistency-check-strategy` sets the strategy for checking the consistency of data between the source and target clusters. You must initiate the WAN synchronization (via Management Center or REST API as explained in <>) to let this strategy reconcile the inconsistencies. The element `consistency-check-strategy` has currently two values: * `NONE`: Means that there are no consistency checks. This is the default value. * `MERKLE_TREES`: Means that WAN synchronization uses Merkle tree structure. ==== Configuring Delta WAN Synchronization You can configure Delta WAN Synchronization declaratively using the `merkle-tree` element or programmatically using the link:https://docs.hazelcast.org/docs/3.11/javadoc/com/hazelcast/config/MerkleTreeConfig.html[MerkleTreeConfig^] object. Following is a declarative configuration example showing how to enable Delta WAN Synchronization, bind it to a Hazelcast data structure (an IMap in the below case) and specify its depth. [source,xml] ---- ... 5 ... ---- Here are the descriptions of sub-elements and attributes: * `enabled`: Specifies whether the Merkle tree structure is enabled. Its default value is `true`. * `mapName`: Specifies the name of the map for which the Merkle tree structure is used. * `depth`: Specifies the depth of Merkle tree. Valid values are between 2 and 27 (exclusive). Its default value is `10`. ** A larger depth means that a data synchronization mechanism is able to pinpoint a smaller subset of the data structure (e.g., IMap) contents in which a change has occurred. This causes the synchronization mechanism to be more efficient. However, keep in mind that a large depth means that the Merkle tree will consume more memory. As the comparison mechanism is iterative, a larger depth also prolongs the comparison duration. Therefore, it is recommended not to have large tree depths if the latency of the comparison operation is high. ** A smaller depth means that the Merkle tree is shallower and the data synchronization mechanism transfers larger chunks of the data structure (e.g., IMap) in which a possible change has happened. As you can imagine, a shallower Merkle tree will consume less memory. Following is a declarative example including the Merkle tree configuration. [source,xml] ---- ... ... 10 clusterName MERKLE_TREES ... ---- NOTE: If you do not specifically configure the `merkle-tree` in your Hazelcast configuration, Hazelcast uses the default Merkle tree structure values (i.e., it is enabled by default and its default depth is 10) when there is a WAN publisher using the Merkle tree (i.e., `consistency-check-strategy` for a WAN replication configuration is set as `MERKLE_TREES` and there is a data structure using that WAN replication configuration). NOTE: Merkle trees are created for each partition holding IMap data. Therefore, increasing the partition count also increases the efficiency of the Delta WAN Synchronization. ==== The Process Synchronizing the maps based on Merkle trees consists of two phases: 1. _Consistency check_: Process of exchanging and comparing the hashes stored in the Merkle tree structures in the source and target clusters. The check starts with the root node and continues recursively with the children with different hash codes. Both sides send the children of the nodes that the other side sent, hence the comparison is done by `depth/2` steps. After this check, the tree leaves holding different entries are identified. 2. _Synchronization_: Process of transferring the entries belong to the leaves identified by the _consistency check_ from the source to target cluster. On the target cluster the configured merge policy is applied for each entry that is in both the source and target clusters. NOTE: If you only need the differences between the clusters, you can trigger the consistency check without performing synchronization. ==== Memory Consumption Since Merkle trees are built for each partition and each map, the memory overhead of the trees with high entry count and deep trees can be significant. The trees are maintained on-heap, therefore - besides the memory consumption - garbage collection could be another concern. Make sure the configuration is tested with realistic data size before deployed in production. The table below shows a few examples for what the memory overhead could be. .Merkle trees memory overhead for a member |=== |Entries Stored |Partitions Owned |Entries per Leaf |Depth |Memory Overhead |1M |271 |7 |10 |57 MB |1M |271 |1 |13 |97 MB |10M |271 |72 |10 |412 MB |10M |271 |9 |13 |453 MB |10M |5009 |4 |10 |577 MB |10M |5009 |1 |12 |900 MB |25M |5009 |10 |10 |1986 MB |25M |5009 |1 |13 |2740 MB |=== ==== Defining the Depth The efficiency of the Delta WAN Synchronization (WAN synchronization based on Merkle trees) is determined by the average number of entries per the tree leaves that is proportionate to the number of entries in the map. The bigger this average the more entries are getting synchronized for the same difference. Raising the depth decreases this average at the cost of increasing the memory overhead. This average can be calculated for a map as `avgEntriesPerLeaf = mapEntryCount / totalLeafCount`, where `totalLeafCount = partitionCount * 2^depth-1^`. The ideal value is 1, however this may come at significant memory overhead as shown in the table above. In order to specify the tree depth, a trade-off between memory consumption and effectiveness might be needed. Even if the map is huge and the Merkle trees are configured to be relatively shallow, the Merkle tree based synchronization may be leveraged if only a small subset of the whole map is expected to be synchronized. The table below illustrates the efficiency of the Merkle tree based synchronization compared to the default synchronization mechanism. .Efficiency examples |=== |Map entry count |Depth |Memory consumption |Avg entries / leaf |Difference count |Entries synced |Efficiency |10M |11 |685 MB |2 |5M |10M |0% |10M |12 |900 MB |1 |5M |5M |100% |10M |10 |577 MB |4 |1M |4M |150% |10M |8 |497 MB |16 |10K |160K |6150% |10M |12 |900 MB |1 |10K |10K |99900% |=== The `Difference count` column shows the number of the entries different in the source and the target clusters. This is the minimum number of the entries that need to be synchronized to make the clusters consistent. The `Entries synced` column shows how many entries are synchronized in the given case, calculated as `Entries synced` = `Difference count` * `Avg entries / leaf`. As shown in the last two rows, the Merkle tree based synchronization transfers significantly less entries than what the default mechanism does even with 8 deep trees. The efficiency with depth 12 is even better but consumes much more memory. NOTE: The averages in the table are calculated with 5009 partitions. NOTE: The average entries per leaf number above assumes perfect distribution of the entries amongst the leaves. Since this is typically not true in real-life scenarios the efficiency can be slightly worse. The statistics section below describes how to get the actual average for the leaves involved in the synchronization. ==== REST API NOTE: To be able to use the REST calls related to synchronization, you need to enable the `WAN` REST endpoint group. See the <> for details. The two phases of the Merkle tree based synchronization can be triggered by a REST call, as it can be done with the default synchronization. The URL for the consistency check REST call: ``` http://member_ip:port/hazelcast/rest/mancenter/wan/consistencyCheck/map ``` The URL for the synchronization REST call - the same as it is for the default synchronization: ``` http://member_ip:port/hazelcast/rest/mancenter/wan/sync/map ``` You need to add parameters to the request in both cases in the following order separated by ""&""; * Name of the WAN replication configuration * Target cluster name * Map name to be synchronized NOTE: You can also use the following URL in your REST call if you want to synchronize all the maps in source and target cluster: `+http://member_ip:port/hazelcast/rest/mancenter/wan/sync/allmaps+` NOTE: Consistency check can be triggered only for one map. ==== Statistics The consistency check and the synchronization both write statistics into the diagnostics subsystem and send it to the Management Center. The following reported fields can be used to reason about the efficiency of the configuration. Consistency check reports the number of the: * Merkle tree nodes checked * Merkle tree nodes found to be different * and entries needed to be synchronized to make the clusters consistent. Synchronization reports the: * duration of the synchronization * number of the entries synchronized * average number of the entries per tree leaves in the synchronized leaves. ",16299,True,2880.6245563812595,median "/* Feathers Copyright 2012-2013 Joshua Tynjala. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.layout { import feathers.core.IFeathersControl; import flash.geom.Point; import starling.display.DisplayObject; import starling.events.Event; import starling.events.EventDispatcher; /** * Dispatched when a property of the layout changes, indicating that a * redraw is probably needed. * * @eventType starling.events.Event.CHANGE */ [Event(name=""change"",type=""starling.events.Event"")] /** * Positions items as tiles (equal width and height) from top to bottom * in multiple columns. Constrained to the suggested height, the tiled * columns layout will change in width as the number of items increases or * decreases. * * @see http://wiki.starling-framework.org/feathers/tiled-columns-layout */ public class TiledColumnsLayout extends EventDispatcher implements IVirtualLayout { /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the top. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_TOP:String = ""top""; /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the middle. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_MIDDLE:String = ""middle""; /** * If the total item height is smaller than the height of the bounds, * the items will be aligned to the bottom. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_BOTTOM:String = ""bottom""; /** * If the total item width is smaller than the width of the bounds, the * items will be aligned to the left. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_LEFT:String = ""left""; /** * If the total item width is smaller than the width of the bounds, the * items will be aligned to the center. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_CENTER:String = ""center""; /** * If the total item width is smaller than the width of the bounds, the * items will be aligned to the right. * * @see #horizontalAlign */ public static const HORIZONTAL_ALIGN_RIGHT:String = ""right""; /** * If an item height is smaller than the height of a tile, the item will * be aligned to the top edge of the tile. * * @see #tileVerticalAlign */ public static const TILE_VERTICAL_ALIGN_TOP:String = ""top""; /** * If an item height is smaller than the height of a tile, the item will * be aligned to the middle of the tile. * * @see #tileVerticalAlign */ public static const TILE_VERTICAL_ALIGN_MIDDLE:String = ""middle""; /** * If an item height is smaller than the height of a tile, the item will * be aligned to the bottom edge of the tile. * * @see #tileVerticalAlign */ public static const TILE_VERTICAL_ALIGN_BOTTOM:String = ""bottom""; /** * The item will be resized to fit the height of the tile. * * @see #tileVerticalAlign */ public static const TILE_VERTICAL_ALIGN_JUSTIFY:String = ""justify""; /** * If an item width is smaller than the width of a tile, the item will * be aligned to the left edge of the tile. * * @see #tileHorizontalAlign */ public static const TILE_HORIZONTAL_ALIGN_LEFT:String = ""left""; /** * If an item width is smaller than the width of a tile, the item will * be aligned to the center of the tile. * * @see #tileHorizontalAlign */ public static const TILE_HORIZONTAL_ALIGN_CENTER:String = ""center""; /** * If an item width is smaller than the width of a tile, the item will * be aligned to the right edge of the tile. * * @see #tileHorizontalAlign */ public static const TILE_HORIZONTAL_ALIGN_RIGHT:String = ""right""; /** * The item will be resized to fit the width of the tile. * * @see #tileHorizontalAlign */ public static const TILE_HORIZONTAL_ALIGN_JUSTIFY:String = ""justify""; /** * The items will be positioned in pages horizontally from left to right. * * @see #paging */ public static const PAGING_HORIZONTAL:String = ""horizontal""; /** * The items will be positioned in pages vertically from top to bottom. * * @see #paging */ public static const PAGING_VERTICAL:String = ""vertical""; /** * The items will not be paged. In other words, they will be positioned * in a continuous set of columns without gaps. * * @see #paging */ public static const PAGING_NONE:String = ""none""; /** * Constructor. */ public function TiledColumnsLayout() { } /** * @private */ protected var _discoveredItemsCache:Vector. = new []; /** * Quickly sets both horizontalGap and verticalGap * to the same value. The gap getter always returns the * value of verticalGap, but the value of * horizontalGap may be different. * * @default 0 * * @see #horizontalGap * @see #verticalGap */ public function get gap():Number { return this._verticalGap; } /** * @private */ public function set gap(value:Number):void { this.horizontalGap = value; this.verticalGap = value; } /** * @private */ protected var _horizontalGap:Number = 0; /** * The horizontal space, in pixels, between tiles. * * @default 0 */ public function get horizontalGap():Number { return this._horizontalGap; } /** * @private */ public function set horizontalGap(value:Number):void { if(this._horizontalGap == value) { return; } this._horizontalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalGap:Number = 0; /** * The vertical space, in pixels, between tiles. * * @default 0 */ public function get verticalGap():Number { return this._verticalGap; } /** * @private */ public function set verticalGap(value:Number):void { if(this._verticalGap == value) { return; } this._verticalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * Quickly sets all padding properties to the same value. The * padding getter always returns the value of * paddingTop, but the other padding values may be * different. * * @default 0 * * @see #paddingTop * @see #paddingRight * @see #paddingBottom * @see #paddingLeft */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The space, in pixels, above of items. * * @default 0 */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingRight:Number = 0; /** * The space, in pixels, to the right of the items. * * @default 0 */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The space, in pixels, below the items. * * @default 0 */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The space, in pixels, to the left of the items. * * @default 0 */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalAlign:String = VERTICAL_ALIGN_TOP; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * If the total column height is less than the bounds, the items in the * column can be aligned vertically. * * @default TiledColumnsLayout.VERTICAL_ALIGN_TOP * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get verticalAlign():String { return this._verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this._verticalAlign == value) { return; } this._verticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _horizontalAlign:String = HORIZONTAL_ALIGN_CENTER; [Inspectable(type=""String"",enumeration=""left,center,right"")] /** * If the total row width is less than the bounds, the items in the row * can be aligned horizontally. * * @default TiledColumnsLayout.HORIZONTAL_ALIGN_CENTER * * @see #HORIZONTAL_ALIGN_LEFT * @see #HORIZONTAL_ALIGN_CENTER * @see #HORIZONTAL_ALIGN_RIGHT */ public function get horizontalAlign():String { return this._horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if(this._horizontalAlign == value) { return; } this._horizontalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _tileVerticalAlign:String = TILE_VERTICAL_ALIGN_MIDDLE; [Inspectable(type=""String"",enumeration=""top,middle,bottom,justify"")] /** * If an item's height is less than the tile bounds, the position of the * item can be aligned vertically. * * @default TiledColumnsLayout.TILE_VERTICAL_ALIGN_MIDDLE * * @see #TILE_VERTICAL_ALIGN_TOP * @see #TILE_VERTICAL_ALIGN_MIDDLE * @see #TILE_VERTICAL_ALIGN_BOTTOM * @see #TILE_VERTICAL_ALIGN_JUSTIFY */ public function get tileVerticalAlign():String { return this._tileVerticalAlign; } /** * @private */ public function set tileVerticalAlign(value:String):void { if(this._tileVerticalAlign == value) { return; } this._tileVerticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _tileHorizontalAlign:String = TILE_HORIZONTAL_ALIGN_CENTER; [Inspectable(type=""String"",enumeration=""left,center,right,justify"")] /** * If the item's width is less than the tile bounds, the position of the * item can be aligned horizontally. * * @default TiledColumnsLayout.TILE_HORIZONTAL_ALIGN_CENTER * * @see #TILE_HORIZONTAL_ALIGN_LEFT * @see #TILE_HORIZONTAL_ALIGN_CENTER * @see #TILE_HORIZONTAL_ALIGN_RIGHT * @see #TILE_HORIZONTAL_ALIGN_JUSTIFY */ public function get tileHorizontalAlign():String { return this._tileHorizontalAlign; } /** * @private */ public function set tileHorizontalAlign(value:String):void { if(this._tileHorizontalAlign == value) { return; } this._tileHorizontalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paging:String = PAGING_NONE; /** * If the total combined width of the columns is larger than the width * of the view port, the layout will be split into pages where each * page is filled with the maximum number of columns that may be * displayed without cutting off any items. * * @default TiledColumnsLayout.PAGING_NONE * * @see #PAGING_NONE * @see #PAGING_HORIZONTAL * @see #PAGING_VERTICAL */ public function get paging():String { return this._paging; } /** * @private */ public function set paging(value:String):void { if(this._paging == value) { return; } this._paging = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _useSquareTiles:Boolean = true; /** * Determines if the tiles must be square or if their width and height * may have different values. * * @default true */ public function get useSquareTiles():Boolean { return this._useSquareTiles; } /** * @private */ public function set useSquareTiles(value:Boolean):void { if(this._useSquareTiles == value) { return; } this._useSquareTiles = value; this.dispatchEventWith(Event.CHANGE); } /** * Determines if items will be set invisible if they are outside the * view port. Can improve performance, especially for non-virtual * layouts. If true, you will not be able to manually * change the visible property of any items in the layout. * * @default false */ public var manageVisibility:Boolean = false; /** * @private */ protected var _useVirtualLayout:Boolean = true; /** * @inheritDoc * * @default true */ public function get useVirtualLayout():Boolean { return this._useVirtualLayout; } /** * @private */ public function set useVirtualLayout(value:Boolean):void { if(this._useVirtualLayout == value) { return; } this._useVirtualLayout = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _typicalItemWidth:Number = 0; /** * @inheritDoc */ public function get typicalItemWidth():Number { return this._typicalItemWidth; } /** * @private */ public function set typicalItemWidth(value:Number):void { if(this._typicalItemWidth == value) { return; } this._typicalItemWidth = value; } /** * @private */ protected var _typicalItemHeight:Number = 0; /** * @inheritDoc */ public function get typicalItemHeight():Number { return this._typicalItemHeight; } /** * @private */ public function set typicalItemHeight(value:Number):void { if(this._typicalItemHeight == value) { return; } this._typicalItemHeight = value; } /** * @inheritDoc */ public function layout(items:Vector., viewPortBounds:ViewPortBounds = null, result:LayoutBoundsResult = null):LayoutBoundsResult { if(!result) { result = new LayoutBoundsResult(); } if(items.length == 0) { result.contentWidth = 0; result.contentHeight = 0; result.viewPortWidth = 0; result.viewPortHeight = 0; return result; } const scrollX:Number = viewPortBounds ? viewPortBounds.scrollX : 0; const scrollY:Number = viewPortBounds ? viewPortBounds.scrollY : 0; const boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; const boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; const minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; const minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; const maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; const maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; const explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; const explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; if(!this._useSquareTiles || !this._useVirtualLayout) { this.validateItems(items); } this._discoveredItemsCache.length = 0; const itemCount:int = items.length; var tileWidth:Number = this._typicalItemWidth; var tileHeight:Number = this._typicalItemHeight; //a virtual layout assumes that all items are the same size as //the typical item, so we don't need to measure every item in //that case if(!this._useVirtualLayout) { for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(!item) { continue; } if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } var itemWidth:Number = item.width; var itemHeight:Number = item.height; if(itemWidth > tileWidth) { tileWidth = itemWidth; } if(itemHeight > tileHeight) { tileHeight = itemHeight; } } } if(tileWidth < 0) { tileWidth = 0; } if(tileHeight < 0) { tileHeight = 0; } if(this._useSquareTiles) { if(tileWidth > tileHeight) { tileHeight = tileWidth; } else if(tileHeight > tileWidth) { tileWidth = tileHeight; } } var availableWidth:Number = NaN; var availableHeight:Number = NaN; var horizontalTileCount:int = 1; if(!isNaN(explicitWidth)) { availableWidth = explicitWidth; horizontalTileCount = (explicitWidth - this._paddingLeft - this._paddingRight + this._horizontalGap) / (tileWidth + this._horizontalGap); } else if(!isNaN(maxWidth)) { availableWidth = maxWidth; horizontalTileCount = (maxWidth - this._paddingLeft - this._paddingRight + this._horizontalGap) / (tileWidth + this._horizontalGap); } if(horizontalTileCount < 1) { horizontalTileCount = 1; } var verticalTileCount:int = itemCount; if(!isNaN(explicitHeight)) { availableHeight = explicitHeight; verticalTileCount = (explicitHeight - this._paddingTop - this._paddingBottom + this._verticalGap) / (tileHeight + this._verticalGap); } else if(!isNaN(maxHeight)) { availableHeight = maxHeight; verticalTileCount = (maxHeight - this._paddingTop - this._paddingBottom + this._verticalGap) / (tileHeight + this._verticalGap); } if(verticalTileCount < 1) { verticalTileCount = 1; } const totalPageWidth:Number = horizontalTileCount * (tileWidth + this._horizontalGap) - this._horizontalGap + this._paddingLeft + this._paddingRight; const totalPageHeight:Number = verticalTileCount * (tileHeight + this._verticalGap) - this._verticalGap + this._paddingTop + this._paddingBottom; const availablePageWidth:Number = isNaN(availableWidth) ? totalPageWidth : availableWidth; const availablePageHeight:Number = isNaN(availableHeight) ? totalPageHeight : availableHeight; const startX:Number = boundsX + this._paddingLeft; const startY:Number = boundsY + this._paddingTop; const perPage:int = horizontalTileCount * verticalTileCount; var pageIndex:int = 0; var nextPageStartIndex:int = perPage; var pageStartY:Number = startY; var positionX:Number = startX; var positionY:Number = startY; var itemIndex:int = 0; var discoveredItemsCachePushIndex:int = 0; for(i = 0; i < itemCount; i++) { item = items[i]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } if(itemIndex != 0 && i % verticalTileCount == 0) { positionX += tileWidth + this._horizontalGap; positionY = pageStartY; } if(itemIndex == nextPageStartIndex) { //we're starting a new page, so handle alignment of the //items on the current page and update the positions if(this._paging != PAGING_NONE) { var discoveredItems:Vector. = this._useVirtualLayout ? this._discoveredItemsCache : items; var discoveredItemsFirstIndex:int = this._useVirtualLayout ? 0 : (itemIndex - perPage); var discoveredItemsLastIndex:int = this._useVirtualLayout ? (this._discoveredItemsCache.length - 1) : (itemIndex - 1); this.applyHorizontalAlign(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, totalPageWidth, availablePageWidth); this.applyVerticalAlign(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, totalPageHeight, availablePageHeight); if(this.manageVisibility) { this.applyVisible(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, boundsX + scrollX, scrollX + availableWidth, boundsY + scrollY, scrollY + availableHeight); } this._discoveredItemsCache.length = 0; discoveredItemsCachePushIndex = 0; } pageIndex++; nextPageStartIndex += perPage; //we can use availableWidth and availableHeight here without //checking if they're NaN because we will never reach a //new page without them already being calculated. if(this._paging == PAGING_HORIZONTAL) { positionX = startX + availableWidth * pageIndex; } else if(this._paging == PAGING_VERTICAL) { positionX = startX; positionY = pageStartY = startY + availableHeight * pageIndex; } } if(item) { switch(this._tileHorizontalAlign) { case TILE_HORIZONTAL_ALIGN_JUSTIFY: { item.x = positionX; item.width = tileWidth; break; } case TILE_HORIZONTAL_ALIGN_LEFT: { item.x = positionX; break; } case TILE_HORIZONTAL_ALIGN_RIGHT: { item.x = positionX + tileWidth - item.width; break; } default: //center or unknown { item.x = positionX + (tileWidth - item.width) / 2; } } switch(this._tileVerticalAlign) { case TILE_VERTICAL_ALIGN_JUSTIFY: { item.y = positionY; item.height = tileHeight; break; } case TILE_VERTICAL_ALIGN_TOP: { item.y = positionY; break; } case TILE_VERTICAL_ALIGN_BOTTOM: { item.y = positionY + tileHeight - item.height; break; } default: //middle or unknown { item.y = positionY + (tileHeight - item.height) / 2; } } if(this._useVirtualLayout) { this._discoveredItemsCache[discoveredItemsCachePushIndex] = item; discoveredItemsCachePushIndex++; } } positionY += tileHeight + this._verticalGap; itemIndex++; } //align the last page if(this._paging != PAGING_NONE) { discoveredItems = this._useVirtualLayout ? this._discoveredItemsCache : items; discoveredItemsFirstIndex = this._useVirtualLayout ? 0 : (nextPageStartIndex - perPage); discoveredItemsLastIndex = this._useVirtualLayout ? (this._discoveredItemsCache.length - 1) : (i - 1); this.applyHorizontalAlign(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, totalPageWidth, availablePageWidth); this.applyVerticalAlign(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, totalPageHeight, availablePageHeight); if(this.manageVisibility) { this.applyVisible(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, boundsX + scrollX, scrollX + availableWidth, boundsY + scrollY, scrollY + availableHeight); } } var totalWidth:Number = positionX + tileWidth + this._paddingRight; if(!isNaN(availableWidth)) { if(this._paging == PAGING_VERTICAL) { totalWidth = availableWidth; } else if(this._paging == PAGING_HORIZONTAL) { totalWidth = Math.ceil(itemCount / perPage) * availableWidth; } } var totalHeight:Number = totalPageHeight; if(!isNaN(availableHeight) && this._paging == PAGING_VERTICAL) { totalHeight = Math.ceil(itemCount / perPage) * availableHeight; } if(isNaN(availableWidth)) { availableWidth = totalWidth; } if(isNaN(availableHeight)) { availableHeight = totalHeight; } if(availableWidth < minWidth) { availableWidth = minWidth; } if(availableHeight < minHeight) { availableHeight = minHeight; } if(this._paging == PAGING_NONE) { discoveredItems = this._useVirtualLayout ? this._discoveredItemsCache : items; discoveredItemsLastIndex = discoveredItems.length - 1; this.applyHorizontalAlign(discoveredItems, 0, discoveredItemsLastIndex, totalWidth, availableWidth); this.applyVerticalAlign(discoveredItems, 0, discoveredItemsLastIndex, totalHeight, availableHeight); if(this.manageVisibility) { this.applyVisible(discoveredItems, discoveredItemsFirstIndex, discoveredItemsLastIndex, boundsX + scrollX, scrollX + availableWidth, boundsY + scrollY, scrollY + availableHeight); } } this._discoveredItemsCache.length = 0; if(!result) { result = new LayoutBoundsResult(); } result.contentWidth = totalWidth; result.contentHeight = totalHeight; result.viewPortWidth = availableWidth; result.viewPortHeight = availableHeight; return result; } /** * @inheritDoc */ public function measureViewPort(itemCount:int, viewPortBounds:ViewPortBounds = null, result:Point = null):Point { if(!result) { result = new Point(); } const explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; const explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; const needsWidth:Boolean = isNaN(explicitWidth); const needsHeight:Boolean = isNaN(explicitHeight); if(!needsWidth && !needsHeight) { result.x = explicitWidth; result.y = explicitHeight; return result; } const boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; const boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; const minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; const minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; const maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; const maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; var tileWidth:Number = this._typicalItemWidth; var tileHeight:Number = this._typicalItemHeight; if(tileWidth < 0) { tileWidth = 0; } if(tileHeight < 0) { tileHeight = 0; } if(this._useSquareTiles) { if(tileWidth > tileHeight) { tileHeight = tileWidth; } else if(tileHeight > tileWidth) { tileWidth = tileHeight; } } var availableWidth:Number = NaN; var availableHeight:Number = NaN; var horizontalTileCount:int = 1; if(!isNaN(explicitWidth)) { availableWidth = explicitWidth; horizontalTileCount = (explicitWidth - this._paddingLeft - this._paddingRight + this._horizontalGap) / (tileWidth + this._horizontalGap); } else if(!isNaN(maxWidth)) { availableWidth = maxWidth; horizontalTileCount = (maxWidth - this._paddingLeft - this._paddingRight + this._horizontalGap) / (tileWidth + this._horizontalGap); } if(horizontalTileCount < 1) { horizontalTileCount = 1; } var verticalTileCount:int = itemCount; if(!isNaN(explicitHeight)) { availableHeight = explicitHeight; verticalTileCount = (explicitHeight - this._paddingTop - this._paddingBottom + this._verticalGap) / (tileHeight + this._verticalGap); } else if(!isNaN(maxHeight)) { availableHeight = maxHeight; verticalTileCount = (maxHeight - this._paddingTop - this._paddingBottom + this._verticalGap) / (tileHeight + this._verticalGap); } if(verticalTileCount < 1) { verticalTileCount = 1; } const totalPageHeight:Number = verticalTileCount * (tileHeight + this._verticalGap) - this._verticalGap + this._paddingTop + this._paddingBottom; const startX:Number = boundsX + this._paddingLeft; const perPage:int = horizontalTileCount * verticalTileCount; var pageIndex:int = 0; var nextPageStartIndex:int = perPage; var positionX:Number = startX; for(var i:int = 0; i < itemCount; i++) { if(i != 0 && i % verticalTileCount == 0) { positionX += tileWidth + this._horizontalGap; } if(i == nextPageStartIndex) { pageIndex++; nextPageStartIndex += perPage; //we can use availableWidth and availableHeight here without //checking if they're NaN because we will never reach a //new page without them already being calculated. if(this._paging == PAGING_HORIZONTAL) { positionX = startX + availableWidth * pageIndex; } else if(this._paging == PAGING_VERTICAL) { positionX = startX; } } } var totalWidth:Number = positionX + tileWidth + this._paddingRight; if(!isNaN(availableWidth)) { if(this._paging == PAGING_VERTICAL) { totalWidth = availableWidth; } else if(this._paging == PAGING_HORIZONTAL) { totalWidth = Math.ceil(itemCount / perPage) * availableWidth; } } var totalHeight:Number = totalPageHeight; if(!isNaN(availableHeight) && this._paging == PAGING_VERTICAL) { totalHeight = Math.ceil(itemCount / perPage) * availableHeight; } if(needsWidth) { var resultX:Number = totalWidth; if(resultX < minWidth) { resultX = minWidth; } else if(resultX > maxWidth) { resultX = maxWidth; } result.x = resultX; } else { result.x = explicitWidth; } if(needsHeight) { var resultY:Number = totalHeight; if(resultY < minHeight) { resultY = minHeight; } else if(resultY > maxHeight) { resultY = maxHeight; } result.y = resultY; } else { result.y = explicitHeight; } return result; } /** * @inheritDoc */ public function getVisibleIndicesAtScrollPosition(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector. = null):Vector. { if(!result) { result = new []; } result.length = 0; if(this._paging == PAGING_HORIZONTAL) { this.getVisibleIndicesAtScrollPositionWithHorizontalPaging(scrollX, scrollY, width, height, itemCount, result); } else if(this._paging == PAGING_VERTICAL) { this.getVisibleIndicesAtScrollPositionWithVerticalPaging(scrollX, scrollY, width, height, itemCount, result); } else { this.getVisibleIndicesAtScrollPositionWithoutPaging(scrollX, scrollY, width, height, itemCount, result); } return result; } /** * @inheritDoc */ public function getScrollPositionForIndex(index:int, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { if(!result) { result = new Point(); } const itemCount:int = items.length; var tileWidth:Number = this._typicalItemWidth; var tileHeight:Number = this._typicalItemHeight; //a virtual layout assumes that all items are the same size as //the typical item, so we don't need to measure every item in //that case if(!this._useVirtualLayout) { for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(!item) { continue; } if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } var itemWidth:Number = item.width; var itemHeight:Number = item.height; if(itemWidth > tileWidth) { tileWidth = itemWidth; } if(itemHeight > tileHeight) { tileHeight = itemHeight; } } } if(tileWidth < 0) { tileWidth = 0; } if(tileHeight < 0) { tileHeight = 0; } if(this._useSquareTiles) { if(tileWidth > tileHeight) { tileHeight = tileWidth; } else if(tileHeight > tileWidth) { tileWidth = tileHeight; } } var verticalTileCount:int = (height - this._paddingTop - this._paddingBottom + this._verticalGap) / (tileHeight + this._verticalGap); if(verticalTileCount < 1) { verticalTileCount = 1; } if(this._paging != PAGING_NONE) { var horizontalTileCount:int = (width - this._paddingLeft - this._paddingRight + this._horizontalGap) / (tileWidth + this._horizontalGap); if(horizontalTileCount < 1) { horizontalTileCount = 1; } const perPage:Number = horizontalTileCount * verticalTileCount; const pageIndex:int = index / perPage; if(this._paging == PAGING_HORIZONTAL) { result.x = pageIndex * width; result.y = 0; } else { result.x = 0; result.y = pageIndex * height; } } else { result.x = this._paddingLeft + ((tileWidth + this._horizontalGap) * index / verticalTileCount) + (width - tileWidth) / 2; result.y = 0; } return result; } /** * @private */ protected function applyVisible(items:Vector., startIndex:int, endIndex:int, startX:Number, endX:Number, startY:Number, endY:Number):void { for(var i:int = startIndex; i <= endIndex; i++) { var item:DisplayObject = items[i]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } var itemX:Number = item.x; var itemY:Number = item.y; item.visible = ((itemX + item.width) >= startX) && (itemX < endX) && ((itemY + item.height) >= startY) && (itemY < endY); } } /** * @private */ protected function applyHorizontalAlign(items:Vector., startIndex:int, endIndex:int, totalItemWidth:Number, availableWidth:Number):void { if(totalItemWidth >= availableWidth) { return; } var horizontalAlignOffsetX:Number = 0; if(this._horizontalAlign == HORIZONTAL_ALIGN_RIGHT) { horizontalAlignOffsetX = availableWidth - totalItemWidth; } else if(this._horizontalAlign != HORIZONTAL_ALIGN_LEFT) { //we're going to default to center if we encounter an //unknown value horizontalAlignOffsetX = (availableWidth - totalItemWidth) / 2; } if(horizontalAlignOffsetX != 0) { for(var i:int = startIndex; i <= endIndex; i++) { var item:DisplayObject = items[i]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.x += horizontalAlignOffsetX; } } } /** * @private */ protected function applyVerticalAlign(items:Vector., startIndex:int, endIndex:int, totalItemHeight:Number, availableHeight:Number):void { if(totalItemHeight >= availableHeight) { return; } var verticalAlignOffsetY:Number = 0; if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { verticalAlignOffsetY = availableHeight - totalItemHeight; } else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE) { verticalAlignOffsetY = (availableHeight - totalItemHeight) / 2; } if(verticalAlignOffsetY != 0) { for(var i:int = startIndex; i <= endIndex; i++) { var item:DisplayObject = items[i]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.y += verticalAlignOffsetY; } } } /** * @private */ protected function validateItems(items:Vector.):void { const itemCount:int = items.length; for(var i:int = 0; i < itemCount; i++) { var item:DisplayObject = items[i]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } if(!(item is IFeathersControl)) { continue; } IFeathersControl(item).validate(); } } /** * @private */ protected function getVisibleIndicesAtScrollPositionWithHorizontalPaging(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector.):void { var tileWidth:Number = this._typicalItemWidth; var tileHeight:Number = this._typicalItemHeight; if(tileWidth < 0) { tileWidth = 0; } if(tileHeight < 0) { tileHeight = 0; } if(this._useSquareTiles) { if(tileWidth > tileHeight) { tileHeight = tileWidth; } else if(tileHeight > tileWidth) { tileWidth = tileHeight; } } var horizontalTileCount:int = (width - this._paddingLeft - this._paddingRight + this._horizontalGap) / (tileWidth + this._horizontalGap); if(horizontalTileCount < 1) { horizontalTileCount = 1; } var verticalTileCount:int = (height - this._paddingTop - this._paddingBottom + this._verticalGap) / (tileHeight + this._verticalGap); if(verticalTileCount < 1) { verticalTileCount = 1; } const perPage:int = horizontalTileCount * verticalTileCount; var minimumItemCount:int = perPage + 2 * verticalTileCount; if(minimumItemCount > itemCount) { minimumItemCount = itemCount; } var startPageIndex:int = Math.round(scrollX / width); var minimum:int = startPageIndex * perPage; var totalRowWidth:Number = horizontalTileCount * (tileWidth + this._horizontalGap) - this._horizontalGap; var leftSideOffset:Number = 0; var rightSideOffset:Number = 0; if(totalRowWidth < width) { if(this._horizontalAlign == HORIZONTAL_ALIGN_RIGHT) { leftSideOffset = width - this._paddingLeft - this._paddingRight - totalRowWidth; rightSideOffset = 0; } else if(this._horizontalAlign == HORIZONTAL_ALIGN_CENTER) { leftSideOffset = rightSideOffset = (width - this._paddingLeft - this._paddingRight - totalRowWidth) / 2; } else if(this._horizontalAlign == HORIZONTAL_ALIGN_LEFT) { leftSideOffset = 0; rightSideOffset = width - this._paddingLeft - this._paddingRight - totalRowWidth; } } var columnOffset:int = 0; var pageStartPosition:Number = startPageIndex * width; var partialPageSize:Number = scrollX - pageStartPosition; if(partialPageSize < 0) { partialPageSize = -partialPageSize - this._paddingRight - rightSideOffset; if(partialPageSize < 0) { partialPageSize = 0; } columnOffset = -Math.floor(partialPageSize / (tileWidth + this._horizontalGap)) - 1; minimum += columnOffset * verticalTileCount; } else if(partialPageSize > 0) { partialPageSize = partialPageSize - this._paddingLeft - leftSideOffset; if(partialPageSize < 0) { partialPageSize = 0; } columnOffset = Math.floor(partialPageSize / (tileWidth + this._horizontalGap)); minimum += columnOffset * verticalTileCount; } if(minimum < 0) { minimum = 0; columnOffset = 0; } var maximum:int = minimum + minimumItemCount; if(maximum > itemCount) { maximum = itemCount; } minimum = maximum - minimumItemCount; var resultPushIndex:int = result.length; for(var i:int = minimum; i < maximum; i++) { result[resultPushIndex] = i; resultPushIndex++; } } /** * @private */ protected function getVisibleIndicesAtScrollPositionWithVerticalPaging(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector.):void { var tileWidth:Number = this._typicalItemWidth; var tileHeight:Number = this._typicalItemHeight; if(tileWidth < 0) { tileWidth = 0; } if(tileHeight < 0) { tileHeight = 0; } if(this._useSquareTiles) { if(tileWidth > tileHeight) { tileHeight = tileWidth; } else if(tileHeight > tileWidth) { tileWidth = tileHeight; } } var horizontalTileCount:int = (width - this._paddingLeft - this._paddingRight + this._horizontalGap) / (tileWidth + this._horizontalGap); if(horizontalTileCount < 1) { horizontalTileCount = 1; } var verticalTileCount:int = (height - this._paddingTop - this._paddingBottom + this._verticalGap) / (tileHeight + this._verticalGap); if(verticalTileCount < 1) { verticalTileCount = 1; } const perPage:int = horizontalTileCount * verticalTileCount; var minimumItemCount:int = perPage + 2 * verticalTileCount; if(minimumItemCount > itemCount) { minimumItemCount = itemCount; } var startPageIndex:int = Math.round(scrollY / height); var minimum:int = startPageIndex * perPage; var totalColumnHeight:Number = verticalTileCount * (tileHeight + this._verticalGap) - this._verticalGap; var topSideOffset:Number = 0; var bottomSideOffset:Number = 0; if(totalColumnHeight < height) { if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { topSideOffset = height - this._paddingTop - this._paddingBottom - totalColumnHeight; bottomSideOffset = 0; } else if(this._horizontalAlign == VERTICAL_ALIGN_MIDDLE) { topSideOffset = bottomSideOffset = (height - this._paddingTop - this._paddingBottom - totalColumnHeight) / 2; } else if(this._horizontalAlign == VERTICAL_ALIGN_TOP) { topSideOffset = 0; bottomSideOffset = height - this._paddingTop - this._paddingBottom - totalColumnHeight; } } var rowOffset:int = 0; var pageStartPosition:Number = startPageIndex * height; var partialPageSize:Number = scrollY - pageStartPosition; if(partialPageSize < 0) { partialPageSize = -partialPageSize - this._paddingBottom - bottomSideOffset; if(partialPageSize < 0) { partialPageSize = 0; } rowOffset = -Math.floor(partialPageSize / (tileWidth + this._verticalGap)) - 1; minimum += -perPage + horizontalTileCount + rowOffset; } else if(partialPageSize > 0) { partialPageSize = partialPageSize - this._paddingTop - topSideOffset; if(partialPageSize < 0) { partialPageSize = 0; } rowOffset = Math.floor(partialPageSize / (tileWidth + this._verticalGap)); minimum += rowOffset; } if(minimum < 0) { minimum = 0; rowOffset = 0; } if(minimum + minimumItemCount >= itemCount) { //an optimized path when we're on or near the last page minimum = itemCount - minimumItemCount; var resultPushIndex:int = result.length; for(var i:int = minimum; i < itemCount; i++) { result[resultPushIndex] = i; resultPushIndex++; } } else { var columnIndex:int = 0; var rowIndex:int = (verticalTileCount + rowOffset) % verticalTileCount; var pageStart:int = int(minimum / perPage) * perPage; i = minimum; var resultLength:int = 0; do { if(i < itemCount) { result[resultLength] = i; resultLength++; } columnIndex++; if(columnIndex == horizontalTileCount) { columnIndex = 0; rowIndex++; if(rowIndex == verticalTileCount) { rowIndex = 0; pageStart += perPage; } i = pageStart + rowIndex - verticalTileCount; } i += verticalTileCount; } while(resultLength < minimumItemCount && pageStart < itemCount) } } /** * @private */ protected function getVisibleIndicesAtScrollPositionWithoutPaging(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector.):void { var tileWidth:Number = this._typicalItemWidth; var tileHeight:Number = this._typicalItemHeight; if(tileWidth < 0) { tileWidth = 0; } if(tileHeight < 0) { tileHeight = 0; } if(this._useSquareTiles) { if(tileWidth > tileHeight) { tileHeight = tileWidth; } else if(tileHeight > tileWidth) { tileWidth = tileHeight; } } var verticalTileCount:int = (height - this._paddingTop - this._paddingBottom + this._verticalGap) / (tileHeight + this._verticalGap); if(verticalTileCount < 1) { verticalTileCount = 1; } var horizontalTileCount:int = Math.ceil((width - this._paddingLeft + this._horizontalGap) / (tileWidth + this._horizontalGap)) + 1; var minimumItemCount:int = verticalTileCount * horizontalTileCount; if(minimumItemCount > itemCount) { minimumItemCount = itemCount; } var columnIndexOffset:int = 0; const totalColumnWidth:Number = Math.ceil(itemCount / verticalTileCount) * (tileWidth + this._horizontalGap) - this._horizontalGap; if(totalColumnWidth < width) { if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { columnIndexOffset = Math.ceil((width - totalColumnWidth) / (tileWidth + this._horizontalGap)); } else if(this._verticalAlign == VERTICAL_ALIGN_MIDDLE) { columnIndexOffset = Math.ceil((width - totalColumnWidth) / (tileWidth + this._horizontalGap) / 2); } } const columnIndex:int = -columnIndexOffset + Math.floor((scrollX - this._paddingLeft + this._horizontalGap) / (tileWidth + this._horizontalGap)); var minimum:int = columnIndex * verticalTileCount; if(minimum < 0) { minimum = 0; } var maximum:int = minimum + minimumItemCount; if(maximum > itemCount) { maximum = itemCount; } minimum = maximum - minimumItemCount; var resultPushIndex:int = result.length; for(var i:int = minimum; i < maximum; i++) { result[resultPushIndex] = i; resultPushIndex++; } } } } ",12148,False,2270.279718473664,median "/* Feathers Copyright 2012-2015 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.controls { import feathers.core.FeathersControl; import feathers.core.IFeathersControl; import feathers.core.ITextRenderer; import feathers.core.IValidating; import feathers.core.PropertyProxy; import feathers.events.FeathersEventType; import feathers.layout.HorizontalLayout; import feathers.layout.LayoutBoundsResult; import feathers.layout.ViewPortBounds; import feathers.skins.IStyleProvider; import feathers.system.DeviceCapabilities; import flash.display.Stage; import flash.display.StageDisplayState; import flash.events.FullScreenEvent; import flash.geom.Point; import flash.system.Capabilities; import starling.core.Starling; import starling.display.DisplayObject; import starling.events.Event; /** * A header that displays an optional title along with a horizontal regions * on the sides for additional UI controls. The left side is typically for * navigation (to display a back button, for example) and the right for * additional actions. The title is displayed in the center by default, * but it may be aligned to the left or right if there are no items on the * desired side. * *

    In the following example, a header is created, given a title, and a * back button:

    * * * var header:Header = new Header(); * header.title = ""I'm a header""; * * var backButton:Button = new Button(); * backButton.label = ""Back""; * backButton.styleNameList.add( Button.ALTERNATE_STYLE_NAME_BACK_BUTTON ); * backButton.addEventListener( Event.TRIGGERED, backButton_triggeredHandler ); * header.leftItems = new <DisplayObject>[ backButton ]; * * this.addChild( header ); * * @see ../../../help/header.html How to use the Feathers Header component */ public class Header extends FeathersControl { /** * @private */ protected static const INVALIDATION_FLAG_LEFT_CONTENT:String = ""leftContent""; /** * @private */ protected static const INVALIDATION_FLAG_RIGHT_CONTENT:String = ""rightContent""; /** * @private */ protected static const INVALIDATION_FLAG_CENTER_CONTENT:String = ""centerContent""; /** * @private */ protected static const IOS_RETINA_STATUS_BAR_HEIGHT:Number = 40; /** * @private */ protected static const IOS_NON_RETINA_STATUS_BAR_HEIGHT:Number = 20; /** * @private */ protected static const IOS_RETINA_MINIMUM_DPI:Number = 264; /** * @private */ protected static const IOS_NAME_PREFIX:String = ""iPhone OS ""; /** * @private */ protected static const STATUS_BAR_MIN_IOS_VERSION:int = 7; /** * The default IStyleProvider for all Header * components. * * @default null * @see feathers.core.FeathersControl#styleProvider */ public static var globalStyleProvider:IStyleProvider; /** * The title will appear in the center of the header. * * @see #titleAlign */ public static const TITLE_ALIGN_CENTER:String = ""center""; /** * The title will appear on the left of the header, if there is no other * content on that side. If there is content, the title will appear in * the center. * * @see #titleAlign */ public static const TITLE_ALIGN_PREFER_LEFT:String = ""preferLeft""; /** * The title will appear on the right of the header, if there is no * other content on that side. If there is content, the title will * appear in the center. * * @see #titleAlign */ public static const TITLE_ALIGN_PREFER_RIGHT:String = ""preferRight""; /** * The items will be aligned to the top of the bounds. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_TOP:String = ""top""; /** * The items will be aligned to the middle of the bounds. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_MIDDLE:String = ""middle""; /** * The items will be aligned to the bottom of the bounds. * * @see #verticalAlign */ public static const VERTICAL_ALIGN_BOTTOM:String = ""bottom""; /** * The default value added to the styleNameList of the header's * items. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_ITEM:String = ""feathers-header-item""; /** * The default value added to the styleNameList of the header's * title. * * @see feathers.core.FeathersControl#styleNameList */ public static const DEFAULT_CHILD_STYLE_NAME_TITLE:String = ""feathers-header-title""; /** * @private */ private static const HELPER_BOUNDS:ViewPortBounds = new ViewPortBounds(); /** * @private */ private static const HELPER_LAYOUT_RESULT:LayoutBoundsResult = new LayoutBoundsResult(); /** * @private */ private static const HELPER_POINT:Point = new Point(); /** * Constructor. */ public function Header() { super(); this.addEventListener(Event.ADDED_TO_STAGE, header_addedToStageHandler); this.addEventListener(Event.REMOVED_FROM_STAGE, header_removedFromStageHandler); } /** * The text renderer for the header's title. * *

    For internal use in subclasses.

    * * @see #title * @see #titleFactory * @see #createTitle() */ protected var titleTextRenderer:ITextRenderer; /** * The value added to the styleNameList of the header's * title text renderer. This variable is protected so that * sub-classes can customize the title text renderer style name in their * constructors instead of using the default style name defined by * DEFAULT_CHILD_STYLE_NAME_TITLE. * * @see feathers.core.FeathersControl#styleNameList */ protected var titleStyleName:String = DEFAULT_CHILD_STYLE_NAME_TITLE; /** * The value added to the styleNameList of each of the * header's items. This variable is protected so that * sub-classes can customize the item style name in their constructors * instead of using the default style name defined by * DEFAULT_CHILD_STYLE_NAME_ITEM. * * @see feathers.core.FeathersControl#styleNameList */ protected var itemStyleName:String = DEFAULT_CHILD_STYLE_NAME_ITEM; /** * @private */ protected var leftItemsWidth:Number = 0; /** * @private */ protected var rightItemsWidth:Number = 0; /** * @private * The layout algorithm. Shared by both sides. */ protected var _layout:HorizontalLayout; /** * @private */ override protected function get defaultStyleProvider():IStyleProvider { return Header.globalStyleProvider; } /** * @private */ protected var _title:String = """"; /** * The text displayed for the header's title. * *

    In the following example, the header's title is set:

    * * * header.title = ""I'm a Header""; * * @default """" * * @see #titleFactory */ public function get title():String { return this._title; } /** * @private */ public function set title(value:String):void { if(value === null) { value = """"; } if(this._title == value) { return; } this._title = value; this.invalidate(INVALIDATION_FLAG_DATA); } /** * @private */ protected var _titleFactory:Function; /** * A function used to instantiate the header's title text renderer * sub-component. By default, the header will use the global text * renderer factory, FeathersControl.defaultTextRendererFactory(), * to create the title text renderer. The title text renderer must be an * instance of ITextRenderer. This factory can be used to * change properties on the title text renderer when it is first * created. For instance, if you are skinning Feathers components * without a theme, you might use this factory to style the title text * renderer. * *

    If you are not using a theme, the title factory can be used to * provide skin the title with appropriate text styles.

    * *

    The factory should have the following function signature:

    *
    function():ITextRenderer
    * *

    In the following example, a custom title factory is passed to the * header:

    * * * header.titleFactory = function():ITextRenderer * { * var titleRenderer:TextFieldTextRenderer = new TextFieldTextRenderer(); * titleRenderer.textFormat = new TextFormat( ""_sans"", 12, 0xff0000 ); * return titleRenderer; * } * * @default null * * @see #title * @see feathers.core.ITextRenderer * @see feathers.core.FeathersControl#defaultTextRendererFactory */ public function get titleFactory():Function { return this._titleFactory; } /** * @private */ public function set titleFactory(value:Function):void { if(this._titleFactory == value) { return; } this._titleFactory = value; this.invalidate(INVALIDATION_FLAG_TEXT_RENDERER); } /** * @private */ protected var _disposeItems:Boolean = true; /** * Determines if the leftItems, centerItems, * and rightItems are disposed or not when the header is * disposed. * *

    If you change this value to false, you must dispose * the items manually. Failing to dispose the items may result in a * memory leak.

    * * @default true */ public function get disposeItems():Boolean { return this._disposeItems; } /** * @private */ public function set disposeItems(value:Boolean):void { this._disposeItems = value; } /** * @private */ protected var _leftItems:Vector.; /** * The UI controls that appear in the left region of the header. * *

    In the following example, a back button is displayed on the left * side of the header:

    * * * var backButton:Button = new Button(); * backButton.label = ""Back""; * backButton.styleNameList.add( Button.ALTERNATE_STYLE_NAME_BACK_BUTTON ); * backButton.addEventListener( Event.TRIGGERED, backButton_triggeredHandler ); * header.leftItems = new <DisplayObject>[ backButton ]; * * @default null */ public function get leftItems():Vector. { return this._leftItems; } /** * @private */ public function set leftItems(value:Vector.):void { if(this._leftItems == value) { return; } if(this._leftItems) { for each(var item:DisplayObject in this._leftItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.remove(this.itemStyleName); item.removeEventListener(FeathersEventType.RESIZE, item_resizeHandler); } item.removeFromParent(); } } this._leftItems = value; if(this._leftItems) { for each(item in this._leftItems) { if(item is IFeathersControl) { item.addEventListener(FeathersEventType.RESIZE, item_resizeHandler); } } } this.invalidate(INVALIDATION_FLAG_LEFT_CONTENT); } /** * @private */ protected var _centerItems:Vector.; /** * The UI controls that appear in the center region of the header. If * centerItems is not null, and the * titleAlign property is Header.TITLE_ALIGN_CENTER, * the title text renderer will be hidden. * *

    In the following example, a settings button is displayed in the * center of the header:

    * * * var settingsButton:Button = new Button(); * settingsButton.label = ""Settings""; * settingsButton.addEventListener( Event.TRIGGERED, settingsButton_triggeredHandler ); * header.centerItems = new <DisplayObject>[ settingsButton ]; * * @default null */ public function get centerItems():Vector. { return this._centerItems; } /** * @private */ public function set centerItems(value:Vector.):void { if(this._centerItems == value) { return; } if(this._centerItems) { for each(var item:DisplayObject in this._centerItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.remove(this.itemStyleName); item.removeEventListener(FeathersEventType.RESIZE, item_resizeHandler); } item.removeFromParent(); } } this._centerItems = value; if(this._centerItems) { for each(item in this._centerItems) { if(item is IFeathersControl) { item.addEventListener(FeathersEventType.RESIZE, item_resizeHandler); } } } this.invalidate(INVALIDATION_FLAG_CENTER_CONTENT); } /** * @private */ protected var _rightItems:Vector.; /** * The UI controls that appear in the right region of the header. * *

    In the following example, a settings button is displayed on the * right side of the header:

    * * * var settingsButton:Button = new Button(); * settingsButton.label = ""Settings""; * settingsButton.addEventListener( Event.TRIGGERED, settingsButton_triggeredHandler ); * header.rightItems = new <DisplayObject>[ settingsButton ]; * * @default null */ public function get rightItems():Vector. { return this._rightItems; } /** * @private */ public function set rightItems(value:Vector.):void { if(this._rightItems == value) { return; } if(this._rightItems) { for each(var item:DisplayObject in this._rightItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.remove(this.itemStyleName); item.removeEventListener(FeathersEventType.RESIZE, item_resizeHandler); } item.removeFromParent(); } } this._rightItems = value; if(this._rightItems) { for each(item in this._rightItems) { if(item is IFeathersControl) { item.addEventListener(FeathersEventType.RESIZE, item_resizeHandler); } } } this.invalidate(INVALIDATION_FLAG_RIGHT_CONTENT); } /** * Quickly sets all padding properties to the same value. The * padding getter always returns the value of * paddingTop, but the other padding values may be * different. * *

    In the following example, the header's padding is set to 20 pixels:

    * * * header.padding = 20; * * @default 0 * * @see #paddingTop * @see #paddingRight * @see #paddingBottom * @see #paddingLeft */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The minimum space, in pixels, between the header's top edge and the * header's content. * *

    In the following example, the header's top padding is set to 20 * pixels:

    * * * header.paddingTop = 20; * * @default 0 */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingRight:Number = 0; /** * The minimum space, in pixels, between the header's right edge and the * header's content. * *

    In the following example, the header's right padding is set to 20 * pixels:

    * * * header.paddingRight = 20; * * @default 0 */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The minimum space, in pixels, between the header's bottom edge and * the header's content. * *

    In the following example, the header's bottom padding is set to 20 * pixels:

    * * * header.paddingBottom = 20; * * @default 0 */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The minimum space, in pixels, between the header's left edge and the * header's content. * *

    In the following example, the header's left padding is set to 20 * pixels:

    * * * header.paddingLeft = 20; * * @default 0 */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _gap:Number = 0; /** * Space, in pixels, between items. The same value is used with the * leftItems and rightItems. * *

    Set the titleGap to make the gap on the left and * right of the title use a different value.

    * *

    In the following example, the header's gap between items is set to * 20 pixels:

    * * * header.gap = 20; * * @default 0 * * @see #titleGap * @see #leftItems * @see #rightItems */ public function get gap():Number { return _gap; } /** * @private */ public function set gap(value:Number):void { if(this._gap == value) { return; } this._gap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _titleGap:Number = NaN; /** * Space, in pixels, between the title and the left or right groups of * items. If NaN (the default), the default gap * property is used instead. * *

    In the following example, the header's title gap is set to 20 * pixels:

    * * * header.titleGap = 20; * * @default NaN * * @see #gap */ public function get titleGap():Number { return _titleGap; } /** * @private */ public function set titleGap(value:Number):void { if(this._titleGap == value) { return; } this._titleGap = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _useExtraPaddingForOSStatusBar:Boolean = false; /** * If enabled, the header's top padding will be increased to account for * the height of the OS status bar when the app is rendered under the OS * status bar. The header will not add extra padding to apps that aren't * rendered under the OS status bar. * *

    iOS started rendering apps that aren't full screen under the OS * status bar in version 7.

    * *

    In the following example, the header's padding will account for * the iOS status bar height:

    * * * header.useExtraPaddingForOSStatusBar = true; * * @default false; * * @see #paddingTop */ public function get useExtraPaddingForOSStatusBar():Boolean { return this._useExtraPaddingForOSStatusBar; } /** * @private */ public function set useExtraPaddingForOSStatusBar(value:Boolean):void { if(this._useExtraPaddingForOSStatusBar == value) { return; } this._useExtraPaddingForOSStatusBar = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _verticalAlign:String = VERTICAL_ALIGN_MIDDLE; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * The alignment of the items vertically, on the y-axis. * *

    In the following example, the header's vertical alignment is set * to the middle:

    * * * header.verticalAlign = Header.VERTICAL_ALIGN_MIDDLE; * * @default Header.VERTICAL_ALIGN_MIDDLE * * @see #VERTICAL_ALIGN_TOP * @see #VERTICAL_ALIGN_MIDDLE * @see #VERTICAL_ALIGN_BOTTOM */ public function get verticalAlign():String { return this._verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this._verticalAlign == value) { return; } this._verticalAlign = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var originalBackgroundWidth:Number = NaN; /** * @private */ protected var originalBackgroundHeight:Number = NaN; /** * @private */ protected var currentBackgroundSkin:DisplayObject; /** * @private */ protected var _backgroundSkin:DisplayObject; /** * A display object displayed behind the header's content. * *

    In the following example, the header's background skin is set to * a Quad:

    * * * header.backgroundSkin = new Quad( 10, 10, 0xff0000 ); * * @default null */ public function get backgroundSkin():DisplayObject { return this._backgroundSkin; } /** * @private */ public function set backgroundSkin(value:DisplayObject):void { if(this._backgroundSkin == value) { return; } if(this._backgroundSkin && this._backgroundSkin != this._backgroundDisabledSkin) { this.removeChild(this._backgroundSkin); } this._backgroundSkin = value; if(this._backgroundSkin && this._backgroundSkin.parent != this) { this._backgroundSkin.visible = false; this.addChildAt(this._backgroundSkin, 0); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _backgroundDisabledSkin:DisplayObject; /** * A background to display when the header is disabled. If the property * is null, the value of the backgroundSkin * property will be used instead. * *

    In the following example, the header's disabled background skin is * set to a Quad:

    * * * header.backgroundDisabledSkin = new Quad( 10, 10, 0x999999 ); * * @default null */ public function get backgroundDisabledSkin():DisplayObject { return this._backgroundDisabledSkin; } /** * @private */ public function set backgroundDisabledSkin(value:DisplayObject):void { if(this._backgroundDisabledSkin == value) { return; } if(this._backgroundDisabledSkin && this._backgroundDisabledSkin != this._backgroundSkin) { this.removeChild(this._backgroundDisabledSkin); } this._backgroundDisabledSkin = value; if(this._backgroundDisabledSkin && this._backgroundDisabledSkin.parent != this) { this._backgroundDisabledSkin.visible = false; this.addChildAt(this._backgroundDisabledSkin, 0); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _customTitleStyleName:String; /** * A style name to add to the header's title text renderer * sub-component. Typically used by a theme to provide different styles * to different headers. * *

    In the following example, a custom title style name is passed to * the header:

    * * * header.customTitleStyleName = ""my-custom-header-title""; * *

    In your theme, you can target this sub-component style name to * provide different styles than the default:

    * * * getStyleProviderForClass( BitmapFontTextRenderer ).setFunctionForStyleName( ""my-custom-header-title"", setCustomHeaderTitleStyles ); * * @default null * * @see #DEFAULT_CHILD_STYLE_NAME_TITLE * @see feathers.core.FeathersControl#styleNameList * @see #titleFactory */ public function get customTitleStyleName():String { return this._customTitleStyleName; } /** * @private */ public function set customTitleStyleName(value:String):void { if(this._customTitleStyleName == value) { return; } this._customTitleStyleName = value; this.invalidate(INVALIDATION_FLAG_TEXT_RENDERER); } /** * @private */ protected var _titleProperties:PropertyProxy; /** * An object that stores properties for the header's title text renderer * sub-component, and the properties will be passed down to the text * renderer when the header validates. The available properties * depend on which ITextRenderer implementation is returned * by textRendererFactory. Refer to * feathers.core.ITextRenderer * for a list of available text renderer implementations. * *

    In the following example, some properties are set for the header's * title text renderer (this example assumes that the title text renderer * is a BitmapFontTextRenderer):

    * * * header.titleProperties.textFormat = new BitmapFontTextFormat( bitmapFont ); * header.titleProperties.wordWrap = true; * *

    If the subcomponent has its own subcomponents, their properties * can be set too, using attribute @ notation. For example, * to set the skin on the thumb which is in a SimpleScrollBar, * which is in a List, you can use the following syntax:

    *
    list.verticalScrollBarProperties.@thumbProperties.defaultSkin = new Image(texture);
    * *

    Setting properties in a titleFactory function instead * of using titleProperties will result in better * performance.

    * * @default null * * @see #titleFactory * @see feathers.core.ITextRenderer */ public function get titleProperties():Object { if(!this._titleProperties) { this._titleProperties = new PropertyProxy(titleProperties_onChange); } return this._titleProperties; } /** * @private */ public function set titleProperties(value:Object):void { if(this._titleProperties == value) { return; } if(value && !(value is PropertyProxy)) { value = PropertyProxy.fromObject(value); } if(this._titleProperties) { this._titleProperties.removeOnChangeCallback(titleProperties_onChange); } this._titleProperties = PropertyProxy(value); if(this._titleProperties) { this._titleProperties.addOnChangeCallback(titleProperties_onChange); } this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected var _titleAlign:String = TITLE_ALIGN_CENTER; [Inspectable(type=""String"",enumeration=""center,preferLeft,preferRight"")] /** * The preferred position of the title. If leftItems and/or * rightItems are not null, the title may be * forced to the center even if the preferred position is on the left or * right. If centerItems is not null, and the * title is centered, the title will be hidden. * *

    In the following example, the header's title aligment is set to * prefer the left side:

    * * * header.titleAlign = Header.TITLE_ALIGN_PREFER_LEFT; * * @default Header.TITLE_ALIGN_CENTER * * @see #TITLE_ALIGN_CENTER * @see #TITLE_ALIGN_PREFER_LEFT * @see #TITLE_ALIGN_PREFER_RIGHT */ public function get titleAlign():String { return this._titleAlign; } /** * @private */ public function set titleAlign(value:String):void { if(this._titleAlign == value) { return; } this._titleAlign = value; this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ override public function dispose():void { if(this._disposeItems) { for each(var item:DisplayObject in this._leftItems) { item.dispose(); } for each(item in this._centerItems) { item.dispose(); } for each(item in this._rightItems) { item.dispose(); } } this.leftItems = null; this.rightItems = null; this.centerItems = null; super.dispose(); } /** * @private */ override protected function initialize():void { if(!this._layout) { this._layout = new HorizontalLayout(); this._layout.useVirtualLayout = false; this._layout.verticalAlign = HorizontalLayout.VERTICAL_ALIGN_MIDDLE; } } /** * @private */ override protected function draw():void { var sizeInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_SIZE); var dataInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_DATA); var stylesInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STYLES); var stateInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_STATE); var leftContentInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_LEFT_CONTENT); var rightContentInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_RIGHT_CONTENT); var centerContentInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_CENTER_CONTENT); var textRendererInvalid:Boolean = this.isInvalid(INVALIDATION_FLAG_TEXT_RENDERER); if(textRendererInvalid) { this.createTitle(); } if(textRendererInvalid || dataInvalid) { this.titleTextRenderer.text = this._title; } if(stateInvalid || stylesInvalid) { this.refreshBackground(); } if(textRendererInvalid || stylesInvalid || sizeInvalid) { this.refreshLayout(); } if(textRendererInvalid || stylesInvalid) { this.refreshTitleStyles(); } if(leftContentInvalid) { if(this._leftItems) { for each(var item:DisplayObject in this._leftItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.add(this.itemStyleName); } this.addChild(item); } } } if(rightContentInvalid) { if(this._rightItems) { for each(item in this._rightItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.add(this.itemStyleName); } this.addChild(item); } } } if(centerContentInvalid) { if(this._centerItems) { for each(item in this._centerItems) { if(item is IFeathersControl) { IFeathersControl(item).styleNameList.add(this.itemStyleName); } this.addChild(item); } } } if(stateInvalid || textRendererInvalid) { this.refreshEnabled(); } sizeInvalid = this.autoSizeIfNeeded() || sizeInvalid; if(sizeInvalid || stylesInvalid) { this.layoutBackground(); } if(sizeInvalid || leftContentInvalid || rightContentInvalid || centerContentInvalid || stylesInvalid) { this.leftItemsWidth = 0; this.rightItemsWidth = 0; if(this._leftItems) { this.layoutLeftItems(); } if(this._rightItems) { this.layoutRightItems(); } if(this._centerItems) { this.layoutCenterItems(); } } if(textRendererInvalid || sizeInvalid || stylesInvalid || dataInvalid || leftContentInvalid || rightContentInvalid || centerContentInvalid) { this.layoutTitle(); } } /** * If the component's dimensions have not been set explicitly, it will * measure its content and determine an ideal size for itself. If the * explicitWidth or explicitHeight member * variables are set, those value will be used without additional * measurement. If one is set, but not the other, the dimension with the * explicit value will not be measured, but the other non-explicit * dimension will still need measurement. * *

    Calls setSizeInternal() to set up the * actualWidth and actualHeight member * variables used for layout.

    * *

    Meant for internal use, and subclasses may override this function * with a custom implementation.

    */ protected function autoSizeIfNeeded():Boolean { var needsWidth:Boolean = this.explicitWidth !== this.explicitWidth; //isNaN var needsHeight:Boolean = this.explicitHeight !== this.explicitHeight; //isNaN if(!needsWidth && !needsHeight) { return false; } var newWidth:Number = needsWidth ? (this._paddingLeft + this._paddingRight) : this.explicitWidth; var newHeight:Number = needsHeight ? 0 : this.explicitHeight; var totalItemWidth:Number = 0; var leftItemCount:int = this._leftItems ? this._leftItems.length : 0; for(var i:int = 0; i < leftItemCount; i++) { var item:DisplayObject = this._leftItems[i]; if(item is IValidating) { IValidating(item).validate(); } var itemWidth:Number = item.width; if(needsWidth && itemWidth === itemWidth) //!isNaN { totalItemWidth += itemWidth; if(i > 0) { totalItemWidth += this._gap; } } var itemHeight:Number = item.height; if(needsHeight && itemHeight === itemHeight && //!isNaN itemHeight > newHeight) { newHeight = itemHeight; } } var centerItemCount:int = this._centerItems ? this._centerItems.length : 0; for(i = 0; i < centerItemCount; i++) { item = this._centerItems[i]; if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width; if(needsWidth && itemWidth === itemWidth) //!isNaN { totalItemWidth += itemWidth; if(i > 0) { totalItemWidth += this._gap; } } itemHeight = item.height; if(needsHeight && itemHeight === itemHeight && //!isNaN itemHeight > newHeight) { newHeight = itemHeight; } } var rightItemCount:int = this._rightItems ? this._rightItems.length : 0; for(i = 0; i < rightItemCount; i++) { item = this._rightItems[i]; if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width if(needsWidth && itemWidth === itemWidth) //!isNaN { totalItemWidth += itemWidth; if(i > 0) { totalItemWidth += this._gap; } } itemHeight = item.height; if(needsHeight && itemHeight === itemHeight && //!isNaN itemHeight > newHeight) { newHeight = itemHeight; } } newWidth += totalItemWidth; if(this._title && !(this._titleAlign == TITLE_ALIGN_CENTER && this._centerItems)) { var calculatedTitleGap:Number = this._titleGap; if(calculatedTitleGap !== calculatedTitleGap) //isNaN { calculatedTitleGap = this._gap; } newWidth += 2 * calculatedTitleGap; var maxTitleWidth:Number = (needsWidth ? this._maxWidth : this.explicitWidth) - totalItemWidth; if(leftItemCount > 0) { maxTitleWidth -= calculatedTitleGap; } if(centerItemCount > 0) { maxTitleWidth -= calculatedTitleGap; } if(rightItemCount > 0) { maxTitleWidth -= calculatedTitleGap; } this.titleTextRenderer.maxWidth = maxTitleWidth; this.titleTextRenderer.measureText(HELPER_POINT); var measuredTitleWidth:Number = HELPER_POINT.x; var measuredTitleHeight:Number = HELPER_POINT.y; if(needsWidth && measuredTitleWidth === measuredTitleWidth) //!isNaN { newWidth += measuredTitleWidth; if(leftItemCount > 0) { newWidth += calculatedTitleGap; } if(rightItemCount > 0) { newWidth += calculatedTitleGap; } } if(needsHeight && measuredTitleHeight === measuredTitleHeight && //!isNaN measuredTitleHeight > newHeight) { newHeight = measuredTitleHeight; } } if(needsHeight) { newHeight += this._paddingTop + this._paddingBottom; var extraPaddingTop:Number = this.calculateExtraOSStatusBarPadding(); if(extraPaddingTop > 0) { //account for the minimum height before adding the padding if(newHeight < this._minHeight) { newHeight = this._minHeight; } newHeight += extraPaddingTop; } } if(needsWidth && this.originalBackgroundWidth === this.originalBackgroundWidth && //!isNaN this.originalBackgroundWidth > newWidth) { newWidth = this.originalBackgroundWidth; } if(needsHeight && this.originalBackgroundHeight === this.originalBackgroundHeight && //!isNaN this.originalBackgroundHeight > newHeight) { newHeight = this.originalBackgroundHeight; } return this.setSizeInternal(newWidth, newHeight, false); } /** * Creates and adds the titleTextRenderer sub-component and * removes the old instance, if one exists. * *

    Meant for internal use, and subclasses may override this function * with a custom implementation.

    * * @see #title * @see #titleTextRenderer * @see #titleFactory */ protected function createTitle():void { if(this.titleTextRenderer) { this.removeChild(DisplayObject(this.titleTextRenderer), true); this.titleTextRenderer = null; } var factory:Function = this._titleFactory != null ? this._titleFactory : FeathersControl.defaultTextRendererFactory; this.titleTextRenderer = ITextRenderer(factory()); var uiTitleRenderer:IFeathersControl = IFeathersControl(this.titleTextRenderer); var titleStyleName:String = this._customTitleStyleName != null ? this._customTitleStyleName : this.titleStyleName; uiTitleRenderer.styleNameList.add(titleStyleName); this.addChild(DisplayObject(uiTitleRenderer)); } /** * @private */ protected function refreshBackground():void { this.currentBackgroundSkin = this._backgroundSkin; if(!this._isEnabled && this._backgroundDisabledSkin) { if(this._backgroundSkin) { this._backgroundSkin.visible = false; } this.currentBackgroundSkin = this._backgroundDisabledSkin; } else if(this._backgroundDisabledSkin) { this._backgroundDisabledSkin.visible = false; } if(this.currentBackgroundSkin) { this.currentBackgroundSkin.visible = true; if(this.originalBackgroundWidth !== this.originalBackgroundWidth) //isNaN { this.originalBackgroundWidth = this.currentBackgroundSkin.width; } if(this.originalBackgroundHeight !== this.originalBackgroundHeight) //isNaN { this.originalBackgroundHeight = this.currentBackgroundSkin.height; } } } /** * @private */ protected function refreshLayout():void { this._layout.gap = this._gap; this._layout.paddingTop = this._paddingTop + this.calculateExtraOSStatusBarPadding(); this._layout.paddingBottom = this._paddingBottom; this._layout.verticalAlign = this._verticalAlign; } /** * @private */ protected function refreshEnabled():void { this.titleTextRenderer.isEnabled = this._isEnabled; } /** * @private */ protected function refreshTitleStyles():void { for(var propertyName:String in this._titleProperties) { var propertyValue:Object = this._titleProperties[propertyName]; this.titleTextRenderer[propertyName] = propertyValue; } } /** * @private */ protected function calculateExtraOSStatusBarPadding():Number { if(!this._useExtraPaddingForOSStatusBar) { return 0; } //first, we check if it's iOS or not. at this time, we only need to //use extra padding on iOS. android and others are fine. var os:String = Capabilities.os; if(os.indexOf(IOS_NAME_PREFIX) != 0 || parseInt(os.substr(IOS_NAME_PREFIX.length, 1), 10) < STATUS_BAR_MIN_IOS_VERSION) { return 0; } //next, we check if the app is full screen or not. if it is full //screen, then the status bar isn't visible, and we don't need the //extra padding. var nativeStage:Stage = Starling.current.nativeStage; if(nativeStage.displayState != StageDisplayState.NORMAL) { return 0; } if(DeviceCapabilities.dpi >= IOS_RETINA_MINIMUM_DPI) { //retina devices have more padding than non-retina //we also need to account for contentScaleFactor return IOS_RETINA_STATUS_BAR_HEIGHT / Starling.current.contentScaleFactor; } return IOS_NON_RETINA_STATUS_BAR_HEIGHT / Starling.current.contentScaleFactor; } /** * @private */ protected function layoutBackground():void { if(!this.currentBackgroundSkin) { return; } this.currentBackgroundSkin.width = this.actualWidth; this.currentBackgroundSkin.height = this.actualHeight; } /** * @private */ protected function layoutLeftItems():void { for each(var item:DisplayObject in this._leftItems) { if(item is IValidating) { IValidating(item).validate(); } } HELPER_BOUNDS.x = HELPER_BOUNDS.y = 0; HELPER_BOUNDS.scrollX = HELPER_BOUNDS.scrollY = 0; HELPER_BOUNDS.explicitWidth = this.actualWidth; HELPER_BOUNDS.explicitHeight = this.actualHeight; this._layout.horizontalAlign = HorizontalLayout.HORIZONTAL_ALIGN_LEFT; this._layout.paddingRight = 0; this._layout.paddingLeft = this._paddingLeft; this._layout.layout(this._leftItems, HELPER_BOUNDS, HELPER_LAYOUT_RESULT); this.leftItemsWidth = HELPER_LAYOUT_RESULT.contentWidth; if(this.leftItemsWidth !== this.leftItemsWidth) //isNaN { this.leftItemsWidth = 0; } } /** * @private */ protected function layoutRightItems():void { for each(var item:DisplayObject in this._rightItems) { if(item is IValidating) { IValidating(item).validate(); } } HELPER_BOUNDS.x = HELPER_BOUNDS.y = 0; HELPER_BOUNDS.scrollX = HELPER_BOUNDS.scrollY = 0; HELPER_BOUNDS.explicitWidth = this.actualWidth; HELPER_BOUNDS.explicitHeight = this.actualHeight; this._layout.horizontalAlign = HorizontalLayout.HORIZONTAL_ALIGN_RIGHT; this._layout.paddingRight = this._paddingRight; this._layout.paddingLeft = 0; this._layout.layout(this._rightItems, HELPER_BOUNDS, HELPER_LAYOUT_RESULT); this.rightItemsWidth = HELPER_LAYOUT_RESULT.contentWidth; if(this.rightItemsWidth !== this.rightItemsWidth) //isNaN { this.rightItemsWidth = 0; } } /** * @private */ protected function layoutCenterItems():void { for each(var item:DisplayObject in this._centerItems) { if(item is IValidating) { IValidating(item).validate(); } } HELPER_BOUNDS.x = HELPER_BOUNDS.y = 0; HELPER_BOUNDS.scrollX = HELPER_BOUNDS.scrollY = 0; HELPER_BOUNDS.explicitWidth = this.actualWidth; HELPER_BOUNDS.explicitHeight = this.actualHeight; this._layout.horizontalAlign = HorizontalLayout.HORIZONTAL_ALIGN_CENTER; this._layout.paddingRight = this._paddingRight; this._layout.paddingLeft = this._paddingLeft; this._layout.layout(this._centerItems, HELPER_BOUNDS, HELPER_LAYOUT_RESULT); } /** * @private */ protected function layoutTitle():void { if((this._titleAlign == TITLE_ALIGN_CENTER && this._centerItems) || this._title.length == 0) { this.titleTextRenderer.visible = false; return; } this.titleTextRenderer.visible = true; var calculatedTitleGap:Number = this._titleGap; if(calculatedTitleGap !== calculatedTitleGap) //isNaN { calculatedTitleGap = this._gap; } //left and right offsets already include padding var leftOffset:Number = (this._leftItems && this._leftItems.length > 0) ? (this.leftItemsWidth + calculatedTitleGap) : 0; var rightOffset:Number = (this._rightItems && this._rightItems.length > 0) ? (this.rightItemsWidth + calculatedTitleGap) : 0; if(this._titleAlign == TITLE_ALIGN_PREFER_LEFT && (!this._leftItems || this._leftItems.length == 0)) { this.titleTextRenderer.maxWidth = this.actualWidth - this._paddingLeft - rightOffset; this.titleTextRenderer.validate(); this.titleTextRenderer.x = this._paddingLeft; } else if(this._titleAlign == TITLE_ALIGN_PREFER_RIGHT && (!this._rightItems || this._rightItems.length == 0)) { this.titleTextRenderer.maxWidth = this.actualWidth - this._paddingRight - leftOffset; this.titleTextRenderer.validate(); this.titleTextRenderer.x = this.actualWidth - this._paddingRight - this.titleTextRenderer.width; } else { var actualWidthMinusPadding:Number = this.actualWidth - this._paddingLeft - this._paddingRight; var actualWidthMinusOffsets:Number = this.actualWidth - leftOffset - rightOffset; this.titleTextRenderer.maxWidth = actualWidthMinusOffsets; this.titleTextRenderer.validate(); var idealTitlePosition:Number = this._paddingLeft + (actualWidthMinusPadding - this.titleTextRenderer.width) / 2; if(leftOffset > idealTitlePosition || (idealTitlePosition + this.titleTextRenderer.width) > (this.actualWidth - rightOffset)) { this.titleTextRenderer.x = leftOffset + (actualWidthMinusOffsets - this.titleTextRenderer.width) / 2; } else { this.titleTextRenderer.x = idealTitlePosition; } } var paddingTop:Number = this._paddingTop + this.calculateExtraOSStatusBarPadding(); if(this._verticalAlign == VERTICAL_ALIGN_TOP) { this.titleTextRenderer.y = paddingTop; } else if(this._verticalAlign == VERTICAL_ALIGN_BOTTOM) { this.titleTextRenderer.y = this.actualHeight - this._paddingBottom - this.titleTextRenderer.height; } else { this.titleTextRenderer.y = paddingTop + (this.actualHeight - paddingTop - this._paddingBottom - this.titleTextRenderer.height) / 2; } } /** * @private */ protected function header_addedToStageHandler(event:Event):void { Starling.current.nativeStage.addEventListener(""fullScreen"", nativeStage_fullScreenHandler); } /** * @private */ protected function header_removedFromStageHandler(event:Event):void { Starling.current.nativeStage.removeEventListener(""fullScreen"", nativeStage_fullScreenHandler); } /** * @private */ protected function nativeStage_fullScreenHandler(event:FullScreenEvent):void { this.invalidate(INVALIDATION_FLAG_SIZE); } /** * @private */ protected function titleProperties_onChange(proxy:PropertyProxy, propertyName:String):void { this.invalidate(INVALIDATION_FLAG_STYLES); } /** * @private */ protected function item_resizeHandler(event:Event):void { this.invalidate(INVALIDATION_FLAG_SIZE); } } } ",12512,True,2644.074139672179,median "//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2003-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package mx.effects { import flash.events.Event; import flash.events.EventDispatcher; import mx.core.FlexVersion; import mx.core.IFlexDisplayObject; import mx.core.mx_internal; import mx.effects.effectClasses.AddRemoveEffectTargetFilter; import mx.effects.effectClasses.HideShowEffectTargetFilter; import mx.effects.effectClasses.PropertyChanges; import mx.events.EffectEvent; import mx.managers.LayoutManager; import mx.styles.IStyleClient; import mx.utils.NameUtil; use namespace mx_internal; /** * Dispatched when one of the effect's instances finishes playing, * either when the instance finishes playing or when the effect * is interrupted by a call to the end() method. * * @eventType mx.events.EffectEvent.EFFECT_END * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""effectEnd"", type=""mx.events.EffectEvent"")] /** * Dispatched when the effect has been stopped, * which only occurs when the effect is * interrupted by a call to the stop() method. * The EFFECT_END event is also dispatched to indicate that * the effect has ended. This extra event is sent first, as an * indicator to listeners that the effect did not reach its * end state. * * @eventType mx.events.EffectEvent.EFFECT_STOP * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""effectStop"", type=""mx.events.EffectEvent"")] /** * Dispatched when the effect starts playing. * * @eventType mx.events.EffectEvent.EFFECT_START * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""effectStart"", type=""mx.events.EffectEvent"")] /** * The Effect class is an abstract base class that defines the basic * functionality of all Flex effects. * The Effect class defines the base factory class for all effects. * The EffectInstance class defines the base class for all effect * instance subclasses. * *

    You do not create an instance of the Effect class itself * in an application. * Instead, you create an instance of one of the subclasses, * such as Fade or WipeLeft.

    * * @mxml * *

    The Effect class defines the following properties, * which all of its subclasses inherit:

    * *
     *  <mx:tagname
     *    Properties
     *    customFilter=""""
     *    duration=""500""
     *    filter=""""
     *    hideFocusRing=""false""
     *    perElementOffset=""0""
     *    repeatCount=""1""
     *    repeatDelay=""0""
     *    startDelay=""0""
     *    suspendBackgroundProcessing=""false|true""
     *    target=""effect target""
     *    targets=""array of effect targets""
     *     
     *    Events
     *    effectEnd=""No default""
     *    efectStart=""No default""
     *  />
     *  
    * * @see mx.effects.EffectInstance * * @includeExample examples/SimpleEffectExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class Effect extends EventDispatcher implements IEffect { include ""../core/Version.as""; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- /** * @private */ private static function mergeArrays(a1:Array, a2:Array):Array { if (a2) { for (var i2:int = 0; i2 < a2.length; i2++) { var addIt:Boolean = true; for (var i1:int = 0; i1 < a1.length; i1++) { if (a1[i1] == a2[i2]) { addIt = false; break; } } if (addIt) a1.push(a2[i2]); } } return a1; } /** * @private */ private static function stripUnchangedValues(propChanges:Array):Array { // Go through and remove any before/after values that are the same. for (var i:int = 0; i < propChanges.length; i++) { if (propChanges[i].stripUnchangedValues == false) continue; for (var prop:Object in propChanges[i].start) { if ((propChanges[i].start[prop] == propChanges[i].end[prop]) || (typeof(propChanges[i].start[prop]) == ""number"" && typeof(propChanges[i].end[prop])== ""number"" && isNaN(propChanges[i].start[prop]) && isNaN(propChanges[i].end[prop]))) { delete propChanges[i].start[prop]; delete propChanges[i].end[prop]; } } } return propChanges; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * *

    Starting an effect is usually a three-step process:

    * *
      *
    • Create an instance of the effect object * with the new operator.
    • *
    • Set properties on the effect object, * such as duration.
    • *
    • Call the play() method * or assign the effect to a trigger.
    • *
    * * @param target The Object to animate with this effect. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function Effect(target:Object = null) { super(); this.target = target; } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- // Transitions will force the values animated by this effect to get set to // their final values, as specified in the end state, when the effect finishes. // This flag is set to true when the effect is being played by a transition, // but applying the values is still gated by the value of the // applyTransitionEndProperties flag, which is set on a per-Effect basis. mx_internal var applyEndValuesWhenDone:Boolean = false; // This property tracks whether the effect is playing in interruption mode. // Normally, effects pick up starting values (when not provided explicitly) // from the current values of the target objects. But when playing in interruption // mode, the effect should get its starting values from the propertyChanges // array instead. private var _transitionInterruption:Boolean = false; mx_internal function get transitionInterruption():Boolean { return _transitionInterruption; } mx_internal function set transitionInterruption(value:Boolean):void { _transitionInterruption = value; } // This is new behavior for the Flex4 effects; previously, we would not // set the end-state values automatically. Because of this switch, the // default value is hinged on a compatibility check, so that applications // can choose to have the older behavior instead. /** * This flag controls whether the effect, when run in a transition, * automatically applies the property values according to the end * state, as opposed to leaving values as set by the effect itself. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var applyTransitionEndProperties:Boolean = (FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0) ? false : true; /** * @private */ private var _instances:Array /* of EffectInstance */ = []; /** * @private */ private var _callValidateNow:Boolean = false; /** * @private */ private var isPaused:Boolean = false; /** * @private */ mx_internal var filterObject:EffectTargetFilter; /** * @private * Used in applyValueToTarget() */ mx_internal var applyActualDimensions:Boolean = true; /** * @private * Holds the init object passed in by the Transition. */ mx_internal var propertyChangesArray:Array; /** * @private * Track the property set in the play() function */ mx_internal var playReversed:Boolean; private var effectStopped:Boolean; /** * @private * Pointer back to the CompositeEffect that created this instance. * Value is null if we are not the child of a CompositeEffect */ mx_internal var parentCompositeEffect:Effect; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // className //---------------------------------- /** * @copy mx.effects.IEffect#className * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get className():String { return NameUtil.getUnqualifiedClassName(this); } //---------------------------------- // customFilter //---------------------------------- /** * @private * Storage for the customFilter property. */ private var _customFilter:EffectTargetFilter; /** * @copy mx.effects.IEffect#customFilter * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get customFilter():EffectTargetFilter { return _customFilter; } /** * @private */ public function set customFilter(value:EffectTargetFilter):void { _customFilter = value; filterObject = value; } //---------------------------------- // duration //---------------------------------- /** * @private * Storage for the duration property. */ private var _duration:Number = 500; /** * @private */ mx_internal var durationExplicitlySet:Boolean = false; [Inspectable(category=""General"", defaultValue=""500"", minValue=""0.0"")] /** * @copy mx.effects.IEffect#duration * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get duration():Number { if (!durationExplicitlySet && parentCompositeEffect) { return parentCompositeEffect.duration; } else { return _duration; } } /** * @private */ public function set duration(value:Number):void { durationExplicitlySet = true; _duration = value; } //---------------------------------- // effectTargetHost //---------------------------------- /** * @private * Storage for the effectTargetHost property. */ private var _effectTargetHost:IEffectTargetHost; /** * @copy mx.effects.IEffect#effectTargetHost * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get effectTargetHost():IEffectTargetHost { return _effectTargetHost; } /** * @private */ public function set effectTargetHost(value:IEffectTargetHost):void { _effectTargetHost = value; } //---------------------------------- // endValuesCaptured //---------------------------------- /** * A flag containing true if the end values * of an effect have already been determined, * or false if they should be acquired from the * current properties of the effect targets when the effect runs. * This property is required by data effects because the sequence * of setting up the data effects, such as DefaultListEffect * and DefaultTileListEffect, is more complicated than for * normal effects. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var endValuesCaptured:Boolean = false; //---------------------------------- // filter //---------------------------------- /** * @private * Storage for the filter property. */ private var _filter:String; [Inspectable(category=""General"", enumeration=""add,remove,show,hide,move,resize,addItem,removeItem,replacedItem,replacementItem,none"", defaultValue=""none"")] /** * @copy mx.effects.IEffect#filter * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get filter():String { return _filter; } /** * @private */ public function set filter(value:String):void { if (!customFilter) { _filter = value; switch (value) { case ""add"": case ""remove"": { filterObject = new AddRemoveEffectTargetFilter(); AddRemoveEffectTargetFilter(filterObject).add = (value == ""add""); break; } case ""hide"": case ""show"": { filterObject = new HideShowEffectTargetFilter(); HideShowEffectTargetFilter(filterObject).show = (value == ""show""); break; } case ""move"": { filterObject = new EffectTargetFilter(); filterObject.filterProperties = [ ""x"", ""y"" ]; break; } case ""resize"": { filterObject = new EffectTargetFilter(); filterObject.filterProperties = [ ""width"", ""height"" ]; break; } case ""addItem"": { filterObject = new EffectTargetFilter(); filterObject.requiredSemantics = {added:true}; break; } case ""removeItem"": { filterObject = new EffectTargetFilter(); filterObject.requiredSemantics = {removed:true}; break; } case ""replacedItem"": { filterObject = new EffectTargetFilter(); filterObject.requiredSemantics = {replaced:true}; break; } case ""replacementItem"": { filterObject = new EffectTargetFilter(); filterObject.requiredSemantics = {replacement:true}; break; } default: { filterObject = null; break; } } } } //---------------------------------- // hideFocusRing //---------------------------------- /** * @private * Storage for the hideFocusRing property. */ private var _hideFocusRing:Boolean = false; /** * @copy mx.effects.IEffect#hideFocusRing * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get hideFocusRing():Boolean { return _hideFocusRing; } /** * @private */ public function set hideFocusRing(value:Boolean):void { _hideFocusRing = value; } //---------------------------------- // instanceClass //---------------------------------- /** * An object of type Class that specifies the effect * instance class class for this effect class. * *

    All subclasses of the Effect class must set this property * in their constructor.

    * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var instanceClass:Class = IEffectInstance; //---------------------------------- // isPlaying //---------------------------------- /** * @copy mx.effects.IEffect#isPlaying * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get isPlaying():Boolean { return _instances && _instances.length > 0; } //---------------------------------- // perElementOffset //---------------------------------- /** * @private * Storage for the perElementOffset property. */ private var _perElementOffset:Number = 0; [Inspectable(defaultValue=""0"", category=""General"", verbose=""0"", minValue=""0.0"")] /** * @copy mx.effects.IEffect#perElementOffset * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get perElementOffset():Number { return _perElementOffset; } /** * @private */ public function set perElementOffset(value:Number):void { _perElementOffset = value; } //---------------------------------- // relevantProperties //---------------------------------- /** * @private * Storage for the relevantProperties property. */ private var _relevantProperties:Array /* of String */; /** * @copy mx.effects.IEffect#relevantProperties * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get relevantProperties():Array /* of String */ { if (_relevantProperties) return _relevantProperties; else return getAffectedProperties(); } /** * @private */ public function set relevantProperties(value:Array /* of String */):void { _relevantProperties = value; } //---------------------------------- // relevantStyles //---------------------------------- /** * @private * Storage for the relevantStyles property. */ private var _relevantStyles:Array /* of String */ = []; /** * @copy mx.effects.IEffect#relevantStyles * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get relevantStyles():Array /* of String */ { return _relevantStyles; } /** * @private */ public function set relevantStyles(value:Array /* of String */):void { _relevantStyles = value; } //---------------------------------- // repeatCount //---------------------------------- [Inspectable(category=""General"", defaultValue=""1"", minValue=""0"")] /** * Number of times to repeat the effect. * Possible values are any integer greater than or equal to 0. * A value of 1 means to play the effect once. * A value of 0 means to play the effect indefinitely * until stopped by a call to the end() method. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var repeatCount:int = 1; //---------------------------------- // repeatDelay //---------------------------------- [Inspectable(category=""General"", defaultValue=""0"", minValue=""0"")] /** * Amount of time, in milliseconds, to wait before repeating the effect. * Possible values are any integer greater than or equal to 0. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var repeatDelay:int = 0; //---------------------------------- // startDelay //---------------------------------- [Inspectable(category=""General"", defaultValue=""0"", minValue=""0"")] /** * Amount of time, in milliseconds, to wait before starting the effect. * Possible values are any int greater than or equal to 0. * If the effect is repeated by using the repeatCount * property, the startDelay is only applied * to the first time the effect is played. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var startDelay:int = 0; //---------------------------------- // suspendBackgroundProcessing //---------------------------------- /** * If true, blocks all background processing * while the effect is playing. * Background processing includes measurement, layout, and * processing responses that have arrived from the server. * The default value is false. * *

    You are encouraged to set this property to * true in most cases, because it improves * the performance of the application. * However, the property should be set to false * if either of the following is true:

    *
      *
    • User input can arrive while the effect is playing, * and the application must respond to the user input * before the effect finishes playing.
    • *
    • A response can arrive from the server while the effect * is playing, and the application must process the response * while the effect is still playing.
    • *
    * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var suspendBackgroundProcessing:Boolean = false; //---------------------------------- // target //---------------------------------- /** * @copy mx.effects.IEffect#target * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get target():Object { if (_targets.length > 0) return _targets[0]; else return null; } /** * @private */ public function set target(value:Object):void { _targets.splice(0); if (value) _targets[0] = value; } //---------------------------------- // targets //---------------------------------- /** * @private * Storage for the targets property. */ private var _targets:Array = []; [Inspectable(arrayType=""Object"")] [ArrayElementType(""Object"")] /** * @copy mx.effects.IEffect#targets * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get targets():Array { return _targets; } /** * @private */ public function set targets(value:Array):void { // Strip out null values. // Binding will trigger again when the null targets are created. var n:int = value.length; for (var i:int = n - 1; i >= 0; i--) { if (value[i] == null) value.splice(i,1); } _targets = value; } //---------------------------------- // triggerEvent //---------------------------------- /** * @private * Storage for the triggerEvent property. */ private var _triggerEvent:Event; /** * @copy mx.effects.IEffect#triggerEvent * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get triggerEvent():Event { return _triggerEvent; } /** * @private */ public function set triggerEvent(value:Event):void { _triggerEvent = value; } //---------------------------------- // playheadTime //---------------------------------- /** * @private * Backing storage for the playheadTime property. Note that this * value is just a backup, used if the effect is not currently running. * A running effect will query its effect instance for the value * instead. */ private var _playheadTime:Number = 0; [Inspectable(minValue=""0.0"")] /** * Current time position of the effect. * This property has a value between 0 and the total duration, * which includes the Effect's startDelay, * repeatCount, and repeatDelay. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get playheadTime():Number { for (var i:int = 0; i < _instances.length; i++) { if (_instances[i]) return IEffectInstance(_instances[i]).playheadTime; } // Effect isn't running: return the cached value return _playheadTime; } public function set playheadTime(value:Number):void { // If the effect is not yet playing, it should still be possible // to seek into it. playing and then pausing it provides that // capability // TODO (chaase): Need better overall mechanism to seek into a // non-playing effect. The internals of seeking in Animation // are complicated and don't end up giving us the behavior we // want, especially for successive seeks. var started:Boolean = false; if (_instances.length == 0) { play(); started = true; } for (var i:int = 0; i < _instances.length; i++) { if (_instances[i]) EffectInstance(_instances[i]).playheadTime = value; } if (started) pause(); _playheadTime = value; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @copy mx.effects.IEffect#getAffectedProperties() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function getAffectedProperties():Array /* of String */ { // Every subclass should override this method. return []; } /** * @copy mx.effects.IEffect#createInstances() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function createInstances(targets:Array = null):Array /* of EffectInstance */ { if (!targets) targets = this.targets; var newInstances:Array = []; // Multiple target support var n:int = targets.length; var offsetDelay:Number = 0; for (var i:int = 0; i < n; i++) { var newInstance:IEffectInstance = createInstance(targets[i]); if (newInstance) { newInstance.startDelay += offsetDelay; offsetDelay += perElementOffset; newInstances.push(newInstance); } } triggerEvent = null; return newInstances; } /** * @copy mx.effects.IEffect#createInstance() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function createInstance(target:Object = null):IEffectInstance { if (!target) target = this.target; var newInstance:IEffectInstance = null; var props:PropertyChanges = null; var create:Boolean = true; var setPropsArray:Boolean = false; if (propertyChangesArray) { setPropsArray = true; create = filterInstance(propertyChangesArray, target); } if (create) { newInstance = IEffectInstance(new instanceClass(target)); initInstance(newInstance); if (setPropsArray) { var n:int = propertyChangesArray.length; for (var i:int = 0; i < n; i++) { if (propertyChangesArray[i].target == target) { newInstance.propertyChanges = propertyChangesArray[i]; } } } EventDispatcher(newInstance).addEventListener(EffectEvent.EFFECT_START, effectStartHandler); EventDispatcher(newInstance).addEventListener(EffectEvent.EFFECT_STOP, effectStopHandler); EventDispatcher(newInstance).addEventListener(EffectEvent.EFFECT_END, effectEndHandler); _instances.push(newInstance); if (triggerEvent) newInstance.initEffect(triggerEvent); } return newInstance; } /** * Copies properties of the effect to the effect instance. * *

    Flex calls this method from the Effect.createInstance() * method; you do not have to call it yourself.

    * *

    When you create a custom effect, override this method to * copy properties from the Effect class to the effect instance class. * In your override, call super.initInstance().

    * * @param EffectInstance The effect instance to initialize. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function initInstance(instance:IEffectInstance):void { instance.duration = duration; Object(instance).durationExplicitlySet = durationExplicitlySet; instance.effect = this; instance.effectTargetHost = effectTargetHost; instance.hideFocusRing = hideFocusRing; instance.repeatCount = repeatCount; instance.repeatDelay = repeatDelay; instance.startDelay = startDelay; instance.suspendBackgroundProcessing = suspendBackgroundProcessing; } /** * @copy mx.effects.IEffect#deleteInstance() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function deleteInstance(instance:IEffectInstance):void { EventDispatcher(instance).removeEventListener( EffectEvent.EFFECT_START, effectStartHandler); EventDispatcher(instance).removeEventListener( EffectEvent.EFFECT_STOP, effectStopHandler); EventDispatcher(instance).removeEventListener( EffectEvent.EFFECT_END, effectEndHandler); var n:int = _instances.length; for (var i:int = 0; i < n; i++) { if (_instances[i] === instance) _instances.splice(i, 1); } } /** * @copy mx.effects.IEffect#play() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function play(targets:Array = null, playReversedFromEnd:Boolean = false): Array /* of EffectInstance */ { effectStopped = false; isPaused = false; playReversed = playReversedFromEnd; // If we have a propertyChangesArray, capture the current values // if they haven't been captured already, strip out any unchanged // values, then apply the start values. if (targets == null && propertyChangesArray != null) { if (_callValidateNow) LayoutManager.getInstance().validateNow(); if (!endValuesCaptured) propertyChangesArray = captureValues(propertyChangesArray, false); propertyChangesArray = stripUnchangedValues(propertyChangesArray); applyStartValues(propertyChangesArray, this.targets); if (playReversedFromEnd) { for (var j:int = 0; j < propertyChangesArray.length; ++j) { var tmpStart:Object = propertyChangesArray[j].start; propertyChangesArray[j].start = propertyChangesArray[j].end; propertyChangesArray[j].end = tmpStart; } } // Revalidate after applying the start values, to get everything // back the way it should be before starting the animation LayoutManager.getInstance().validateNow(); applyEndValuesWhenDone = true; } var newInstances:Array = createInstances(targets); var n:int = newInstances.length; for (var i:int = 0; i < n; i++) { var newInstance:IEffectInstance = IEffectInstance(newInstances[i]); Object(newInstance).playReversed = playReversedFromEnd; newInstance.startEffect(); } return newInstances; } /** * @copy mx.effects.IEffect#pause() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function pause():void { if (isPlaying && !isPaused) { isPaused = true; var n:int = _instances.length; for (var i:int = 0; i < n; i++) { IEffectInstance(_instances[i]).pause(); } } } /** * @copy mx.effects.IEffect#stop() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function stop():void { var n:int = _instances.length - 1; for (var i:int = n; i >= 0; i--) { var instance:IEffectInstance = IEffectInstance(_instances[i]); if (instance) instance.stop(); } } /** * @copy mx.effects.IEffect#resume() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function resume():void { if (isPlaying && isPaused) { isPaused = false; var n:int = _instances.length; for (var i:int = 0; i < n; i++) { IEffectInstance(_instances[i]).resume(); } } } /** * @copy mx.effects.IEffect#reverse() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function reverse():void { if (isPlaying) { var n:int = _instances.length; for (var i:int = 0; i < n; i++) { IEffectInstance(_instances[i]).reverse(); } } } /** * @copy mx.effects.IEffect#end() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function end(effectInstance:IEffectInstance = null):void { if (effectInstance) { effectInstance.end(); } else { var n:int = _instances.length; for (var i:int = n - 1; i >= 0; i--) { var instance:IEffectInstance = IEffectInstance(_instances[i]); if (instance) instance.end(); } } } /** * Determines the logic for filtering out an effect instance. * The CompositeEffect class overrides this method. * * @param propChanges The properties modified by the effect. * * @param targ The effect target. * * @return Returns true if the effect instance should play. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function filterInstance(propChanges:Array, target:Object):Boolean { if (filterObject) return filterObject.filterInstance(propChanges, effectTargetHost, target); return true; } /** * @copy mx.effects.IEffect#captureStartValues() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function captureStartValues():void { if (targets.length > 0) { // Reset the PropertyChanges array by passing in 'null' propertyChangesArray = captureValues(null, true); _callValidateNow = true; } endValuesCaptured = false; } /** * @copy mx.effects.IEffect#captureMoreStartValues() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function captureMoreStartValues(targets:Array):void { if (targets.length > 0) { // make temporary PropertyChangesArray var additionalPropertyChangesArray:Array = captureValues(null, true); propertyChangesArray = (propertyChangesArray != null) ? propertyChangesArray.concat(additionalPropertyChangesArray) : additionalPropertyChangesArray; } } /** * @copy mx.effects.IEffect#captureEndValues() * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function captureEndValues():void { // captureValues will create propertyChangesArray if it does not // yet exist propertyChangesArray = captureValues(propertyChangesArray, false); endValuesCaptured = true; } /** * @private * Used internally to grab the values of the relevant properties */ mx_internal function captureValues(propChanges:Array, setStartValues:Boolean, targetsToCapture:Array = null):Array { var n:int; var i:int; if (!propChanges) { propChanges = []; // Create a new PropertyChanges object for the sum of all targets. n = targets.length; for (i = 0; i < n; i++) propChanges.push(new PropertyChanges(targets[i])); } // Merge Effect.filterProperties and filterObject.filterProperties var effectProps:Array = !filterObject ? relevantProperties : mergeArrays(relevantProperties, filterObject.filterProperties); var valueMap:Object; var target:Object; var m:int; var j:int; // For each target, grab the property's value // and put it into the propChanges Array. // Walk the targets. if (effectProps && effectProps.length > 0) { n = propChanges.length; for (i = 0; i < n; i++) { target = propChanges[i].target; if (targetsToCapture == null || targetsToCapture.length == 0 || targetsToCapture.indexOf(target) >= 0) { valueMap = setStartValues ? propChanges[i].start : propChanges[i].end; // Walk the properties in the target m = effectProps.length; for (j = 0; j < m; j++) { // Don't clobber values already set if (valueMap[effectProps[j]] === undefined) { valueMap[effectProps[j]] = getValueFromTarget(target,effectProps[j]); } } } } } var styles:Array = !filterObject ? relevantStyles : mergeArrays(relevantStyles, filterObject.filterStyles); if (styles && styles.length > 0) { n = propChanges.length; for (i = 0; i < n; i++) { target = propChanges[i].target; if (targetsToCapture == null || targetsToCapture.length == 0 || targetsToCapture.indexOf(target) >= 0) { if (!(target is IStyleClient)) continue; valueMap = setStartValues ? propChanges[i].start : propChanges[i].end; // Walk the properties in the target. m = styles.length; for (j = 0; j < m; j++) { // Don't clobber values set by relevantProperties if (valueMap[styles[j]] === undefined) { var value:* = target.getStyle(styles[j]); valueMap[styles[j]] = value; } } } } } return propChanges; } /** * Called by the captureStartValues() method to get the value * of a property from the target. * This function should only be called internally * by the effects framework. * The default behavior is to simply return target[property]. * Effect developers can override this function * if you need a different behavior. * * @param target The effect target. * * @param property The target property. * * @return The value of the target property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function getValueFromTarget(target:Object, property:String):* { if (property in target) return target[property]; return undefined; } /** * @private * Applies the start values found in the array of PropertyChanges * to the relevant targets. */ mx_internal function applyStartValues(propChanges:Array, targets:Array):void { var effectProps:Array = relevantProperties; var n:int = propChanges.length; for (var i:int = 0; i < n; i++) { var m:int; var j:int; var target:Object = propChanges[i].target; var apply:Boolean = false; m = targets.length; for (j = 0; j < m; j++) { if (targets[j] == target) { apply = filterInstance(propChanges, target); break; } } if (apply) { // Walk the properties in the target m = effectProps.length; for (j = 0; j < m; j++) { var propName:String = effectProps[j]; var startVal:* = propChanges[i].start[propName]; var endVal:* = propChanges[i].end[propName]; if (propName in propChanges[i].start && endVal != startVal && (!(startVal is Number) || !(isNaN(endVal) && isNaN(startVal)))) { applyValueToTarget(target, effectProps[j], propChanges[i].start[effectProps[j]], propChanges[i].start); } } // Walk the styles in the target m = relevantStyles.length; for (j = 0; j < m; j++) { var styleName:String = relevantStyles[j]; var startStyle:* = propChanges[i].start[styleName]; var endStyle:* = propChanges[i].end[styleName]; if (styleName in propChanges[i].start && endStyle != startStyle && (!(startStyle is Number) || !(isNaN(endStyle) && isNaN(startStyle))) && target is IStyleClient) { if (propChanges[i].end[relevantStyles[j]] !== undefined) target.setStyle(relevantStyles[j], propChanges[i].start[relevantStyles[j]]); else target.clearStyle(relevantStyles[j]); } } } } } /** * @private * Applies the start values found in the array of PropertyChanges * to the relevant targets. */ mx_internal function applyEndValues(propChanges:Array, targets:Array):void { // For now, only new Flex4 effects will apply end values when transitions // are over, to preserve the previous behavior of Flex3 effects if (!applyTransitionEndProperties) return; var effectProps:Array = relevantProperties; var n:int = propChanges.length; for (var i:int = 0; i < n; i++) { var m:int; var j:int; var target:Object = propChanges[i].target; var apply:Boolean = false; m = targets.length; for (j = 0; j < m; j++) { if (targets[j] == target) { apply = filterInstance(propChanges, target); break; } } if (apply) { // Walk the properties in the target m = effectProps.length; for (j = 0; j < m; j++) { var propName:String = effectProps[j]; var startVal:* = propChanges[i].start[propName]; var endVal:* = propChanges[i].end[propName]; if (propName in propChanges[i].end && (!(endVal is Number) || !(isNaN(endVal) && isNaN(startVal)))) { applyValueToTarget(target, propName, propChanges[i].end[propName], propChanges[i].end); } } // Walk the styles in the target m = relevantStyles.length; for (j = 0; j < m; j++) { var styleName:String = relevantStyles[j]; var startStyle:* = propChanges[i].start[styleName]; var endStyle:* = propChanges[i].end[styleName]; if (styleName in propChanges[i].end && (!(endStyle is Number) || !(isNaN(endStyle) && isNaN(startStyle))) && target is IStyleClient) { if (propChanges[i].end[styleName] !== undefined) target.setStyle(styleName, propChanges[i].end[styleName]); else target.clearStyle(styleName); } } } } } /** * Used internally by the Effect infrastructure. * If captureStartValues() has been called, * then when Flex calls the play() method, it uses this function * to set the targets back to the starting state. * The default behavior is to take the value captured * using the getValueFromTarget() method * and set it directly on the target's property. For example:
         *  
         *  target[property] = value;
    * *

    Only override this method if you need to apply * the captured values in a different way. * Note that style properties of a target are set * using a different mechanism. * Use the relevantStyles property to specify * which style properties to capture and apply.

    * * @param target The effect target. * * @param property The target property. * * @param value The value of the property. * * @param props Array of Objects, where each Array element contains a * start and end Object * for the properties that the effect is monitoring. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function applyValueToTarget(target:Object, property:String, value:*, props:Object):void { if (property in target) { // The ""property in target"" test only tells if the property exists // in the target, but does not distinguish between read-only and // read-write properties. Put a try/catch around the setter and // ignore any errors. try { if (applyActualDimensions && target is IFlexDisplayObject && property == ""height"") { target.setActualSize(target.width,value); } else if (applyActualDimensions && target is IFlexDisplayObject && property == ""width"") { target.setActualSize(value,target.height); } else { target[property] = value; } } catch(e:Error) { // Ignore errors } } } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * This method is called when the effect instance starts playing. * If you override this method, ensure that you call the super method. * * @param event An event object of type EffectEvent. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function effectStartHandler(event:EffectEvent):void { dispatchEvent(event); } /** * Called when an effect instance has stopped by a call * to the stop() method. * If you override this method, ensure that you call the super method. * * @param event An event object of type EffectEvent. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function effectStopHandler(event:EffectEvent):void { dispatchEvent(event); // We use this event to determine whether we should set final // state values in the ensuing endHandler() call effectStopped = true; } /** * Called when an effect instance has finished playing. * If you override this method, ensure that you call the super method. * * @param event An event object of type EffectEvent. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function effectEndHandler(event:EffectEvent):void { if (playReversed && propertyChangesArray != null) { for (var j:int = 0; j < propertyChangesArray.length; ++j) { var tmpStart:Object = propertyChangesArray[j].start; propertyChangesArray[j].start = propertyChangesArray[j].end; propertyChangesArray[j].end = tmpStart; } } var lastTime:Boolean = !_instances || _instances.length == 1; // Transitions should set the end values when done if (applyEndValuesWhenDone && !effectStopped && lastTime) applyEndValues(propertyChangesArray, targets); var instance:IEffectInstance = IEffectInstance(event.effectInstance); deleteInstance(instance); dispatchEvent(event); if (lastTime) { propertyChangesArray = null; applyEndValuesWhenDone = false; } } } } ",12284,True,2804.2489102527525,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package flashx.textLayout.elements { import flash.display.Shape; import flash.text.engine.ContentElement; import flash.text.engine.EastAsianJustifier; import flash.text.engine.GroupElement; import flash.text.engine.LineJustification; import flash.text.engine.SpaceJustifier; import flash.text.engine.TabAlignment; import flash.text.engine.TabStop; import flash.text.engine.TextBaseline; import flash.text.engine.TextBlock; import flash.text.engine.TextLine; import flash.text.engine.TextLineValidity; import flash.text.engine.TextRotation; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import flashx.textLayout.compose.TextFlowLine; import flashx.textLayout.container.ContainerController; import flashx.textLayout.debug.Debugging; import flashx.textLayout.debug.assert; import flashx.textLayout.formats.BlockProgression; import flashx.textLayout.formats.Direction; import flashx.textLayout.formats.FormatValue; import flashx.textLayout.formats.ITextLayoutFormat; import flashx.textLayout.formats.JustificationRule; import flashx.textLayout.formats.LeadingModel; import flashx.textLayout.formats.LineBreak; import flashx.textLayout.formats.TabStopFormat; import flashx.textLayout.formats.TextAlign; import flashx.textLayout.formats.TextJustify; import flashx.textLayout.formats.TextLayoutFormat; import flashx.textLayout.property.Property; import flashx.textLayout.tlf_internal; import flashx.textLayout.utils.CharacterUtil; import flashx.textLayout.utils.LocaleUtil; use namespace tlf_internal; /** * The ParagraphElement class represents a paragraph in the text flow hierarchy. Its parent * is a ParagraphFormattedElement, and its children can include spans (SpanElement), images * (inLineGraphicElement), links (LinkElement) and TCY (Tatechuuyoko - ta-tae-chu-yo-ko) elements (TCYElement). The * paragraph text is stored in one or more SpanElement objects, which define ranges of text that share the same attributes. * A TCYElement object defines a small run of Japanese text that runs perpendicular to the line, as in a horizontal run of text in a * vertical line. A TCYElement can also contain multiple spans. * * @includeExample examples\\ParagraphElementExample.as -noswf * @includeExample examples\\ParagraphElementExample2.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see InlineGraphicElement * @see LinkElement * @see SpanElement * @see TCYElement * @see TextFlow */ public final class ParagraphElement extends ParagraphFormattedElement { //private var _textBlock:TextBlock; private var _terminatorSpan:SpanElement; private var _interactiveChildrenCount:int; /** Constructor - represents a paragraph in a text flow. * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ public function ParagraphElement() { super(); _terminatorSpan = null; _interactiveChildrenCount = 0 ; } tlf_internal function get interactiveChildrenCount():int { return _interactiveChildrenCount; } /** @private */ tlf_internal function createTextBlock():void { CONFIG::debug { assert(_textBlock == null,""createTextBlock called when there is already a textblock""); } computedFormat; // recreate the format BEFORE the _textBlock is created var tbs:Vector. = getTextBlocks(); //tbs.length = 0; var tableCount:int = 0; if(tbs.length == 0 && !(getChildAt(0) is TableElement) ) tbs.push(new TextBlock()); //getTextBlocks()[0] = new TextBlock(); CONFIG::debug { Debugging.traceFTECall(_textBlock,null,""new TextBlock()""); } for (var i:int = 0; i < numChildren; i++) { var child:FlowElement = getChildAt(i); if(child is TableElement) tableCount++; // tbs.push(new TextBlock()); else { //child.releaseContentElement(); //child.createContentElement(); } } while(tableCount >= tbs.length) tbs.push(new TextBlock()); for (i = 0; i < numChildren; i++) { child = getChildAt(i); child.createContentElement(); } tbs.length = tableCount + 1; var tb:TextBlock; for each(tb in tbs){ updateTextBlock(tb); } } private function updateTextBlockRefs():void { var tbs:Vector. = getTextBlocks(); if(tbs.length == 0) return;//nothing to do var tbIdx:int = 0; var tb:TextBlock = tbs[tbIdx]; var items:Array = []; var child:FlowElement; for (var i:int = 0; i < numChildren; i++) { child = getChildAt(i); if(child is TableElement) { tb.userData = items; if(++tbIdx == tbs.length) return; tb = tbs[tbIdx]; tb.userData = null; //Advance to the next one. if(++tbIdx == tbs.length) return; tb = tbs[tbIdx]; items = []; continue; } items.push(child); } tb.userData = items; } private function removeTextBlock(tb:TextBlock):void { var tbs:Vector. = getTextBlocks(); if(tbs) { var idx:int = getTextBlocks().indexOf(tb); if(idx > -1) { tbs.splice(idx,1); } } } private function releaseTextBlockInternal(tb:TextBlock):void { if (!tb) return; if (tb.firstLine) // A TextBlock may have no firstLine if it has previously been released. { for (var textLineTest:TextLine = tb.firstLine; textLineTest != null; textLineTest = textLineTest.nextLine) { if(textLineTest.numChildren != 0) { //if the number of adornments added does not match the number of children on the textLine //then a third party has added adornments. Don't recycle the line or the adornment will be //lost. var tfl:TextFlowLine = textLineTest.userData as TextFlowLine; if(tfl.adornCount != textLineTest.numChildren) return; } } CONFIG::debug { Debugging.traceFTECall(null,tb,""releaseLines"",tb.firstLine, tb.lastLine); } tb.releaseLines(tb.firstLine, tb.lastLine); } var items:Array = tb.userData; if(items) { var len:int = items.length; for (var i:int = 0; i < len; i++) { var child:FlowElement = items[i]; child.releaseContentElement(); } items.length = 0; } tb.content = null; removeTextBlock(tb); } /** @private */ tlf_internal function releaseTextBlock(tb:TextBlock=null):void { updateTextBlockRefs(); if(tb) { releaseTextBlockInternal(tb); return; } var tbs:Vector. = getTextBlocks(); for each(var textBlock:TextBlock in tbs) { releaseTextBlockInternal(textBlock); } //_textBlock = null; if (_computedFormat) _computedFormat = null; } private var _textBlocks:Vector.; tlf_internal function getTextBlocks():Vector. { if(_textBlocks == null) _textBlocks = new Vector.(); return _textBlocks; } /** TextBlock where the text of the paragraph is kept. @private */ tlf_internal function getTextBlock():TextBlock { if (!getTextBlocks().length) createTextBlock(); return getTextBlocks()[0]; } /** Last TextBlock where the text of the paragraph is kept. @private */ tlf_internal function getLastTextBlock():TextBlock { var tbs:Vector. = getTextBlocks(); if(!tbs.length) createTextBlock(); return tbs[tbs.length-1]; } /** Get TextBlock at specified position. @private */ tlf_internal function getTextBlockAtPosition(pos:int):TextBlock { var curPos:int = 0; var posShift:int = 0; var tables:Vector. = getTables(); if(!tables.length) return getTextBlock(); for each(var table:TableElement in tables) { if(table.getElementRelativeStart(this) < pos) posShift++; } var tbs:Vector. = getTextBlocks(); for each(var tb:TextBlock in tbs) { if(tb.content == null) return tb; curPos += tb.content.rawText.length; if(curPos + posShift > pos) { if(getTextBlockStart(tb) > pos) return null; return tb; } } return null; } tlf_internal function getTextBlockAbsoluteStart(tb:TextBlock):int { var start:int = getTextBlockStart(tb); if(start < 0) start = 0; return getAbsoluteStart() + start; } tlf_internal function getTextBlockStart(tb:TextBlock):int { var i:int; var curPos:int = 0; var tbs:Vector. = getTextBlocks(); if(tbs.length == 0) return -1; var tables:Vector. = getTables(); for each(var curTB:TextBlock in tbs) { for each(var table:TableElement in tables) { if(table.getElementRelativeStart(this) <= curPos) { curPos++; tables.splice(tables.indexOf(table),1); } } if(tb == curTB) return curPos; if(tb.content) curPos += curTB.content.rawText.length; } return -1; } private function getTables():Vector. { var tables:Vector. = new Vector.(); for (var i:int = 0; i < numChildren; i++) { var child:FlowElement = getChildAt(i); if(child is TableElement) tables.push(child as TableElement); } return tables; } /** TextBlock where the text of the paragraph is kept, or null if we currently don't have one. @private */ tlf_internal function peekTextBlock():TextBlock { return getTextBlocks().length == 0 ? null : getTextBlocks()[0]; } /** @private */ tlf_internal function releaseLineCreationData():void { CONFIG::debug { assert(Configuration.playerEnablesArgoFeatures,""bad call to releaseLineCreationData""); } var tbs:Vector. = getTextBlocks(); for each(var tb:TextBlock in tbs) { tb[""releaseLineCreationData""](); } } /** @private */ tlf_internal override function createContentAsGroup(pos:int=0):GroupElement { var tb:TextBlock = getTextBlockAtPosition(pos); if(!tb) tb = getTextBlockAtPosition(pos-1); var group:GroupElement = tb.content as GroupElement; if (!group) { var originalContent:ContentElement = tb.content; group = new GroupElement(); CONFIG::debug { Debugging.traceFTECall(group,null,""new GroupElement()""); } tb.content = group; CONFIG::debug { Debugging.traceFTEAssign(tb,""content"",group); } if (originalContent) { var gc:Vector. = new Vector.(); CONFIG::debug { Debugging.traceFTECall(gc,null,""new Vector.()"") } gc.push(originalContent); CONFIG::debug { Debugging.traceFTECall(null,gc,""push"",originalContent); } group.replaceElements(0,0,gc); CONFIG::debug { Debugging.traceFTECall(null,group,""replaceElements"",0,0,gc); } } // Now we've got to force damage the entire paragraph, because we restructured it in FTE. if (tb.firstLine && textLength) { var textFlow:TextFlow = getTextFlow(); if (textFlow) textFlow.damage(getAbsoluteStart(), textLength, TextLineValidity.INVALID, false); } } return group; } /** @private */ tlf_internal override function removeBlockElement(child:FlowElement, block:ContentElement):void { var tb:TextBlock = getTextBlockAtPosition(child.getElementRelativeStart(this)); if(!tb) tb = getTextBlock(); if(tb.content == null) return; var relativeStart:int = child.getElementRelativeStart(this); if (getChildrenInTextBlock(relativeStart).length < 2) { if (block is GroupElement) { // see insertBlockElement CONFIG::debug { assert(_textBlock.content != block,""removeBlockElement: bad call to removeBlockElement""); } CONFIG::debug { assert(_textBlock.content is GroupElement,""removeBlockElement: bad content""); } CONFIG::debug { assert(GroupElement(_textBlock.content).elementCount == 1,""removeBlockElement: bad element count""); } CONFIG::debug { assert(GroupElement(_textBlock.content).getElementAt(0) == block,""removeBlockElement: bad group content""); } GroupElement(tb.content).replaceElements(0,1,null); CONFIG::debug { Debugging.traceFTECall(null,_textBlock.content,""replaceElements"",0,1,null); } } tb.content = null; CONFIG::debug { Debugging.traceFTEAssign(_textBlock,""content"",null); } } else if(block.groupElement) { var idx:int = getChildIndexInBlock(child); var group:GroupElement = GroupElement(tb.content); CONFIG::debug { assert(group.elementCount == numChildren,""Mismatched group and elementCount""); } group.replaceElements(idx,idx+1,null); if(group.elementCount == 0) return; CONFIG::debug { Debugging.traceFTECall(null,group,""replaceElements"",idx,idx+1,null); } if (numChildren == 2) // its going to be one so ungroup { // ungroup - need to take it out first as inlinelements can only have one parent var elem:ContentElement = group.getElementAt(0); CONFIG::debug { Debugging.traceFTECall(elem,group,""getElementAt"",0); } if (!(elem is GroupElement)) { group.replaceElements(0,1,null); CONFIG::debug { Debugging.traceFTECall(null,group,""replaceElements"",0,1,null); } tb.content = elem; CONFIG::debug { Debugging.traceFTEAssign(tb,""content"",elem); } } } } else { //trace(""1""); //tb.content = null; } } /** @private */ tlf_internal override function hasBlockElement():Boolean { return getTextBlocks().length > 0; } /** @private */ override tlf_internal function createContentElement():void { createTextBlock(); } /** @private */ private function getChildrenInTextBlock(pos:int):Array { var retVal:Array = []; if(numChildren == 0) return retVal; if(numChildren == 1) { retVal.push(getChildAt(0)); return retVal } var chldrn:Array = mxmlChildren.slice(); for(var i:int = 0; i= pos) break; } retVal.push(chldrn[i]); } return retVal; } /** @private */ tlf_internal override function insertBlockElement(child:FlowElement, block:ContentElement):void { var relativeStart:int = child.getElementRelativeStart(this); var tb:TextBlock = getTextBlockAtPosition(relativeStart); if(!tb) tb = getTextBlockAtPosition(relativeStart-1); if(!tb) { child.releaseContentElement(); return; } if (getTextBlocks().length == 0) { child.releaseContentElement(); createTextBlock(); // does the whole tree return; } var gc:Vector.; // scratch var var group:GroupElement; // scratch if (getChildrenInTextBlock(relativeStart).length < 2) { if (block is GroupElement) { // this case forces the Group to be in a Group so that following FlowLeafElements aren't in a SubParagraphGroupElementBase's group gc = new Vector.(); CONFIG::debug { Debugging.traceFTECall(gc,null,""new Vector.()"") } gc.push(block); CONFIG::debug { Debugging.traceFTECall(null,gc,""push"",block); } group = new GroupElement(gc); CONFIG::debug { Debugging.traceFTECall(group,null,""new GroupElement"",gc); } tb.content = group; CONFIG::debug { Debugging.traceFTEAssign(_textBlock,""content"",group); } } else { if(block.groupElement) { block.groupElement.elementCount; } tb.content = block; CONFIG::debug { Debugging.traceFTEAssign(_textBlock,""content"",block); } } } else { group = createContentAsGroup(relativeStart); var idx:int = getChildIndexInBlock(child); gc = new Vector.(); CONFIG::debug { Debugging.traceFTECall(gc,null,""new Vector."") } gc.push(block); CONFIG::debug { Debugging.traceFTECall(null,gc,""push"",block); } // If elements in the middle (i.e. ones in the process of being added) were missed, the idx can be too high. // The missed ones will be inserted later. if(idx > group.elementCount) idx = group.elementCount; group.replaceElements(idx,idx,gc); CONFIG::debug { Debugging.traceFTECall(null,group,""replaceElements"",idx,idx,gc); } } } private function getChildIndexInBlock(elem:FlowElement):int { var relIdx:int = 0; for (var i:int = 0; i < numChildren; i++) { var child:FlowElement = getChildAt(i); if(child == elem) return relIdx; relIdx++; if(child is TableElement) relIdx = 0; } return -1; } /** @private */ override protected function get abstract():Boolean { return false; } /** @private */ tlf_internal override function get defaultTypeName():String { return ""p""; } tlf_internal function removeEmptyTerminator():void { if(numChildren == 1 && _terminatorSpan && _terminatorSpan.textLength == 1) { _terminatorSpan.removeParaTerminator(); super.replaceChildren(0, 1); this._terminatorSpan = null; } } /** @private */ public override function replaceChildren(beginChildIndex:int,endChildIndex:int,...rest):void { var applyParams:Array; do{ if(_terminatorSpan) { var termIdx:int = getChildIndex(_terminatorSpan); if(termIdx > 0 && termIdx < beginChildIndex && _terminatorSpan.textLength == 1) { super.replaceChildren(termIdx, termIdx+1); _terminatorSpan = null; if(beginChildIndex >= termIdx) { beginChildIndex--; if(rest.length == 0) // delete of terminator was already done. break; } if(endChildIndex >= termIdx && beginChildIndex != endChildIndex) endChildIndex--; } } // makes a measurable difference - rest.length zero and one are the common cases if (rest.length == 1) applyParams = [beginChildIndex, endChildIndex, rest[0]]; else { applyParams = [beginChildIndex, endChildIndex]; if (rest.length != 0) applyParams = applyParams.concat.apply(applyParams, rest); } super.replaceChildren.apply(this, applyParams); }while(false); ensureTerminatorAfterReplace(); // ensure correct text blocks createTextBlock(); } public override function splitAtPosition(relativePosition:int):FlowElement { // need to handle multiple TextBlocks // maybe not. It might be handled in replaceChildren(). return super.splitAtPosition(relativePosition); } /** @private */ tlf_internal function ensureTerminatorAfterReplace():void { //lose reference to terminator if it was removed or not a direct child. if(_terminatorSpan && _terminatorSpan.parent != this) { _terminatorSpan.removeParaTerminator(); _terminatorSpan = null; } var newLastLeaf:FlowLeafElement = getLastLeaf(); if (_terminatorSpan != newLastLeaf) { if(_terminatorSpan) _terminatorSpan.removeParaTerminator(); if (newLastLeaf && _terminatorSpan) { if(_terminatorSpan.textLength == 0 && !_terminatorSpan.id) { var termIdx:int = getChildIndex(_terminatorSpan); super.replaceChildren(termIdx, termIdx+1); } this._terminatorSpan = null; } if(newLastLeaf) { if (newLastLeaf is SpanElement) { (newLastLeaf as SpanElement).addParaTerminator(); this._terminatorSpan = newLastLeaf as SpanElement; } else { var s:SpanElement = new SpanElement(); super.replaceChildren(numChildren,numChildren,s); s.format = newLastLeaf ? newLastLeaf.format : _terminatorSpan.format; s.addParaTerminator(); this._terminatorSpan = s; } } else _terminatorSpan = null; } //merge terminator span to previous if possible if(_terminatorSpan && _terminatorSpan.textLength == 1) { var prev:FlowLeafElement = _terminatorSpan.getPreviousLeaf(this); if(prev && prev.parent == this && prev is SpanElement) { _terminatorSpan.mergeToPreviousIfPossible(); } } } /** @private */ tlf_internal function updateTerminatorSpan(splitSpan:SpanElement,followingSpan:SpanElement):void { if (_terminatorSpan == splitSpan) _terminatorSpan = followingSpan; } [RichTextContent] /** @private NOTE: all FlowElement implementers and overrides of mxmlChildren must specify [RichTextContent] metadata */ public override function set mxmlChildren(array:Array):void { // remove all existing children replaceChildren(0,numChildren); for each (var child:Object in array) { if (child is FlowElement) { if ((child is SpanElement) || (child is SubParagraphGroupElementBase)) child.bindableElement = true; // Note: calling super.replaceChildren because we don't want to transfer para terminator each time super.replaceChildren(numChildren, numChildren, child as FlowElement); } else if (child is String) { var s:SpanElement = new SpanElement(); s.text = String(child); s.bindableElement = true; // Note: calling super.replaceChildren because we don't want to transfer para terminator each time super.replaceChildren(numChildren, numChildren, s); } else if (child != null) throw new TypeError(GlobalSettings.resourceStringFunction(""badMXMLChildrenArgument"",[ getQualifiedClassName(child) ])); } // Now ensure para terminator ensureTerminatorAfterReplace(); // recreate text blocks to handle possible TableElement changes createTextBlock(); } /** @private */ public override function getText(relativeStart:int=0, relativeEnd:int=-1, paragraphSeparator:String=""\\n""):String { // Optimization for getting text of the entire paragraph if (relativeStart == 0 && (relativeEnd == -1 || relativeEnd >= textLength-1) && getTextBlocks().length) { var tb:TextBlock; var tbs:Vector. = getTextBlocks(); var text:String = """"; for each(tb in tbs) { text = text + getTextInBlock(tb); } if(tb.content && tb.content.rawText) return text.substring(0, text.length - 1); return text; } return super.getText(relativeStart, relativeEnd, paragraphSeparator); } private function getTextInBlock(tb:TextBlock):String{ if(!tb.content || !tb.content.rawText) return """"; return tb.content.rawText; } /** Returns the paragraph that follows this one, or null if there are no more paragraphs. * * @return the next paragraph or null if there are no more paragraphs. * * @includeExample examples\\ParagraphElement_getNextParagraph.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see #getPreviousParagraph() */ public function getNextParagraph():ParagraphElement { var nextLeaf:FlowLeafElement = getLastLeaf().getNextLeaf(); return nextLeaf ? nextLeaf.getParagraph() : null; } /** Returns the paragraph that precedes this one, or null, if this paragraph is the first one * in the TextFlow. * * @includeExample examples\\ParagraphElement_getPreviousParagraph.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see #getNextParagraph() */ public function getPreviousParagraph():ParagraphElement { var previousLeaf:FlowLeafElement = getFirstLeaf().getPreviousLeaf(); return previousLeaf ? previousLeaf.getParagraph() : null; } /** * Scans backward from the supplied position to find the location * in the text of the previous atom and returns the index. The term atom refers to * both graphic elements and characters (including groups of combining characters), the * indivisible entities that make up a text line. * * @param relativePosition position in the text to start from, counting from 0 * @return index in the text of the previous cluster * * @includeExample examples\\ParagraphElement_findPreviousAtomBoundary.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see flash.text.engine.TextLine */ public function findPreviousAtomBoundary(relativePosition:int):int { var tb:TextBlock = getTextBlockAtPosition(relativePosition); if(!tb || !tb.content) return relativePosition-1; var tbStart:int = getTextBlockStart(tb); var textBlockPos:int = relativePosition - tbStart; var tl:TextLine = tb.getTextLineAtCharIndex(textBlockPos); if (ContainerController.tlf_internal::usesDiscretionaryHyphens && tl != null) { var currentAtomIndex:int = tl.getAtomIndexAtCharIndex(textBlockPos); //trace(""relpos"", relativePosition, ""atomIndex"", currentAtomIndex); var isRTL:Boolean = tl.getAtomBidiLevel(currentAtomIndex) == 1; if (isRTL) { var foo:int = tb.findPreviousAtomBoundary(textBlockPos); if (currentAtomIndex == 0) { // when cursor is left of all characters (end of line) // atomIndex is 0, so compensate if (tl.atomCount > 0) { while (--textBlockPos) { --relativePosition; if (tl.getAtomIndexAtCharIndex(textBlockPos) != currentAtomIndex) break; } } } else { while (--relativePosition && --textBlockPos) { if (tl.getAtomIndexAtCharIndex(textBlockPos) != currentAtomIndex) break; } } if (CharacterUtil.isLowSurrogate(getText(relativePosition, relativePosition + 1).charCodeAt(0))) { relativePosition--; textBlockPos--; } //trace(""previous"", relativePosition, foo); } else { if (currentAtomIndex == 0) { tl = tl.previousLine; if (!tl) { if(tb != _textBlocks[0]) return relativePosition-1; return -1; } // need this when 0x2028 line separator in use if (tl.textBlockBeginIndex + tl.rawTextLength == textBlockPos) return tl.textBlockBeginIndex + tl.rawTextLength - 1 + tbStart; return tl.textBlockBeginIndex + tl.rawTextLength + tbStart; } while (--relativePosition && --textBlockPos) { if (tl.getAtomIndexAtCharIndex(textBlockPos) < currentAtomIndex) break; } if (CharacterUtil.isLowSurrogate(getText(relativePosition, relativePosition + 1).charCodeAt(0))) { relativePosition--; textBlockPos--; } } return relativePosition; } var pos:int = tb.findPreviousAtomBoundary(textBlockPos); if(pos >= 0) pos += tbStart; //trace(""previous"", relativePosition, pos); return pos; } /** * Scans ahead from the supplied position to find the location * in the text of the next atom and returns the index. The term atom refers to * both graphic elements and characters (including groups of combining characters), the * indivisible entities that make up a text line. * * @param relativePosition position in the text to start from, counting from 0 * @return index in the text of the following atom * * @includeExample examples\\ParagraphElement_findNextAtomBoundary.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * * @see flash.text.engine.TextLine */ public function findNextAtomBoundary(relativePosition:int):int { var tb:TextBlock = getTextBlockAtPosition(relativePosition); if(!tb || !tb.content) return relativePosition+1; var tbStart:int = getTextBlockStart(tb); var textBlockPos:int = relativePosition - tbStart; var tl:TextLine = tb.getTextLineAtCharIndex(textBlockPos); if (ContainerController.tlf_internal::usesDiscretionaryHyphens && tl != null) { var currentAtomIndex:int = tl.getAtomIndexAtCharIndex(textBlockPos); //trace(""relpos"", relativePosition, ""atomIndex"", currentAtomIndex); var isRTL:Boolean = tl.getAtomBidiLevel(currentAtomIndex) == 1; if (isRTL) { var foo:int = tb.findNextAtomBoundary(textBlockPos); if (currentAtomIndex == 0) { while (++textBlockPos) { ++relativePosition; if (tl.getAtomIndexAtCharIndex(textBlockPos) != currentAtomIndex) break; } } else { while (++textBlockPos) { ++relativePosition; if (tl.getAtomIndexAtCharIndex(textBlockPos) != currentAtomIndex) break; } } if (CharacterUtil.isHighSurrogate(getText(relativePosition, relativePosition + 1).charCodeAt(0))) { relativePosition++; textBlockPos++; } //trace(""next"", relativePosition, foo); } else { if (currentAtomIndex == tl.atomCount - 1) { tl = tl.nextLine; if (!tl) { if(tb != _textBlocks[_textBlocks.length-1]) return relativePosition+1; return -1; } return tl.textBlockBeginIndex + tbStart; } while (++textBlockPos) { ++relativePosition; if (tl.getAtomIndexAtCharIndex(textBlockPos) > currentAtomIndex) break; } if (CharacterUtil.isHighSurrogate(getText(relativePosition, relativePosition + 1).charCodeAt(0))) { relativePosition++; textBlockPos++; } } return relativePosition; } var pos:int = tb.findNextAtomBoundary(textBlockPos); if(pos >= 0) pos += tbStart; //trace(""next"", relativePosition, pos); return pos; } /** @private */ public override function getCharAtPosition(relativePosition:int):String { var foundTB:TextBlock = getTextBlockAtPosition(relativePosition); if(!foundTB) return ""\\u0016""; var tables:Vector. = getTables(); var pos:int = relativePosition; for each(var table:TableElement in tables) { if(table.getElementRelativeStart(this) < pos) relativePosition--; } var tbs:Vector. = getTextBlocks(); for each(var tb:TextBlock in tbs) { if(foundTB == tb) break; if(tb) relativePosition -= tb.content.rawText.length; else relativePosition -= 1;this.getText() } return foundTB.content.rawText.charAt(relativePosition); } /** * Returns the index of the previous word boundary in the text. * *

    Scans backward from the supplied position to find the previous position * in the text that starts or ends a word.

    * * @param relativePosition position in the text to start from, counting from 0 * @return index in the text of the previous word boundary * * @includeExample examples\\ParagraphElement_findPreviousWordBoundary.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ public function findPreviousWordBoundary(relativePosition:int):int { if (relativePosition == 0) return 0; var prevCharCode:int = getCharCodeAtPosition(relativePosition - 1); if (CharacterUtil.isWhitespace(prevCharCode)) { while (CharacterUtil.isWhitespace(prevCharCode) && ((relativePosition - 1) > 0)) { relativePosition--; prevCharCode = getCharCodeAtPosition(relativePosition - 1); } return relativePosition; } var block:TextBlock = getTextBlockAtPosition(relativePosition); if(block == null) block = getTextBlockAtPosition(--relativePosition); var pos:int = getTextBlockStart(block); if(pos < 0) pos = 0; return relativePosition == pos ? pos : pos + block.findPreviousWordBoundary(relativePosition - pos); } /** * Returns the index of the next word boundary in the text. * *

    Scans ahead from the supplied position to find the next position * in the text that starts or ends a word.

    * * @param relativePosition position in the text to start from, counting from 0 * @return index in the text of the next word boundary * * @includeExample examples\\ParagraphElement_findNextWordBoundary.as -noswf * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ public function findNextWordBoundary(relativePosition:int):int { if (relativePosition == textLength) return textLength; var curCharCode:int = getCharCodeAtPosition(relativePosition); if (CharacterUtil.isWhitespace(curCharCode)) { while (CharacterUtil.isWhitespace(curCharCode) && relativePosition < (textLength - 1)) { relativePosition++; curCharCode = getCharCodeAtPosition(relativePosition); } return relativePosition; } var block:TextBlock = getTextBlockAtPosition(relativePosition); if(block == null) block = getTextBlockAtPosition(--relativePosition); var pos:int = getTextBlockStart(block); if(pos < 0) pos = 0; return pos + block.findNextWordBoundary(relativePosition - pos); } static private var _defaultTabStops:Vector.; static private const defaultTabWidth:int = 48; // matches default tabs setting in Argo static private const defaultTabCount:int = 20; static private function initializeDefaultTabStops():void { _defaultTabStops = new Vector.(defaultTabCount, true); for (var i:int = 0; i < defaultTabCount; ++i) _defaultTabStops[i] = new TabStop(TextAlign.START, defaultTabWidth * i); } private function updateTextBlock(textBlock:TextBlock=null):void { if(!textBlock) textBlock = getTextBlock(); // find the ancestor with a container and use its format for various settings var containerElement:ContainerFormattedElement = getAncestorWithContainer(); if (!containerElement) return; var containerElementFormat:ITextLayoutFormat = containerElement ? containerElement.computedFormat : TextLayoutFormat.defaultFormat; var lineJust:String; if (computedFormat.textAlign == TextAlign.JUSTIFY) { lineJust = (_computedFormat.textAlignLast == TextAlign.JUSTIFY) ? LineJustification.ALL_INCLUDING_LAST : LineJustification.ALL_BUT_LAST; // We don't allow explicit line breaks and justification together because it results in very strange (invisible) lines if (containerElementFormat.lineBreak == LineBreak.EXPLICIT) lineJust = LineJustification.UNJUSTIFIED; } else lineJust = LineJustification.UNJUSTIFIED; var makeJustRuleStyle:String = this.getEffectiveJustificationStyle(); var justRule:String = this.getEffectiveJustificationRule(); // set the justifier in the TextBlock if (justRule == JustificationRule.SPACE) { var spaceJustifier:SpaceJustifier = new SpaceJustifier(_computedFormat.locale,lineJust,false); spaceJustifier.letterSpacing = _computedFormat.textJustify == TextJustify.DISTRIBUTE ? true : false; if (Configuration.playerEnablesArgoFeatures) { // These three properties have to be set in the correct order so that consistency checks done // in the Player on set are never violated var newMinimumSpacing:Number = Property.toNumberIfPercent(_computedFormat.wordSpacing.minimumSpacing)/100; var newMaximumSpacing:Number = Property.toNumberIfPercent(_computedFormat.wordSpacing.maximumSpacing)/100; var newOptimumSpacing:Number = Property.toNumberIfPercent(_computedFormat.wordSpacing.optimumSpacing)/100; spaceJustifier[""minimumSpacing""] = Math.min(newMinimumSpacing, spaceJustifier[""minimumSpacing""]); spaceJustifier[""maximumSpacing""] = Math.max(newMaximumSpacing, spaceJustifier[""maximumSpacing""]); spaceJustifier[""optimumSpacing""] = newOptimumSpacing; spaceJustifier[""minimumSpacing""] = newMinimumSpacing; spaceJustifier[""maximumSpacing""] = newMaximumSpacing; } CONFIG::debug { Debugging.traceFTECall(spaceJustifier,null,""new SpaceJustifier"",_computedFormat.locale,lineJust,spaceJustifier.letterSpacing); } textBlock.textJustifier = spaceJustifier; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""textJustifier"",spaceJustifier); } textBlock.baselineZero = getLeadingBasis(this.getEffectiveLeadingModel()); CONFIG::debug { Debugging.traceFTEAssign(textBlock,""baselineZero"",textBlock.baselineZero); } } else { var eastAsianJustifier:Object = new EastAsianJustifier(_computedFormat.locale,lineJust, makeJustRuleStyle); if( Configuration.versionIsAtLeast(10,3) && eastAsianJustifier.hasOwnProperty(""composeTrailingIdeographicSpaces"")){ eastAsianJustifier.composeTrailingIdeographicSpaces = true; } CONFIG::debug { Debugging.traceFTECall(eastAsianJustifier,null,""new EastAsianJustifier"",_computedFormat.locale,lineJust,makeJustRuleStyle); } textBlock.textJustifier = eastAsianJustifier as EastAsianJustifier; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""textJustifier"",eastAsianJustifier); } textBlock.baselineZero = getLeadingBasis(this.getEffectiveLeadingModel()); CONFIG::debug { Debugging.traceFTEAssign(textBlock,""baselineZero"",textBlock.baselineZero); } } textBlock.bidiLevel = _computedFormat.direction == Direction.LTR ? 0 : 1; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""bidiLevel"",textBlock.bidiLevel); } textBlock.lineRotation = containerElementFormat.blockProgression == BlockProgression.RL ? TextRotation.ROTATE_90 : TextRotation.ROTATE_0; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""lineRotation"",textBlock.lineRotation); } if (_computedFormat.tabStops && _computedFormat.tabStops.length != 0) { //create a vector of TabStops and assign it to tabStops in textBlock var tabStops:Vector. = new Vector.(); CONFIG::debug { Debugging.traceFTECall(tabStops,null,""new Vector.()""); } for each(var tsa:TabStopFormat in _computedFormat.tabStops) { var token:String = tsa.decimalAlignmentToken==null ? """" : tsa.decimalAlignmentToken; var alignment:String = tsa.alignment==null ? TabAlignment.START : tsa.alignment; var tabStop:TabStop = new TabStop(alignment,Number(tsa.position),token); // this next line when uncommented works around bug 1912782 if (tsa.decimalAlignmentToken != null) var garbage:String = ""x"" + tabStop.decimalAlignmentToken; CONFIG::debug { Debugging.traceFTECall(tabStop,null,""new TabStop"",tabStop.alignment,tabStop.position,tabStop.decimalAlignmentToken); } tabStops.push(tabStop); CONFIG::debug { Debugging.traceFTECall(null,tabStops,""push"",tabStop); } } textBlock.tabStops = tabStops; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""tabStops"",tabStops); } } else if (GlobalSettings.enableDefaultTabStops && !Configuration.playerEnablesArgoFeatures) { // Player versions prior to 10.1 do not set up any default tabStops. As a workaround, if enableDefaultTabs // is true, TLF will set up default tabStops in the case where there are no tabs defined. if (_defaultTabStops == null) initializeDefaultTabStops(); textBlock.tabStops = _defaultTabStops; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""tabStops"",_defaultTabStops); } } else { textBlock.tabStops = null; CONFIG::debug { Debugging.traceFTEAssign(textBlock,""tabStops"",null); } } } /** @private */ public override function get computedFormat():ITextLayoutFormat { if (!_computedFormat) { super.computedFormat; var tbs:Vector. = getTextBlocks(); for each(var tb:TextBlock in tbs) updateTextBlock(tb); } return _computedFormat; } /** @private */ tlf_internal override function canOwnFlowElement(elem:FlowElement):Boolean { return elem is FlowLeafElement || elem is SubParagraphGroupElementBase || elem is TableElement; } /** @private */ tlf_internal override function normalizeRange(normalizeStart:uint,normalizeEnd:uint):void { var idx:int = findChildIndexAtPosition(normalizeStart); if (idx != -1 && idx < numChildren) { var child:FlowElement = getChildAt(idx); normalizeStart = normalizeStart-child.parentRelativeStart; CONFIG::debug { assert(normalizeStart >= 0, ""bad normalizeStart in normalizeRange""); } for (;;) { // watch out for changes in the length of the child var origChildEnd:int = child.parentRelativeStart+child.textLength; child.normalizeRange(normalizeStart,normalizeEnd-child.parentRelativeStart); var newChildEnd:int = child.parentRelativeStart+child.textLength; normalizeEnd += newChildEnd-origChildEnd; // adjust // no zero length children if (child.textLength == 0 && !child.bindableElement) replaceChildren(idx,idx+1); else if (child.mergeToPreviousIfPossible()) { var prevElement:FlowElement = this.getChildAt(idx-1); // possibly optimize the start to the length of prevelement before the merge prevElement.normalizeRange(0,prevElement.textLength); } else idx++; if (idx == numChildren) { // check if last child is an empty SubPargraphBlock and remove it if (idx != 0) { var lastChild:FlowElement = this.getChildAt(idx-1); if (lastChild is SubParagraphGroupElementBase && lastChild.textLength == 1 && !lastChild.bindableElement) replaceChildren(idx-1,idx); } break; } // next child child = getChildAt(idx); if (child.parentRelativeStart > normalizeEnd) break; normalizeStart = 0; // for the next child } } // empty paragraphs not allowed after normalize if (numChildren == 0 || textLength == 0) { var s:SpanElement = new SpanElement(); replaceChildren(0,0,s); s.normalizeRange(0,s.textLength); } } /** @private */ tlf_internal function getEffectiveLeadingModel():String { return computedFormat.leadingModel == LeadingModel.AUTO ? LocaleUtil.leadingModel(computedFormat.locale) : computedFormat.leadingModel; } /** @private */ tlf_internal function getEffectiveDominantBaseline():String { return computedFormat.dominantBaseline == FormatValue.AUTO ? LocaleUtil.dominantBaseline(computedFormat.locale) : computedFormat.dominantBaseline; } /** @private */ tlf_internal function getEffectiveJustificationRule():String { return computedFormat.justificationRule == FormatValue.AUTO ? LocaleUtil.justificationRule(computedFormat.locale) : computedFormat.justificationRule; } /** @private */ tlf_internal function getEffectiveJustificationStyle():String { return computedFormat.justificationStyle == FormatValue.AUTO ? LocaleUtil.justificationStyle(computedFormat.locale) : computedFormat.justificationStyle; } /** @private */ CONFIG::debug public override function debugCheckFlowElement(depth:int = 0, extraData:String = """"):int { var tb:TextBlock = getTextBlock(); var rslt:int = super.debugCheckFlowElement(depth,"" fte:""+getDebugIdentity(tb)+"" ""+extraData); // now check the character count and then the last character if (tb) { var contentLength:int = tb.content && tb.content.rawText ? tb.content.rawText.length : 0; rslt += assert(contentLength == textLength,""Bad paragraph length mode:""+textLength.toString()+"" _textBlock:"" + contentLength.toString()); var groupElement:GroupElement = tb.content as GroupElement; if (groupElement) assert(groupElement.elementCount == numChildren,""Mismatched group and elementCount""); else if (tb.content) assert(1 == numChildren,""Mismatched group and elementCount""); else assert(0 == numChildren,""Mismatched group and elementCount""); } rslt += assert(numChildren == 0 || textLength > 0,""Para must have at least one text char""); return rslt; } /** @private */ tlf_internal static function getLeadingBasis (leadingModel:String):String { switch (leadingModel) { default: CONFIG::debug { assert(false,""Unsupported parameter to ParagraphElement.getLeadingBasis""); } // In particular, AUTO is not supported by this method. Must be mapped to one of the above case LeadingModel.ASCENT_DESCENT_UP: case LeadingModel.APPROXIMATE_TEXT_FIELD: case LeadingModel.BOX: case LeadingModel.ROMAN_UP: return flash.text.engine.TextBaseline.ROMAN; case LeadingModel.IDEOGRAPHIC_TOP_UP: case LeadingModel.IDEOGRAPHIC_TOP_DOWN: return flash.text.engine.TextBaseline.IDEOGRAPHIC_TOP; case LeadingModel.IDEOGRAPHIC_CENTER_UP: case LeadingModel.IDEOGRAPHIC_CENTER_DOWN: return flash.text.engine.TextBaseline.IDEOGRAPHIC_CENTER; } } /** @private */ tlf_internal static function useUpLeadingDirection (leadingModel:String):Boolean { switch (leadingModel) { default: CONFIG::debug { assert(false,""Unsupported parameter to ParagraphElement.useUpLeadingDirection""); } // In particular, AUTO is not supported by this method. Must be mapped to one of the above case LeadingModel.ASCENT_DESCENT_UP: case LeadingModel.APPROXIMATE_TEXT_FIELD: case LeadingModel.BOX: case LeadingModel.ROMAN_UP: case LeadingModel.IDEOGRAPHIC_TOP_UP: case LeadingModel.IDEOGRAPHIC_CENTER_UP: return true; case LeadingModel.IDEOGRAPHIC_TOP_DOWN: case LeadingModel.IDEOGRAPHIC_CENTER_DOWN: return false; } } tlf_internal function incInteractiveChildrenCount() : void { ++ _interactiveChildrenCount ; } tlf_internal function decInteractiveChildrenCount() : void { -- _interactiveChildrenCount ; } tlf_internal function hasInteractiveChildren() : Boolean { return _interactiveChildrenCount != 0 ; } tlf_internal function get terminatorSpan():SpanElement { return _terminatorSpan; } } } ",12162,False,2351.4699069742555,median ":toc: :toclevels: 4 :sectnums: = MLPerf Training Rules Version 1.0 March 25, 2021 == Overview This document describes how to implement the MLPerf Training Suite using an ML framework and how to use that implementation to measure the performance of an ML software framework or hardware. There are seperate rules for the submission, review, and publication process for all MLPerf benchmarks https://github.com/mlperf/policies/blob/master/submission_rules.adoc[here]. The MLPerf name and logo are trademarks. In order to refer to a result using the MLPerf name, the result must conform to the letter and spirit of the rules specified in this document. The MLPerf organization reserves the right to solely determine if a use of its name or logo is acceptable. === Definitions (read this section carefully) The following definitions are used throughout this document: _Performance_ always refers to execution speed. _Quality_ always refers to a model’s ability to produce “correct” outputs. A _system_ consists of a defined set of hardware resources such as processors, memories, disks, and interconnect. It also includes specific versions of all software such as operating system, compilers, libraries, and drivers that significantly influences the running time of a benchmark, excluding the ML framework. A _framework_ is a specific version of a software library or set of related libraries, possibly with associated offline compiler, for training ML models using a system. Examples include specific versions of Caffe2, MXNet, PaddlePaddle, pyTorch, or TensorFlow. A _benchmark_ is an abstract problem that can be solved using ML by training a model based on a specific dataset or simulation environment to a target quality level. A _suite_ is a specific set of benchmarks. A _division_ is a set of rules for implementing benchmarks from a suite to produce a class of comparable results. A _reference implementation_ is a specific implementation of a benchmark provided by the MLPerf organization. A _benchmark implementation_ is an implementation of a benchmark in a particular framework by a user under the rules of a specific division. A _submission implementation set_ is a set of benchmark implementations for one or more benchmarks from a suite under the rules of a specific division using the same framework. A _run_ is a complete execution of an implementation on a system, training a model from initialization to the quality target. A _run result_ is the wallclock time required for a run. A _reference result_ is the result provided by the MLPerf organization for each reference implementation A _benchmark result_ is the mean of a benchmark-specific number of run results, dropping the highest and lowest results. The result is then normalized to the reference result for that benchmark. Normalization is of the form (reference result / benchmark result) such that a better benchmark result produces a higher number. A _submission result set_ is a one benchmark result for each benchmark implementation in a submission implementation set. A _submission_ is a submission implementation set and a corresponding submission result set. A _custom summary result_ is the weighted geometric mean of an arbitrary set of results from a specific submission. MLPerf endorses this methodology for computing custom summary results but does not endorse any official summary result. == General rules The following rules apply to all benchmark implementations. === Strive to be fair Benchmarking should be conducted to measure the framework and system performance as fairly as possible. Ethics and reputation matter. === System and framework must be consistent The same system and framework must be used for a submission result set. Note that the reference implementations do not all use the same framework. === Benchmark detection is not allowed The framework and system should not detect and behave differently for benchmarks. === Pre-training is not allowed Unless part of the definition of a benchmark, the implementation should not encode any information about the content of the dataset or a successful model’s state in any form. High-level statistical information about the dataset, such as distribution of sizes, may be used. For benchmarks which are defined as starting from a fixed set of weights, such as a checkpoint or backbone, the implementation should start from the weights provided in the benchmark reference definition, or if that is not posssible, provide information and code sufficient for reproducing how those starting weights were obtained. For v0.7, sets of weights used in v0.6 are allowed. == Benchmarks The benchmark suite consists of the benchmarks shown in the following table. |=== |Area|Problem |Dataset |Vision |Image classification |ImageNet | |Image segmentation (medical) |KiTS19 | |Object detection (light weight) |COCO | |Object detection (heavy weight) |COCO |Language |Speech recognition |LibriSpeech | |NLP |Wikipedia 2020/01/01 |Commerce |Recommendation |1TB Click Logs |Research |Reinforcement learning |Go |=== The MLPerf organization provides a reference implementation of each benchmark, which includes the following elements: Code that implements the model in a framework. A plain text “README.md” file that describes: * Problem ** Dataset/Environment ** Publication/Attribution ** Data preprocessing ** Training and test data separation ** Training data order ** Test data order ** Simulation environment (RL models only) ** Steps necessary for reproducing the initial set of weights, if an initial set of non-standard weights is used. For v0.7, weights from v0.6 may be used without this information. ** Publication/Attribution ** List of layers ** Weight and bias initialization ** Loss function ** Optimizer * Quality ** Quality metric ** Quality target ** Evaluation frequency (training items between quality evaluations) ** Evaluation thoroughness (test items per quality evaluation) * Directions ** Steps to configure machine ** Steps to download and verify data ** Steps to run and time A “download_dataset” script that downloads the dataset. A “verify_dataset” script that verifies the dataset against the checksum. A “run_and_time” script that executes the benchmark and reports the wall-clock time. == Divisions There are two divisions of the benchmark suite, the Closed division and the Open division. === Closed Division The Closed division requires using the same preprocessing, model, training method, and quality target as the reference implementation. The closed division models and quality targets are: |=== |Area |Problem |Model |Target |Vision |Image classification |ResNet-50 v1.5 |75.90% classification | |Image segmentation (medical) |U-Net3D |0.908 Mean DICE score | |Object detection (light weight) |SSD |23.0% mAP | |Object detection (heavy weight) |Mask R-CNN |0.377 Box min AP and 0.339 Mask min AP |Language | Speech recognition | RNN-T | 0.058 Word Error Rate | |NLP |BERT |0.720 Mask-LM accuracy |Commerce |Recommendation |DLRM |0.8025 AUC |Research |Reinforcement learning |Mini Go (based on Alpha Go paper) |50% win rate vs. checkpoint |=== Closed division benchmarks must be referred to using the benchmark name plus the term Closed, e.g. “for the Image Classification Closed benchmark, the system achieved a result of 7.2.” === Open Division The Open division allows using arbitrary training data, preprocessing, model, and/or training method. However, the Open division still requires using supervised or reinforcement machine learning in which a model is iteratively improved based on training data, simulation, or self-play. Open division benchmarks must be referred to using the benchmark name plus the term Open, e.g. “for the Image Classification Open benchmark, the system achieved a result of 7.2.” == Basics === Random numbers CLOSED: Random numbers must be generated using stock random number generators. Random number generators may be seeded from the following sources: * Clock * System source of randomness, e.g. /dev/random or /dev/urandom * Another random number generator initialized with an allowed seed Random number generators may be initialized repeatedly in multiple processes or threads. For a single run, the same seed may be shared across multiple processes or threads. OPEN: Any random number generation may be used. === Numerical formats CLOSED: The numerical formats fp64, fp32, tf32, fp16, bfloat16, Graphcore FLOAT 16.16, int8, uint8, int4, and uint4 are pre-approved for use. Additional formats require explicit approval. Scaling may be added where required to compensate for different precision. Reference Convergence Points must be obtained using FP32 precision, or FP32 emulation with explanation of the methodology for emulation. OPEN: Any format and scaling may be used. === Epoch numbering Epochs should always be numbered from 1. === Result rounding Public results should be rounded normally. == Data Set === Data State at Start of Run CLOSED: Each reference implementation includes a script to download the input dataset and script to verify the dataset using a checksum. The data must then be preprocessed in a manner consistent with the reference implementation, excepting any transformations that must be done for each run (e.g. random transformations). The data may also be reformatted for the target system provided that the reformatting does not introduce new information or introduce duplicate copies of data. OPEN: Any public dataset may be used for training the model, however the evaluation data must be drawn from the benchmark dataset in a manner consistent with the reference. You must flush the cache or restart the system prior to benchmarking. Data can start on any durable storage system such as local disks and cloud storage systems. This explicitly excludes RAM. === Preprocessing During the Run Only preprocessing that must be done for each run (e.g. random transformations) must be timed. CLOSED: The same preprocessing steps as the reference implementation must be used. OPEN: Any preprocessing steps are allowed for training data. However, each datum must be preprocessed individually in a manner that is not influenced by any other data. The evaluation data must be preprocessed in a manner consistent with reference. === Data Representation CLOSED: Images must have the same size as in the reference implementation. Mathematically equivalent padding of images is allowed. CLOSED: For benchmarks with sequence inputs, you may choose a length N and either truncate all examples to length N or throw out all examples which exceed length N. This must be done uniformly for all examples. This may only be done on the training set and not the evaluation set. CLOSED: Two ways to represent the Mask R-CNN mask are permitted. One is a polygon and the other is a scalable bitmask. OPEN: The closed division data representations restrictions only apply at the start of the run. Data may be represented in an arbitrary fashion during the run. === Other Uses of Data Input encoding data, such as language vocabulary, or the set of possible labels may used during pre-processing or execution without counting as ""touching the training data"" for timing purposes. === Training and Test Sets CLOSED: If applicable, the dataset must be separated into training and test sets in the same manner as the reference implementation. OPEN: If applicable, the test dataset must be extracted in the same manner as the reference implementation. The training data set may not contain data that appears in the test set. === Training Data Order CLOSED: the training and test data must be traversed in the same conceptual order as the reference implementation. For instance, the data might be traversed sequentially or randomly with uniform distribution. Batch size, shard size, and the random number generator will affect order. Where data pipelines randomly order data, arbitrary sharding, batching, and packing are allowed provided that (1) the data is still overall randomly ordered and not ordered to improve convergence and (2) each datum still appears exactly once. Modifications to data order and/or batching must be presented to the SWG group in advance of the submission deadline for approval if they could affect the ability to borrow hyperparameters and/or approximately follow the learning rate schedule defined by the RCPs. OPEN: The training data may be traversed in any order. The test data must be traversed in the same order as the reference implementation. == RL Environment CLOSED: The implementation must use the same RL algorithm and simulator or game as the reference implementation, with the same parameters. OPEN: The implementation may use a different RL algorithm but must use the same simulator or game with the same parameters. If the reference implementation generates all data online, the Open division implementation must also generate all data online. It is allowed and encouraged to parallelize and otherwise optimize (e.g. by implementing in a compiled language) the RL environment provided that the semantics are preserved. == Model CLOSED: The benchmark implementation must use the same model as the reference implementation, as defined by the remainder of this section. OPEN: The benchmark implementation may use a different model. === Graph Definition CLOSED: Each of the current frameworks has a graph that describes the operations performed during the forward propagation of training. The frameworks automatically infer and execute the corresponding back-propagation computations from this graph. Benchmark implementations must use the same graph as the reference implementation. === Weight and Bias Initialization CLOSED: Weights and biases must be initialized using the same constant or random value distribution as the reference implementation, unless a pre-trained set of weights, such as a checkpoint or backbone, is used by the reference. OPEN: Weights and biases must be initialized using a consistent constant or random value distribution. === Graph Execution CLOSED: Frameworks are free to optimize the non-weight parts of the computation graph provided that the changes are mathematically equivalent. So optimizations and graph / code transformations of the flavor of dead code elimination, common subexpression elimination, loop-invariant code motion, and recomputation of node state are entirely allowed. OPEN: Frameworks are free to alter the graph. == Training Loop === Hyperparameters CLOSED: By default, the hyperparameters must be the same as the reference. Hyperparameters include the optimizer used and values like the regularization norms and weight decays. The implementation of the optimizer must match the optimizer specified in the Appendex: Allowed Optimizer. The Appendex lists which optimizers in the popular deep learning frameworks are compliant by default. If a submission uses an alternate implementation, the submitter must describe the optimizer's equation and demonstrate equivalence with the approved optimizers on that list. The following table lists the tunable hyperparameters for each allowed model,optimizer combination. The value of each tunable hyperparameter must meet the listed constraint. The MLPerf verifier scripts checks all hyperparameters except those with names marked with asterisks. If a hyperparameter is marked with one asterisk, it must be checked manually. If a hyperparameter is marked with two asterisks, it is also not logged and it must be checked manually in the code. If the verifier and the constraints in this table differ, the verifier (specifically, the version on the date of submission unless otherwise decided by the review committee) is the source of truth. |=== |Model |Optimizer |Name |Constraint |Definition |Reference Code |bert |lamb |global_batch_size |unconstrained |The glboal batch size for training. |--train_batch_size |bert |lamb |opt_base_learning_rate |unconstrained |The base learning rate. |--learning_rate |bert |lamb |opt_epsilon |unconstrained |adam epsilon |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L75[reference code] |bert |lamb |opt_learning_rate_training_steps |unconstrained |Step at which your reach the lowest learning late |link:https://github.com/mlperf/training/blob/master/language_model/tensorflow/bert/run_pretraining.py#L64[reference code] |bert |lamb |opt_learning_rate_warmup_steps |unconstrained |""num_warmup_steps"" |link:https://github.com/mlperf/training/blob/master/language_model/tensorflow/bert/optimization.py#L34[reference code] |bert |lamb |num_warmup_steps |unconstrained |Number of steps for linear warmup. |--num_warmup_steps |bert |lamb |start_warmup_step |unconstrained |--start_warmup_step |--start_warmup_step |bert |lamb |opt_lamb_beta_1 |unconstrained |adam beta1 |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L73[reference code] |bert |lamb |opt_lamb_beta_2 |unconstrained |adam beta2 |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L74[reference code] |bert |lamb |opt_lamb_weight_decay_rate |unconstrained |Weight decay |link:https://github.com/mlperf/training/blob/fb058e3849c25f6c718434e60906ea3b0cb0f67d/language_model/tensorflow/bert/optimization.py#L72[reference code] |dlrm |sgd |global_batch_size |unconstrained |global batch size | |dlrm |sgd |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/facebookresearch/dlrm/blob/master/dlrm_s_pytorch.py#L492[reference code] |dlrm |sgd |opt_learning_rate_warmup_steps |unconstrained |Number to steps go from 0 to sgd_opt_base_learning_rate with a linear warmup |See PR (From Intel and NV, TODO Link) |dlrm |sgd |lr_decay_start_steps |unconstrained |step at which you start poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_base_learning_rate |unconstrained |learning rate at the start of poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_learning_rate_decay_poly_power |2 |power of the poly decay |See PR (From Intel and NV, TODO Link) |dlrm |sgd |sgd_opt_learning_rate_decay_steps |unconstrained |the step at which you reach the end learning rate |See PR (From Intel and NV, TODO Link) |maskrcnn |sgd |global_batch_size |arbitrary constant |global version of reference SOLVER.IMS_PER_BATCH |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/build.py#L112[reference code] |maskrcnn |sgd |opt_learning_rate_decay_factor$$*$$ |fixed to reference (0.1) |learning rate decay factor |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L13[reference code] |maskrcnn |sgd |opt_learning_rate_decay_steps$$*$$ |(60000, 80000) * (1 + K / 10) * 16 / global_batch_size where K is integer |Steps at which learning rate is decayed |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L26[reference code] |maskrcnn |sgd |opt_base_learning_rate |0.02 * K for any integer K |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L12[reference code] |maskrcnn |sgd |max_image_size$$*$$ |fixed to reference |Maximum size of the longer side |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/transforms/build.py#L8[reference code] |maskrcnn |sgd |min_image_size$$*$$ |fixed to reference |Maximum size of the shorter side |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/data/transforms/build.py#L7[reference code] |maskrcnn |sgd |num_image_candidates$$*$$ |1000 or 1000 * batches per chip |tunable number of region proposals for given batch size |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L183[reference code] |maskrcnn |sgd |opt_learning_rate_warmup_factor |unconstrained |the constant factor applied at learning rate warm up |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L28[reference code] |maskrcnn |sgd |opt_learning_rate_warmup_steps |unconstrained |number of steps for learning rate to warm up |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/solver/build.py#L29[reference code] |maskrcnn |sgd |num_image_candidates$$*$$ |(1000 or 2000) or (1000 * batches per chip) |tunable number of region proposals for given batch size |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L183[reference code] |minigo |sgd |train_batch_size |integer > 0 |Batch size to use for training |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L47[reference code] |minigo |sgd |lr_boundaries |unconstrained |The number of steps at which the learning rate will decay |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L67[reference code] |minigo |sgd |lr_rates |unconstrained |The different learning rates |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/dual_net.py#L70[reference code] |minigo |sgd |actual_selfplay_games_per_generation |integer >= 8192 (min_selfplay_games_per_generation) |""NOT A HYPERPARAMETER, CANNOT BE 'BORROWED' during review"" Implicit (LOG ONLY) - total number of games played per epoch; many parameters can impact this, varies per iteration |N/A |minigo |sgd |min_selfplay_games_per_generation$$*$$ |fixed to reference (8192) |Minimum number of games to play for each training iteration |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/reinforcement/tensorflow/minigo/ml_perf/train_loop.py#L51[reference code] |resnet |lars |lars_opt_base_learning_rate |arbitrary constant |Base ""plr"" in the PR linked. |link:https://github.com/mlperf/training/pull/342/files#[reference code] |resnet |lars |lars_opt_end_learning_rate$$*$$ |fixed to reference |end learning rate for polynomial decay, implied mathemetically from other HPs |N/A |resnet |lars |lars_opt_learning_rate_decay_poly_power$$*$$ |fixed to reference |power of polynomial decay, no link needed since not tunable |N/A |resnet |lars |lars_epsilon$$*$$ |Fixed to reference |epsilon in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_learning_rate_warmup_epochs |arbitrary constant |w_epochs in PR |link:https://github.com/mlperf/training/pull/342/files#[reference code] |resnet |lars |lars_opt_momentum | 0.9 for batch<32k, otherwise arbitrary constant |momentum in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_weight_decay |(0.0001 * 2 ^ N) where N is any integer |weight_decay in reference |link:https://github.com/mlperf/training/pull/342/files#diff-b7db7d58acb8134acb65b4d1d60b8e90R49[reference code] |resnet |lars |lars_opt_learning_rate_decay_steps |unconstrained |num_epochs in reference |link:https://github.com/mlperf/training/blob/master/image_classification/tensorflow/official/resnet/resnet_run_loop.py[reference code] |resnet |lars |global_batch_size |unconstrained |global batch size in reference |link:https://github.com/mlperf/training/blob/00570abf77d351e474d57830014f6a3e501dece1/image_classification/tensorflow/official/utils/arg_parsers/parsers.py#L158[reference code] |resnet |lars |label smoothing$$*$$$$*$$ |0 or 0.1 | TODO |TODO |resnet |lars |truncated norm initialization$$*$$$$*$$ |boolean | TODO |TODO |resnet |sgd |global_batch_size |arbitrary constant |reference --batch_size |See LARS |resnet |sgd |sgd_opt_base_learning_rate |0.001 * k where is an integer |the learning rate |See LARS |resnet |sgd |sgd_opt_end_learning_rate |10^-4 |end learning rate for polynomial decay, implied mathemetically from other HPs |See LARS |resnet |sgd |sgd_opt_learning_rate_decay_poly_power |2 |power of polynomial decay, no link needed since not tunable |See LARS |resnet |sgd |sgd_opt_learning_rate_decay_steps |integer >= 0 |num_epochs in reference |See LARS |resnet |sgd |sgd_opt_weight_decay |(0.0001 * 2 ^ N) where N is any integer |Weight decay, same as LARS. |See LARS |resnet |sgd |sgd_opt_momentum |0.9 |Momentum for SGD. |See LARS |resnet |sgd |model_bn_span |arbitrary constant |number of samples whose statistics a given BN layer uses to normalize a training minibatch (may be just the portion of global_batch_size per device, but also may be aggregated over several devices) |See LARS |resnet |sgd |opt_learning_rate_warmup_epochs |integer >= 0 |number of epochs needed for learning rate warmup |See LARS |resnet |sgd |label smoothing$$*$$$$*$$ |0 or 0.1 | TODO |TODO |resnet |sgd |truncated norm initialization$$*$$$$*$$ |boolean | TODO |TODO |resnet |lars/sgd |opt_name |""lars"" or ""sgd"" |The optimizer that was used. | |rnnt |lamb |global_batch_size |unconstrained |reference --batch_size |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L270-L271[reference code] |rnnt |lamb |opt_name |""lamb"" |The optimizer that was used. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L357[reference code] |rnnt |lamb |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L358[reference code] |rnnt |lamb |opt_lamb_epsilon |1e-9 |LAMB epsilon |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L359[reference code] |rnnt |lamb |opt_lamb_learning_rate_decay_poly_power |unconstrained |Exponential decay rate |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L360[reference code] |rnnt |lamb |opt_lamb_learning_rate_hold_epochs |unconstrained |Number of epochs when LR schedule keeps the base learning rate value |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L362[reference code] |rnnt |lamb |opt_learning_rate_warmup_epochs |unconstrained |Number of epochs when LR linearly increases from 0 to base learning rate |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L361[reference code] |rnnt |lamb |opt_weight_decay |1e-3 |L2 weight decay |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L372[reference code] |rnnt |lamb |opt_lamb_beta_1 |unconstrained |LAMB beta 1 |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L363[reference code] |rnnt |lamb |opt_lamb_beta_2 |unconstrained |LAMB beta 2 |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L364[reference code] |rnnt |lamb |opt_gradient_clip_norm |1 or inf |Gradients are clipped above this norm threshold. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L365[reference code] |rnnt |lamb |opt_gradient_accumulation_steps |unconstrained |Numer of fwd/bwd steps between optimizer step. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L222[reference code] |rnnt |lamb |opt_learning_rate_alt_decay_func |True |whether to use alternative learning rate decay function |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/common/optimizers.py#L20-L49[reference code] |rnnt |lamb |opt_learning_rate_alt_warmup_func |True |whether to use alternative learning rate warmup function |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L367[reference code] |rnnt |lamb |opt_lamb_learning_rate_min |1e-5 |LR schedule doesn't set LR values below this threshold |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L368[reference code] |rnnt |lamb |train_samples |unconstrained |Number of training samples after filtering out samples longer than data_train_max_duration |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L337[reference code] |rnnt |lamb |eval_samples |2703 |Number of evaluation samples |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L338[reference code] |rnnt |lamb |data_train_max_duration |unconstrained |Samples longer than this number of seconds are not included to training dataset |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L252-L253[reference code] |rnnt |lamb |data_train_num_buckets |unconstrained |Training dataset is split to this number of buckets |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L293[reference code] |rnnt |lamb |data_train_speed_perturbation_min |0.85 |Input audio is resampled to a random rample rate not less than this fraction of original sample rate. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L256-L257[reference code] |rnnt |lamb |data_train_speed_perturbation_max |1.15 |Input audio is resampled to a random rample rate not greater than this fraction of original sample rate. |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L254-L255[reference code] |rnnt |lamb |data_spec_augment_freq_n |2 |Number of masks for frequency bands |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L258-L259[reference code] |rnnt |lamb |data_spec_augment_freq_min |0 |Minimum number of frequencies in a single mask |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L260-L261[reference code] |rnnt |lamb |data_spec_augment_freq_max |20 |Maximum number of frequencies in a single mask |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L262-L263[reference code] |rnnt |lamb |data_spec_augment_time_n |10 |Number of masks for time band |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L264-L265[reference code] |rnnt |lamb |data_spec_augment_time_min |0 |Minimum number of masked time steps as a fraction of all steps |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L266-L267[reference code] |rnnt |lamb |data_spec_augment_time_max |0.03 |Maximum number of masked time steps as a fraction of all steps |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L268-L269[reference code] |rnnt |lamb |model_eval_ema_factor |unconstrained |Smoothing factor for Exponential Moving Average |See link:https://github.com/mlcommons/training/blob/651e7c47bcbd7f4708d633afa567205a826438f1/rnn_speech_recognition/pytorch/train.py#L395[reference code] |rnnt |lamb |model_weights_initialization_scale |unconstrained |After random initialization of weight and bias tensors, all are scaled with this factorAfter random initialization of weight and bias tensors, all are scaled with this factor |See link:https://github.com/mwawrzos/training/blob/2126999a1ffff542064bb3208650a1e673920dcf/rnn_speech_recognition/pytorch/train.py#L342[reference code] |ssd |sgd |global_batch_size |arbitrary constant |reference --batch-size |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L23[reference code] |ssd |sgd |model_bn_span |integer >= 1 |number of samples whose statistics a given BN layer uses to normalize a training minibatch (may be just the portion of global_batch_size per device, but also may be aggregated over several devices) |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L335[reference code] |ssd |sgd |opt_learning_rate_warmup_factor |Integer >= 0 |the constant factor applied at learning rate warm up |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L45[reference code] |ssd |sgd |opt_learning_rate_warmup_steps |integer >= 1 |number of steps for learning rate to warm up |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L43[reference code] |ssd |sgd |opt_weight_decay |arbitrary constant |L2 weight decay |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L40[reference code] |ssd |sgd |opt_base_learning_rate |unconstrained |base learning rate, this should be the learning rate after warm up and before decay |link:https://github.com/mlperf/training/blob/master/single_stage_detector/ssd/train.py#L47[reference code] |ssd |sgd |max_samples |1 or 50 |maximum number of samples attempted when generating a training patch for a given IoU choice |link:https://github.com/mlperf/training/pull/367/commits/e6fbbb323adb7d1521cc5b7d7371f2e4461ece59#diff-591431110d6b55f5afe595b96253fddbR111[reference code] |ssd |sgd |opt_learning_rate_decay_boundary_epochs |[40, 50] * (1 + k/10) for some integer k |Epochs at which the learning rate decays |link:https://github.com/mlperf/training/blob/e6fbbb323adb7d1521cc5b7d7371f2e4461ece59/single_stage_detector/ssd/train.py#L48[reference code] |unet3d |sgd |global_batch_size |unconstrained |global batch size |reference --batch_size |unet3d |sgd |opt_base_learning_rate |unconstrained |base learning rate |reference --learning_rate |unet3d |sgd |opt_momentum |unconstrained |SGD momentum |reference --momentum |unet3d |sgd |opt_learning_rate_warmup_steps |unconstrained |number of epochs needed for learning rate warmup|reference --lr_warmup_epochs |unet3d |sgd |opt_initial_learning_rate |unconstrained |initial learning rate (for LR warm up) |reference --init_learning_rate |unet3d |sgd |opt_learning_rate_decay_steps |unconstrained |epochs at which the learning rate decays |reference --lr_decay_epochs |unet3d |sgd |opt_learning_rate_decay_factor |unconstrained |factor used for learning rate decay |reference --lr_decay_factor |unet3d |sgd |opt_weight_decay |unconstrained |L2 weight decay |reference --weight_decay |unet3d |sgd |training_oversampling |fixed to reference |training oversampling |reference --oversampling |unet3d |sgd |training_input_shape |fixed to reference |training input shape |reference --input_shape |unet3d |sgd |evaluation_overlap |fixed to reference |evaluation sliding window overlap |reference --overlap |unet3d |sgd |evaluation_input_shape |fixed to reference |evaluation input shape |reference --val_input_shape |unet3d |sgd |data_train_samples |fixed to reference |number of training samples | N/A |unet3d |sgd |data_eval_samples |fixed to reference |number of evaluation samples | N/A |=== OPEN: Hyperparameters and optimizer may be freely changed. === Hyperparameter Borrowing Submitters are expected to use their best efforts to submit with optimal hyperparameters for their system. The intent of Hyperparameter Borrowing is to allow a submitter to update their submission to reflect what they would have submitted had they known about more optimal hyperparameters before submitting, without knowing any other info (ie the performance of other submissions). During the review period as described in the Submission Rules, a submitter may replace the hyperparameters, once per benchmark entry, in their implementation of a benchmark with hyperparameters from another submitter's implementation of the same benchmark. By default, they may change batch size (local batch size, global batch size, batchnorm span), but must replace all other hyperparameters as a group. With evidence that the resulting model, using the same batch size as the other submitter's implementation, converges worse in terms of epochs required, the submitter may make a minimum number of additional hyperparameter changes for the purpose of improving convergence and achieving comparable, but not better, convergence in epochs compared to the other submitter's implementation, but preserving any difference in convergence that may exist due to precision choices. In this situation, the other submitter's implementation is considered the reference, and the new submitter must match the convergence behavior of the other submitter in a similar way as we compare any submission to the reference. A resubmission of a benchmark with borrowed hyperparameters must use the same software (with the exceptions listed in the Software Adoption section of this document), system and system configuration (accelerators, NICs etc) as the original submission. The largest scale submission for a benchmark from a given system may be resubmitted with borrowed hyperparameters using a change of scale on that system, but only if the new scale is either larger, or enables the resubmission to achieve a faster run result. In addition, the new scale must not be larger than the largest scale used in an original submission of at least one of the benchmarks on that system in this round. === Loss function CLOSED: The same loss function used in the reference implementation must be used. OPEN: Any loss function may be used. Do not confuse the loss function with target quality measure. === Quality measure Each run must reach a target quality level on the reference implementation quality measure. By default, the time to evaluate the quality is included in the wallclock time. However, if the reference implementation generates timestamped checkpoints and evaluates the quality after the clock has been stopped, then an implementation may either perform evaluation on-the-clock or generate timestamped checkpoints, evaluate them after the clock has been stopped, and update the clock stopped time to the timestamp of the first passing checkpoint. The checkpoint timestamp may be any time after the last weight value included in the checkpoint is updated. CLOSED: The same quality measure as the reference implementation must be used. The quality measure must be evaluated at the same frequency (in terms of number of training items between test sets) and at least as thoroughly (in terms of number of tests per set) as in the reference implementation. Where applicable, the required evaluation point may be rounded up to the nearest batch size. Typically, a test consists of comparing the output of one forward pass through the network with the desired output from the test set. |=== |Area |Problem |Model|Evaluation frequency |Vision |Image classification |Resnet-50 v1.5|Every 4 epochs with offset 0 or 1 or 2 or 3 | |Image segmentation (medical) |U-Net3D | Starting at `CEILING(1000*168/samples_per_epoch)` epochs, then every `CEILING(20*168/samples_per_epoch)` epochs. Where `samples_per_epoch` is the number of samples processed in a given epoch assuming that in the case of uneven batches the last batch is padded, e.g. `CEILING(168/global_batch_size) * global_batch_size`. | |Object detection (light weight) |SSD|Every 5 epochs | |Object detection (heavy weight) |Mask R-CNN|Every 1 epoch |Language|Speech recognition |RNN-T|Every 1 epoch | |NLP |BERT| eval_interval_samples=FLOOR(0.05*(230.23*GBS+3000000), 25000), skipping 0 |Commerce|Recommendation |DLRM|Every 102400 samples |Research|Reinforcement learning |Mini Go|Every 1 epoch |=== OPEN: An arbitrary stopping criteria may be used, including but not limited to the closed quality measure, a different quality measure, the number of epochs, or a fixed time. However, the reported results must include the geometric mean of the final quality as measured by the closed quality measure. Check points can be created at the discretion of submitter. No check points are required to be produced or retained. === Equivalence exceptions The CLOSED division allows limited exemptions to mathematical equivalence between implementations for pragmatic purposes, including: * Different methods can be used to add color jitter as long as the methods are of a similar distribution and magnitude to the reference. * If data set size is not evenly divisible by batch size, one of several techniques may be used. The last batch in an epoch may be composed of the remaining samples in the epoch, may be padded, or may be a mixed batch composed of samples from the end of one epoch and the start of the next. If the mixed batch technique is used, quality for the ending epoch must be evaluated after the mixed batch. If the padding technique is used, the first batch may be padded instead of the last batch. * Values introduced for padding purposes may be reflected in batch norm computations. * Adam optimizer implementations may use the very small value epsilon to maintain mathematical stability in slightly different ways, provided that methods are reviewed and approved in advance. One such method involves squaring the value of epsilon and moving epsilon inside the square root in the parameter update equation. * Distributed batch normalization is allowed. Additional exemptions need to be explicitly requested and approved in advance. In general, exemptions may be approved for techniques that are common industry practice, introduce small differences that would be difficult to engineer around relative to their significance, and do not substantially decrease the required computation. Over time, MLPerf should seek to help the industry converge on standards and remove exemptions. The OPEN division does not restrict mathematical equivalence. == Software Adoption == For a given round of MLPerf, the ""canonical version"" of a software component shall be defined as the public version as of 14 days before submission. If the software is open source, the canonical version shall be the one compiled with the default compilation options. If a system software provider submits with a component whose version is other than the canonical version, then other submitters using the same component are allowed to update their submission to use that version. Those other submitters must resubmit with the updated system software before the resubmission deadline during the review period. Software adoption applies only to system software, only to the version used by the software provider’s submission, and explicitly does not cover benchmark implementations. Benchmark implementations should be borrowed as a whole only if the software provider’s submission introduces new APIs. [#section-run-results] == Run Results A run result consists of a wall-clock timing measurement for a contiguous period that includes model initialization in excess of a maximum initialization time, any data preprocessing required to be on the clock, using the dataset to train the model, and quality evaluation unless specified otherwise for the benchmark. Prior to starting the clock, a system may use a maximum of 20 minutes of model initialization time. Model initialization time begins when the system first begins to construct or execute the model. This maximum initialization time is intended to ensure that model initialization is not disproportionate on large systems intended to run much larger models, and may be adjusted in the future with sufficient evidence. The clock must start before any part of the system touches the dataset or when the maximum model initialization time is exceeded. The clock may be stopped as soon as any part of the system determines target accuracy has been reached. The clock may not be paused during the run. == Benchmark Results Each benchmark result is based on a set of run results. The number of results for each benchmark is based on a combination of the variance of the benchmark result, the cost of each run, and the likelihood of convergence. |=== |Area|Problem |Minimum Number of Runs |Vision |Image classification |5 | |Image segmentation (medical) | 40 | |Object detection (light weight) |5 | |Object detection (heavy weight) |5 |Language |NLP |10 | |Speech recognition |10 |Commerce |Recommendation |5 |Research |Reinforcement learning |10 |=== Each benchmark result is computed by dropping the fastest and slowest runs, then taking the mean of the remaining times. For this purpose, a single non-converging run may be treated as the slowest run and dropped. A benchmark result is invalid if there is more than one non-converging run. In the case of UNET3D, due to large variance, 40 runs are required. Out of the 40 runs, the 4 fastest and 4 slowest are dropped. There can be maximum of 4 non-converging runs. A run is classified as non-converged if the target quality metric is not reached within `CEILING(10000*168/samples_in_epoch)` epochs. Each benchmark result should be normalized by dividing the reference result for the corresponding reference implementation by the benchmark result. This normalization produces higher numbers for better results, which better aligns with human intuition. === Scoring An MLPerf submission score is intended to represent the median expected result across a large number of runs. To reduce statistical variance and the potential to cherry pick results, each benchmark submission is composed of a set of N independent runs, with N chosen based on the observed variation of the benchmark, as described in the table above. Running multiple iterations of N independent runs with the goal of validating that the submission is close to a median result is encouraged but not required. Running multiple iterations of N runs to try find the lowest one is against the spirit of MLPerf and is prohibited – see Section 2.1, “Strive to be fair”. Results that appear to be too far away from a median result may be rejected. As a more computationally efficient method of validating that a submission is close to the median result, it is also allowed to run M>N independent runs as a group and to designate N consecutive runs from the group as the runs to be used for scoring, provided that the submitter chooses the N consecutive runs that are closest to the median result. For the purposes of calculating the median, sets of N consecutive runs that would create an invalid benchmark result should be included in the median calculation as ""infinite"" scores. If the median set would be an invalid benchmark result, the entire result is invalid. Submitting the full run set (vs just the N runs used for scoring) as a reference is optional, but may be required in the future. For purposes of this scoring, ""consecutive"" is defined as an objective and deterministic method, such as submission timestamps. Submitters are not allowed to pick different orderings to improve their score. Runs may go in parallel on the submitter's compute resources, as long as there is a way to objectively and deterministically sort the runs, for example by timestamp. An example could be for a benchmark with N=5 runs, a submitter could ahead of time pick M=10, launch 10 runs on their compute resources, sort the 10 runs by their launch time stamp, then take a sliding window of 5 consecutive runs over those 10 runs. That sliding window would create 6 possible sets of 5 runs. Each of those 6 sets would be olympically scored, and the set with the median runtime would be submitted as that submitter's score. Any failed runs within those 10 runs would count as infinity time and need to be included in the olympic scoring (could be thrown away as the slowest score). It is recommended that a submitter keep the logs for all M runs, because the review committee may ask for the submitter to share the M logs during the review period. == Reference Convergence Points (RCPs) Reference Convergence Points are used to ensure that the convergence of the submission does not deviate from the convergence of the reference. We are interested in avoiding cases where the submission convergence is faster than the reference. Reference implementation convergence sets a lower bound on epoch convergence that a valid submission should not beat. From a statistical standpoint if the submission mean epochs to converge is significantly lower than the reference mean epochs to converge, then submission convergence points belong to a different population than the reference convergence points, and thus the submission should not be accepted. Compliance to reference convergence points is validated as follows * Reference implementations provide at least 2N epoch convergence numbers, where N is the number of submission runs needed for each benchmark. Since convergence is affected by batch size (larger batch size means slower convergence), reference implementations provide convergence data for a few different batch sizes. * Using the mean and standard deviation of the reference convergence we apply a 1-sided independent two-sample Student's t-test with unequal sample sizes, similar variances with p-value=0.05 (explained link:https://en.wikipedia.org/wiki/Student%27s_t-test#Equal_or_unequal_sample_sizes,_similar_variances_(1/2_%3C_sX1/sX2_%3C_2)[here]) to find the maximum acceptable speedup for submission convergence. * At submission time, the submission is matched to an RCP based on the submission batch size. ** If there is an RCP for that batch size then mean epochs to converge of the submission is extracted from submission logs. If this does not violate the maximum acceptable speedup condition when compared to the reference then the submission is accepted, otherwise it may be rejected. ** If there is no RCP for that batch size but there are RCPs for smaller and larger batch sizes an interpolated RCP is created, and the mean epochs to converge is compared against the interpolated RCP just like in the previous case ** If the submission batch size is larger than the batch size of any RCP the submitter must provide the missing RCPs by running the reference implementation with their batch size. ** If the submission batch size is smaller that the batch size of any RCP AND the convergence test against the RCP with the minimum batch size fails, then again the submitter must provide the missing RCPs by running the reference implementation with their batch size. Please refer to the related Appendix for examples that shed light to the RCP process. === RCP Rules and Guidelines Submitters are encouraged to run the RCP checker script prior to their submission to make sure they do not violate RCP limits. If a submission fails the RCP test, such as S2 in the Appendix, they have the option to submit with the --rcp_bypass parameter. This will allow the submission to upload, but the submitter must notify the results chair, and prepare for the audit process described in the link:https://github.com/mlcommons/policies/blob/master/submission_rules.adoc#auditing[policies document] but at review time the submitter should be able to justify why their submission is valid while it failed the RCP test. If a submission is missing the RCP for the batch size they are submitting, such as S4 and S6 in the Appendix they must provide the missing convergence points by making a PR in the logger. If not, the submission will not be accepted. All missing RCPs are due at submission time. RCPs are added by making a pull request into the RCP library in the logging repository. During hyperparameter borrowing, borrowers can use hyperparameters from submissions that passed or failed the RCP test. If their submission fails to pass the RCP test they can have it upload by using --rcp-bypass and then prepare for the audit decribed in the link:https://github.com/mlcommons/policies/blob/master/submission_rules.adoc#auditing[policies document] To extract submission convergence points, logs should report epochs as follows. For this round no RCP checks will be made for Minigo. |=== | Benchmark | Epoch reporting | RN50 | Epoch | BERT | Training sample (integer) | DLRM | 1 + Epoch / 20.0 (1.05, 1.1, 1.15...) | SSD | Epoch | Mask-RCNN | Epoch | RNN-T | Epoch | UNET3D | Epoch | Minigo | N/A |=== == Appendix: Benchmark Specific Rules * Image Classification ** The model may have 1000 or 1001 classes, where the 1001st is ""I don't know"" == Appendix: Allowed Closed Division Optimizers Analysis to support this can be found in the document ""MLPerf Optimizer Review"" in the MLPerf Training document area. TODO: locate the document and provide working link |=== | Benchmark | Algorithm | Framework | Allowed Optimizer | Image classification | LARS | PyTorch | [No compliant implementation] | | | TensorFlow | MLPERF_LARSOptimizer | | | MxNet | SGDwFASTLARS | Image classification | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | | | MxNet | [No compliant implementation] | Reinforcement learning| SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Object detection (heavy weight) | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Object detection (light weight) | SGD with Momentum | PyTorch | apex.optimizers.FusedSGD | | | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | NLP | LAMB | PyTorch | apex.optimizers.FusedLAMB | | | TensorFlow | tf.optimizers.LAMB | Speech recognition | LAMB | PyTorch | apex.optimizers.FusedLAMB | | | TensorFlow | tf.optimizers.LAMB | Recommendation | SGD | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | Image segmentation (medical) | SGD with Momentum | PyTorch | torch.optim.SGD | | | TensorFlow | tf.train.MomentumOptimizer | | | MXNet | mx.optimizer.NAG |=== == Appendix: v1.0 Specific Rules This section contains rules specific to the v1.0 round of MLPerf Training. These do not apply to future rounds, unless explicitly ratified as rules for those rounds, or unless these rules are promoted to official rules in previous sections of this document. === MaskRCNN backbone For v1.0 only, Mask-RCNN submitters may use the non-reference backbone located https://drive.google.com/drive/folders/1lGU_pP2Pr2k578DslciwE4AlOKm6dKCK?usp=sharing[here] with the understanding that it converges similarly to the reference backbone. If the non-reference backbone is shown to converge faster than the reference backbone at any scale on any submitted hyperparameter set, all uses of that backbone for any submitter are to be re-run with the reference backbone to have their submission published. For future rounds, the expectation is that all submitters will use the reference backbone, which will fixed at reference code freeze time. === BERT clip-normalization order For v1.0 only, BERT submissions may implement clip-norm either before or after inter-accelerator all-reduce. For future rounds, the expectation is that submissions must use clip-norm-after-reduce, to be consistent with most commonly used public BERT model repos. For performance consistency of at scale BERT submissions for v1.0, submitters are disallowed from using clip-norm-after-reduce to enable additional overlap of communication and math. If a submitter plans to use clip-norm-after-reduce for v1.0, they must notify the committee before the submission deadline, and be prepared to show code in their submission proving that they do not do overlap as a result of clip-norm-after-reduce. Furthermore, for simplicity, the RCPs for this round will use clip-norm-before-reduce. In theory, this could allow clip-norm-after-reduce submissions that converge faster than they should, but still not faster than clip-norm-before-reduce, but the Training Working Group feels that this is ok risk for v1.0, in interest of simplifying the RCPs for v1.0. === Compile time For v1.0 only, the allowed untimed compile time is increased from 20 minutes to 30 minutes. This is to enable new submitters to submit who were close to the 20 minute limit. The 20 minute number was chosen empirically for rounds prior to v1.0. For v1.1 and beyond, the training working group should make a data driven decision on what compile time is reasonable for real user applications. == Appendix: v1.1 Specific Rules This section contains rules specific to the v1.1 round of MLPerf Training. These do not apply to future rounds, unless explicitly ratified as rules for those rounds, or unless these rules are promoted to official rules in previous sections of this document. === BERT clip-normalization order For v1.0 only, BERT submissions may implement clip-norm either before or after inter-accelerator all-reduce. For future rounds, the expectation is that submissions must use clip-norm-after-reduce, to be consistent with most commonly used public BERT model repos. This exception from v1.0 was extended to v1.1 because of the tight schedule between rounds. === Preview Category For v1.1, we changed the policy documentation to say that a Preview submission needs to be available at the next submission after 140 days, not 180 days like it was before. However, this does not apply to Preview submissions from v1.0, which will still follow the 180 day policy. For v1.1 Preview submissions and beyond, the 140 day rule will apply. This is not necessarily an ""exception,"" but we are listing it here as a special case for the record. == Appendix: RCP Examples The RCP checking process is best illustrated with the following examples: Benchmark A requires 5 submission runs. The reference implementation provides (at least) 10 convergence points, let's say [16, 14, 16, 17, 16, 16, 15, 16, 15, 16] for batch size 128. The top and bottom run are excluded from the mean and standard deviation computation. So in this case the Mean = 15.75 epochs and Stdev = 0.43. Based on the t-test the maximum allowed speedup for p-value=0.05 is 3.53%. In other words the minimum mean epochs to converge for each submission with batch size 128 is 15.21. The reference also provides convergence points for batch size 256: [20, 21, 21, 20, 22, 22, 21, 21, 20, 20]. In this case Mean = 20.75, Stdev = 0.66 and based on the t-test the maximum allowed speedup for p-value=0.05 is 4.12%. In other words the minimum mean epochs to converge for batch-256 is 19.93. Let's consider now the following submission scenarios: * Submitter S1 makes a submission for A with batch size 128, and from the logs the epochs to converge are [15, 15, 15, 16, 16]. Excluding the top and bottom runs the mean epochs to converge is 15.33 (> 15.21), so S1 passes the RCP test for benchmark A, batch size 128. * Submitter S2 makes a submission for A with batch size 256, and from the logs the epochs to converge are [19, 19, 19, 20, 21]. Excluding the top and bottom runs the mean epochs to converge is 19.33 (< 19.93), so S2 fails the RCP test for benchmark A, batch size 256. * Submitter S3 makes a submission for A with batch size 192, and from the logs the epochs to converge are [17, 18, 18, 18, 20]. There are no RCPs for 192, but there are for larger and lower batch sizes. In this situation we find an interpolation of the mean and standard deviations for the RCPs at batch size 192. Mean = 18.25 and Stdev=0.547. Based on the t-test with p-value=0.05 the maximum allowed speedup is 3.68%. Exclusing the top and botton submission runs, the submission mean epochs to converge is 18, which is more than 18.25 / 1.0368, so the submission is accepted for batch size 192. * Submitter S4 makes a submission for A with batch size 512. Since there is neither RCP for that batch size, nor RCPs for larger batch sizes, S2 needs to provide convergence points by running the reference with that batch size. * Submitter S5 makes a submission for A with batch size 64 that meets the (stricter) convergence criteria for the RCP with the smallest batch size (128). In this case the submission is accepted. * Submitter S6 makes a submission for A with batch size 64 that does not meet the convergence criteria for the RCP with the smallest batch size (128). In this case S1 needs to provide convergence points by running the reference with batch size = 64. ",16288,True,2888.695566207312,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package spark.layouts { import flash.geom.ColorTransform; import flash.geom.Point; import flash.geom.Vector3D; import mx.core.IVisualElement; import mx.core.UIComponent; import spark.layouts.HorizontalAlign; import spark.layouts.VerticalAlign; import spark.primitives.supportClasses.GraphicElement; import spark.layouts.supportClasses.PerspectiveAnimationNavigatorLayoutBase; /** * A CarouselLayout class arranges the layout elements in a * sequence along an arc, with one of them at a time selected. * *

    The position of the elements is determined by the radii * radiusX, radiusY and radiusZ. * These can be properties can be set the negative values to produce * a ring of elements surrounding the view point.

    * *

    The rotation of the elements is determined by the * rotationX and rotationY properties.

    *
      *
    • If a value of ""none"" is used for a rotation property, * no rotation is applied to the element around the corresponding axis.
    • * *
    • If a value of ""standard"" is used for a rotation property, * the element will be rotated so that it faces outwards around the arc.
    • * *
    • If a value of ""reversed"" is used for a rotation property, * the element will be rotated so that it faces inwards around the arc.
    • *
    * * @mxml * *

    The <st:CarouselLayout> tag inherits all of the * tag attributes of its superclass, and adds the following tag attributes:

    * *
    	 *  <st:AccordionLayout
    	 *    Properties
    	 *    angle=""360""
    	 *    depthColor=""-1""
    	 *    depthColorAlpha=""1""
    	 *    horizontalAlign=""center|left|right""
    	 *    horizontalAlignOffset=""0""
    	 *    horizontalAlignOffsetPercent=""0""
    	 *    numUnselectedElements=""-1""
    	 *    radiusX=""100""
    	 *    radiusY=""0""
    	 *    radiusZ=""NaN""
    	 *    rotateX=""none|reversed|standard""
    	 *    rotateY=""none|reversed|standard""
    	 *    verticalAlign=""bottom|middle|top""
    	 *    verticalAlignOffset=""0""
    	 *    verticalAlignOffsetPercent=""0""
    	 *  />
    	 *  
    * * @includeExample examples/CarouselLayoutExample.mxml * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public class CarouselLayout extends PerspectiveAnimationNavigatorLayoutBase { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function CarouselLayout() { super( INDIRECT ); _transformCalculator = new TransformValues( this ); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private */ private var _transformCalculator : TransformValues; /** * @private */ private var _horizontalCenterMultiplier : Number; /** * @private */ private var _verticalCenterMultiplier : Number; /** * @private */ private var _elementHorizontalCenterMultiplier : Number; /** * @private */ private var _elementVerticalCenterMultiplier : Number; /** * @private */ private var _displayedElements : Vector. //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // angle //---------------------------------- /** * @private * Storage property for angle. */ private var _angle:Number = 360; /** * The segment of a circle to rotate the elements around. * * @default 360 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get angle():Number { return _angle; } /** * @private */ public function set angle( value:Number ) : void { if( _angle == value ) return; _angle = value; invalidateTargetDisplayList(); } //---------------------------------- // rotateX //---------------------------------- /** * @private * Storage property for rotateX. */ private var _rotateX:int = 0; [Inspectable(category=""General"", enumeration=""none,reversed,standard"", defaultValue=""none"")] /** * Whether rotation should be applied to the x axis of elements. * * @default true * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get rotateX():String { return _rotateX ? _rotateX < 0 ? ""reversed"" : ""standard"" : ""none""; } /** * @private */ public function set rotateX( value:String ) : void { var r:int; switch( value ) { case ""reversed"" : { r = -1; break; } case ""standard"" : { r = 1; break; } default : { r = 0; } } if( _rotateX == r ) return; _rotateX = r; invalidateTargetDisplayList(); } //---------------------------------- // rotateY //---------------------------------- /** * @private * Storage property for rotateY. */ private var _rotateY:int = 1; [Inspectable(category=""General"", enumeration=""none,reversed,standard"", defaultValue=""standard"")] /** * Whether rotation should be applied to the y axis of elements. * * @default true * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get rotateY():String { return _rotateY ? _rotateY < 0 ? ""reversed"" : ""standard"" : ""none""; } /** * @private */ public function set rotateY( value:String ) : void { var r:int; switch( value ) { case ""reversed"" : { r = -1; break; } case ""standard"" : { r = 1; break; } default : { r = 0; } } if( r == _rotateY ) return; _rotateY = r; invalidateTargetDisplayList(); } //---------------------------------- // depthColor //---------------------------------- /** * @private * Storage property for depthColor. */ private var _depthColor : int = -1; [Inspectable(category=""General"", defaultValue=""-1"")] /** * The color tint to apply to elements as their are moved back on the z axis. * *

    If a valid color is added to elements are tinted as they are moved * back on the z axis taking into account the depthColorAlpha * specified. If a value of -1 is set for the color no tinting is applied.

    * * @default -1 * * @see #depthColorAlpha * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get depthColor():int { return _depthColor; } /** * @private */ public function set depthColor( value:int ) : void { if( _depthColor == value ) return; _depthColor = value; invalidateTargetDisplayList(); } //---------------------------------- // depthColorAlpha //---------------------------------- /** * @private * Storage property for depthColorAlpha. */ private var _depthColorAlpha : Number = 1; [Inspectable(category=""General"", defaultValue=""1"")] /** * The alpha to be used for the color tint that is applied to elements * as their are moved back on the z axis. * * @default 1 * * @see #depthColor * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get depthColorAlpha():Number { return _depthColorAlpha; } /** * @private */ public function set depthColorAlpha( value:Number ) : void { if( _depthColorAlpha == value ) return; _depthColorAlpha = value; invalidateTargetDisplayList(); } //---------------------------------- // numUnselectedElements //---------------------------------- /** * @private * Storage property for numUnselectedElements. */ private var _numUnselectedElements : int = -1; [Inspectable(category=""General"", defaultValue=""-1"")] /** * The number of items to show either side of the selected item * are positioned around this element. * *

    Valid values are HorizontalAlign.LEFT, HorizontalAlign.CENTER * and HorizontalAlign.RIGHT.

    * * @default 2 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get numUnselectedElements():int { return _numUnselectedElements; } /** * @private */ public function set numUnselectedElements( value:int ) : void { if( _numUnselectedElements == value ) return; _numUnselectedElements = value; invalidateTargetDisplayList(); } //---------------------------------- // horizontalAlign //---------------------------------- /** * @private * Storage property for horizontalAlign. */ private var _horizontalAlign:String = HorizontalAlign.CENTER; /** * @private * Flag to indicate the horizontalAlign property has changed. */ private var _horizontalAlignChange:Boolean = true; [Inspectable(category=""General"", enumeration=""left,right,center"", defaultValue=""center"")] /** * The horizontal position of the selected element in the viewport. All other elements * are positioned around this element. * *

    Valid values are HorizontalAlign.LEFT, HorizontalAlign.CENTER * and HorizontalAlign.RIGHT.

    * * @default ""center"" * * @see #horizontalAlignOffset * @see #horizontalAlignOffsetPercent * @see spark.layouts.HorizontalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get horizontalAlign():String { return _horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if( value == _horizontalAlign ) return; _horizontalAlign = value; _horizontalAlignChange = true; invalidateTargetDisplayList(); } //---------------------------------- // verticalAlign //---------------------------------- /** * @private * Storage property for verticalAlign. */ private var _verticalAlign:String = VerticalAlign.MIDDLE; /** * @private * Flag to indicate the verticalAlign property has changed. */ private var _verticalAlignChange:Boolean = true; [Inspectable(category=""General"", enumeration=""top,bottom,middle"", defaultValue=""middle"")] /** * The vertical position of the selected element in the viewport. All other elements * are positioned around this element. * *

    Valid values are VerticalAlign.TOP, VerticalAlign.MIDDLE * and VerticalAlign.BOTTOM.

    * * @default ""middle"" * * @see #verticalAlignOffset * @see #verticalAlignOffsetPercent * @see spark.layouts.VerticalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get verticalAlign():String { return _verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if( value == _verticalAlign ) return; _verticalAlign = value; _verticalAlignChange = true; invalidateTargetDisplayList(); } //---------------------------------- // horizontalAlignOffset //---------------------------------- /** * @private * Storage property for horizontalAlignOffset. */ private var _horizontalAlignOffset:Number = 0; [Inspectable(category=""General"", defaultValue=""0"")] /** * The offset in pixels to be used in conjunction with horizontalAlign * to set the horizontal position of the selected element in the viewport. All other elements * are positioned around this element. * *

    If horizontalAlignOffsetPercent is set after this property, * this property is set automatically depending on the value of horizontalAlignOffsetPercent.

    * * @default 0 * * @see #horizontalAlign * @see #horizontalAlignOffsetPercent * @see spark.layouts.HorizontalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get horizontalAlignOffset():Number { return _horizontalAlignOffset; } /** * @private */ public function set horizontalAlignOffset(value:Number):void { if( _horizontalAlignOffset == value ) return; _horizontalAlignOffset = value; _horizontalAlignOffsetPercent = NaN; invalidateTargetDisplayList(); } //---------------------------------- // verticalAlignOffset //---------------------------------- /** * @private * Storage property for verticalAlignOffset. */ private var _verticalAlignOffset:Number = 0; [Inspectable(category=""General"", defaultValue=""0"")] /** * The offset in pixels to be used in conjunction with verticalAlign * to set the vertical position of the selected element in the viewport. All other elements * are positioned around this element. * *

    If verticalAlignOffsetPercent is set after this property, * this property is set automatically depending on the value of verticalAlignOffsetPercent.

    * * @default 0 * * @see #verticalAlign * @see #verticalAlignOffsetPercent * @see spark.layouts.VerticalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get verticalAlignOffset():Number { return _verticalAlignOffset; } /** * @private */ public function set verticalAlignOffset(value:Number):void { if( _verticalAlignOffset == value ) return; _verticalAlignOffset = value; _verticalAlignOffsetPercent = NaN; // _indicesInViewChanged = true; invalidateTargetDisplayList(); } //---------------------------------- // horizontalAlignOffsetPercent //---------------------------------- /** * @private * Storage property for horizontalAlignOffsetPercent. */ private var _horizontalAlignOffsetPercent:Number = 0; [Inspectable(category=""General"", defaultValue=""0"")] /** * The offset as a percentage of the unscaled width of the viewport * to be used in conjunction with horizontalAlign to set the horizontal * position of the selected element in the viewport. All other elements are * positioned around this element. * *

    Setting this property overrides any value set on horizontalAlignOffset.

    * * @default 0 * * @see #horizontalAlign * @see #horizontalAlignOffset * @see spark.layouts.HorizontalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get horizontalAlignOffsetPercent():Number { return _horizontalAlignOffsetPercent; } /** * @private */ public function set horizontalAlignOffsetPercent(value:Number):void { if( _horizontalAlignOffsetPercent == value ) return; _horizontalAlignOffsetPercent = value; if( !isNaN( _horizontalAlignOffsetPercent ) ) _horizontalAlignOffset = unscaledHeight * ( _horizontalAlignOffsetPercent / 100 ); // _indicesInViewChanged = true; invalidateTargetDisplayList(); } //---------------------------------- // verticalAlignOffsetPercent //---------------------------------- /** * @private * Storage property for verticalAlignOffsetPercent. */ private var _verticalAlignOffsetPercent:Number = 0; [Inspectable(category=""General"", defaultValue=""0"")] /** * The offset as a percentage of the unscaled height of the viewport * to be used in conjunction with verticalAlign to set the vertical * position of the selected element in the viewport. All other elements are * positioned around this element. * *

    Setting this property overrides any value set on verticalAlignOffset.

    * * @default 0 * * @see #verticalAlign * @see #verticalAlignOffset * @see spark.layouts.VerticalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get verticalAlignOffsetPercent():Number { return _verticalAlignOffsetPercent; } /** * @private */ public function set verticalAlignOffsetPercent(value:Number):void { if( _verticalAlignOffsetPercent == value ) return; _verticalAlignOffsetPercent = value; if( !isNaN( _verticalAlignOffsetPercent ) ) _verticalAlignOffset = unscaledHeight * ( _verticalAlignOffsetPercent / 100 ); // _indicesInViewChanged = true; invalidateTargetDisplayList(); } //---------------------------------- // elementHorizontalAlign //---------------------------------- /** * @private * Storage property for elementHorizontalAlign. */ private var _elementHorizontalAlign:String = HorizontalAlign.CENTER; /** * @private * Flag to indicate the elementHorizontalAlign property has changed. */ private var _elementHorizontalAlignChange : Boolean = true; [Inspectable(category=""General"", enumeration=""left,right,center"", defaultValue=""center"")] /** * The horizontal transform point of elements. * *

    Valid values are HorizontalAlign.LEFT, HorizontalAlign.CENTER * and HorizontalAlign.RIGHT.

    * * @default ""center"" * * @see spark.layouts.HorizontalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get elementHorizontalAlign():String { return _elementHorizontalAlign; } /** * @private */ public function set elementHorizontalAlign(value:String):void { if( value == _elementHorizontalAlign ) return; _elementHorizontalAlign = value; _elementHorizontalAlignChange = true; invalidateTargetDisplayList(); } //---------------------------------- // elementVerticalAlign //---------------------------------- /** * @private * Storage property for elementVerticalAlign. */ private var _elementVerticalAlign:String = VerticalAlign.MIDDLE; /** * @private * Flag to indicate the elementVerticalAlign property has changed. */ private var _elementVerticalAlignChange : Boolean = true; [Inspectable(category=""General"", enumeration=""top,bottom,middle"", defaultValue=""middle"")] /** * The vertical transform point of elements. * *

    Valid values are VerticalAlign.TOP, VerticalAlign.MIDDLE * and VerticalAlign.BOTTOM.

    * * @default ""middle"" * * @see spark.layouts.VerticalAlign * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get elementVerticalAlign():String { return _elementVerticalAlign; } /** * @private */ public function set elementVerticalAlign(value:String):void { if( value == _elementVerticalAlign ) return; _elementVerticalAlign = value; _elementVerticalAlignChange = true; invalidateTargetDisplayList(); } //---------------------------------- // radiusX //---------------------------------- /** * @private * Storage property for radiusX. */ private var _radiusX : Number = 100; [Inspectable(category=""General"", type=""Number"", defaultValue=""100"")] /** * The radius to be used on the x axis for the SemiCarouselLayout. * * @default 100 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get radiusX():Number { return _radiusX; } /** * @private */ public function set radiusX( value:Number ):void { if( value == _radiusX ) return; _radiusX = value; invalidateTargetDisplayList(); } //---------------------------------- // radiusY //---------------------------------- /** * @private * Storage property for radiusY. */ private var _radiusY : Number = 0; [Inspectable(category=""General"", type=""Number"", defaultValue=""0"")] /** * The radius to be used on the y axis for the SemiCarouselLayout. * * @default 0 * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get radiusY():Number { return _radiusY; } /** * @private */ public function set radiusY( value:Number ):void { if( value == _radiusY ) return; _radiusY = value; invalidateTargetDisplayList(); } //---------------------------------- // radiusZ //---------------------------------- /** * @private * Storage property for radiusZ. */ private var _radiusZ : Number; [Inspectable(category=""General"", type=""Number"", defaultValue=""NaN"")] /** * The radius to be used on the z axis for the SemiCarouselLayout. * *

    If a value of NaN is passed the largest of radiusX * or radiusY is used.

    * * @default NaN * * @see #radiusX * @see #radiusY * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get radiusZ():Number { return _radiusZ; } /** * @private */ public function set radiusZ( value:Number ):void { if( value == _radiusZ ) return; _radiusZ = value; invalidateTargetDisplayList(); } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * * Positions, transforms and sets the size of an element * that will be visible in the layout. */ protected function updateVisibleElementAt( element:IVisualElement, index:int ):void { _displayedElements.push( element ); setElementLayoutBoundsSize( element, false ); _transformCalculator.updateForIndex( index, element, element.width, element.height, _elementHorizontalCenterMultiplier, _elementVerticalCenterMultiplier ); // elementTransformAround( element ); applyColorTransformToElement( element, _transformCalculator.colorTransform ); element.visible = true; } /** * @private */ private function sortElementsByZ( a:IVisualElement, b:IVisualElement ):int { if( getZ( a ) > getZ( b ) ) { return -1; } else if( getZ( a ) < getZ( b ) ) { return 1; } return 0; } /** * @private * * Util function to return the value of the z property * on an element. */ private function getZ( e:IVisualElement ):Number { if( e is GraphicElement ) { return GraphicElement( e ).z; } else { return UIComponent( e ).z; } } /** * @private * * Sets the depth of elements inlcuded in the layout at depths * to display correctly for the z position set with transformAround. * * Also sets the depth of elements that are not included in the layout. * The depth of these is dependent on whether their element index is before * or after the index of the selected element. * * - If their element index is before the selected elements index * they appear beneath all items included in the layout. * * - If their element index is after the selected elements index * they appear above all items included in the layout */ private function updateDepths( depths:Vector. ):void { if( !depths || !depths.length ) return; var animationIndex:int = Math.max( 0, Math.min( Math.round( animationValue ), numElementsInLayout - 1 ) ); var element:IVisualElement; var index:int; var i:int var numBeforeMinDepth:int = 0; var minDepth:int = depths[ 0 ] - 1; var maxDepth:int = depths[ depths.length - 1 ] + 1; const elements:Vector. = new Vector.(); for( i = firstIndexInView; i <= lastIndexInView; i++ ) { index = indicesInLayout[ i ]; element = target.getElementAt( index ); if( !element ) continue; elements.push( element ); } elements.sort( sortElementsByZ ); var num:int = elements.length; for( i = 0; i < num; i++ ) { elements[ i ].depth = depths[ i ]; } // target.validateNow(); // for( i = firstIndexInView; i <= lastIndexInView; i++ ) // { // index = indicesInLayout[ i ]; // element = target.getElementAt( index ); // if( !element ) continue; // if( index < indicesInLayout[ animationIndex ] ) // { // element.depth = _transformCalculator.radiusZ > -1 ? depths.shift() : depths.pop(); // } //// else if ( index > indicesInLayout[ animationIndex ] ) //// { //// element.depth = _direction == SemiCarouselLayoutDirection.CONVEX ? depths.pop() : depths.shift(); //// } // else // { // element.depth = _transformCalculator.radiusZ > -1 ? depths.pop() : depths.shift(); // } // } // // // var numElementsNotInLayout:int = indicesNotInLayout.length; // for( i = 0; i < numElementsNotInLayout; i++ ) // { // if( indicesNotInLayout[ i ] > indicesInLayout[ animationIndex ] ) // { // break; // } // else // { // numBeforeMinDepth++; // } // } // // minDepth -= numBeforeMinDepth - 1; // for( i = 0; i < numElementsNotInLayout; i++ ) // { // element = target.getElementAt( indicesNotInLayout[ i ] ); // if( !element ) continue; // if( indicesNotInLayout[ i ] > indicesInLayout[ animationIndex ] ) // { // element.depth = maxDepth; // maxDepth++; // } // else // { // element.depth = minDepth; // minDepth++; // } // } // // target.validateNow(); } /** * @private * * A convenience method used to transform an element by applying * the current values if the TransforCalulator instance. */ // private function elementTransformAround( element:IVisualElement ):void // { // var halfWidth:Number = element.width / 2; // var halfHeight:Number = element.height / 2; // var offsetX:Number = halfWidth * ( _elementHorizontalCenterMultiplier - 0.5 ) * 2; // var offsetY:Number = halfHeight * ( _elementVerticalCenterMultiplier - 0.5 ) * 2; // // element.transformAround( new Vector3D( element.width / 2, element.height / 2, 0 ), // null, // null, // new Vector3D( _transformCalculator.x - offsetX, _transformCalculator.y - offsetY, _transformCalculator.z ), // null, // new Vector3D( _transformCalculator.xRotation, _transformCalculator.yRotation, 0 ), // new Vector3D( _transformCalculator.x - offsetX, _transformCalculator.y - offsetY, _transformCalculator.z ), // false ); // // } //-------------------------------------------------------------------------- // // Overridden Methods // //-------------------------------------------------------------------------- /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override public function updateDisplayList( unscaledWidth:Number, unscaledHeight:Number):void { // if( this.unscaledWidth != unscaledWidth || this.unscaledHeight != unscaledHeight ) _sizeChanged = true; if( _horizontalAlignChange ) { _horizontalAlignChange = false; // _indicesInViewChanged = true; switch( _horizontalAlign ) { case HorizontalAlign.LEFT : { _horizontalCenterMultiplier = 0; break; } case HorizontalAlign.RIGHT : { _horizontalCenterMultiplier = 1; break; } default : { _horizontalCenterMultiplier = 0.5; } } } if( _verticalAlignChange ) { _verticalAlignChange = false; // _indicesInViewChanged = true; switch( _verticalAlign ) { case VerticalAlign.TOP : { _verticalCenterMultiplier = 0; break; } case VerticalAlign.BOTTOM : { _verticalCenterMultiplier = 1; break; } default : { _verticalCenterMultiplier = 0.5; } } } if( _elementHorizontalAlignChange ) { _elementHorizontalAlignChange = false; // _indicesInViewChanged = true; switch( _elementHorizontalAlign ) { case HorizontalAlign.LEFT : { _elementHorizontalCenterMultiplier = 0; break; } case HorizontalAlign.RIGHT : { _elementHorizontalCenterMultiplier = 1; break; } default : { _elementHorizontalCenterMultiplier = 0.5; } } } if( _elementVerticalAlignChange ) { _elementVerticalAlignChange = false; // _indicesInViewChanged = true; switch( _elementVerticalAlign ) { case VerticalAlign.TOP : { _elementVerticalCenterMultiplier = 0; break; } case VerticalAlign.BOTTOM : { _elementVerticalCenterMultiplier = 1; break; } default : { _elementVerticalCenterMultiplier = 0.5; } } } super.updateDisplayList( unscaledWidth, unscaledHeight ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function updateDisplayListBetween():void { super.updateDisplayListBetween(); if( sizeChangedInLayoutPass ) { // _indicesInViewChanged = true; if( !isNaN( _horizontalAlignOffsetPercent ) ) _horizontalAlignOffset = unscaledHeight * ( _horizontalAlignOffsetPercent / 100 ); if( !isNaN( _verticalAlignOffsetPercent ) ) _verticalAlignOffset = unscaledHeight * ( _verticalAlignOffsetPercent / 100 ); } _transformCalculator.updateForLayoutPass( _horizontalCenterMultiplier, _verticalCenterMultiplier, _rotateX, _rotateY ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function updateDisplayListVirtual():void { super.updateDisplayListVirtual(); var element:IVisualElement; var depths:Vector. = new Vector.(); for each( element in _displayedElements ) { element.visible = false; } _displayedElements = new Vector.(); for( var i:int = firstIndexInView; i <= lastIndexInView; i++ ) { element = target.getVirtualElementAt( indicesInLayout[ i ] ); depths.push( indicesInLayout[ i ] ); updateVisibleElementAt( element, i ); } updateDepths( depths ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function updateDisplayListReal():void { super.updateDisplayListReal(); var element:IVisualElement; var depths:Vector. = new Vector.(); _displayedElements = new Vector.(); for( var i:int = 0; i < numElementsInLayout; i++ ) { element = target.getElementAt( indicesInLayout[ i ] ); if( i >= firstIndexInView && i <= lastIndexInView ) { depths.push( indicesInLayout[ i ] ); updateVisibleElementAt( element, i); } else { element.visible = false; } } updateDepths( depths ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function restoreElement( element:IVisualElement ):void { super.restoreElement( element ); var vector:Vector3D = new Vector3D( 0, 0, 0 ); element.visible = true; element.depth = 0; element.transformAround( vector, null, null, vector, null, vector, vector, false ); applyColorTransformToElement( element, new ColorTransform() ); } /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ override protected function updateIndicesInView():void { super.updateIndicesInView(); if( _numUnselectedElements > 0 ) { const ceilIndex:int = Math.ceil( animationValue ); const floorIndex:int = Math.floor( animationValue ); const firstIndexInView:int = Math.max( ceilIndex - _numUnselectedElements, 0 ); var numIndicesInView:int = ( _numUnselectedElements * 2 ) + 1; // If the number of elements on the left are less than _numUnselectedElements if( floorIndex < _numUnselectedElements ) { numIndicesInView -= _numUnselectedElements - floorIndex; } // If we are mid transition, we don't need the last item else if( floorIndex != animationValue ) { numIndicesInView -= 1; } // If we are at the end of the list of elements if( floorIndex + _numUnselectedElements >= numElementsInLayout ) { numIndicesInView -= _numUnselectedElements - ( ( numElementsInLayout - 1 ) - floorIndex ); } indicesInView( firstIndexInView, numIndicesInView ); } else { indicesInView( 0, numElementsInLayout ); } } } } import flash.geom.ColorTransform; import flash.geom.Point; import flash.geom.Vector3D; import mx.core.IVisualElement; import spark.layouts.CarouselLayout; internal class TransformValues { //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function TransformValues( layout:CarouselLayout ) { _layout = layout; _colorTransform = new ColorTransform(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- private var _layout : CarouselLayout; private var _index : int; private var _indexOffset : Number; // Center private var _cx : Number; private var _cy : Number; // AlignOffset private var _ho : Number; private var _vo : Number; private var _rx : Number; private var _ry : Number; private var _rz : Number; // Number of items private var _ni : Number; private var _an : Number; private var _c : int; private var _ca : Number; private var _rotY : int; private var _rotX : int; private var _oy:Number; private var _ox:Number; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // x //---------------------------------- /** * @private * Storage property for x. */ private var _x:Number; // /** // * x // * // * @langversion 3.0 // * @playerversion Flash 10 // * @playerversion AIR 1.5 // * @productversion Flex 4 // */ // public function get x():Number // { // return _x; // } //---------------------------------- // y //---------------------------------- /** * @private * Storage property for y. */ private var _y:Number; // /** // * y // * // * @langversion 3.0 // * @playerversion Flash 10 // * @playerversion AIR 1.5 // * @productversion Flex 4 // */ // public function get y():Number // { // return _y; // } //---------------------------------- // z //---------------------------------- /** * @private * Storage property for z. */ private var _z:Number; // /** // * z // * // * @langversion 3.0 // * @playerversion Flash 10 // * @playerversion AIR 1.5 // * @productversion Flex 4 // */ // public function get z():Number // { // return _z; // } //---------------------------------- // xRotation //---------------------------------- /** * @private * Storage property for xRotation. */ private var _xRotation:Number; // /** // * xRotation // * // * @langversion 3.0 // * @playerversion Flash 10 // * @playerversion AIR 1.5 // * @productversion Flex 4 // */ // public function get xRotation():Number // { // return _xRotation; // } //---------------------------------- // yRotation //---------------------------------- /** * @private * Storage property for yRotation. */ private var _yRotation:Number; /** * yRotation * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ // public function get yRotation():Number // { // return _yRotation; // } // // public function get radiusZ():Number { return _rz; } //---------------------------------- // colorTransform //---------------------------------- /** * @private * Storage property for colorTransform. */ private var _colorTransform:ColorTransform; /** * colorTransform * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function get colorTransform():ColorTransform { return _colorTransform; } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * updateForLayoutPass * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function updateForLayoutPass( centerMultiplierX:Number, centerMultiplierY:Number, rotX:int, rotY:int ):void { _index = Math.floor( _layout.animationValue ); _indexOffset = _layout.animationValue - _index; _cx = _layout.unscaledWidth * centerMultiplierX; _cy = _layout.unscaledHeight * centerMultiplierY; _ho = _layout.horizontalAlignOffset; _vo = _layout.verticalAlignOffset; _c = _layout.depthColor; _ca = _layout.depthColorAlpha / 100; if( _c < 0 ) { _colorTransform.redMultiplier = _colorTransform.greenMultiplier = _colorTransform.blueMultiplier = 1; _colorTransform.redOffset = _colorTransform.greenOffset = _colorTransform.blueOffset = _colorTransform.alphaOffset = 0; } _rx = _layout.radiusX; _ry = _layout.radiusY; _rz = _layout.radiusZ; if( isNaN( _rz ) ) _rz = Math.abs( ( Math.abs( _rx ) > Math.abs( _ry ) ) ? _rx : _ry ); _rotY = rotY; _rotX = rotX; const numElements:int = _layout.numUnselectedElements < 0 ? 0 : _layout.numUnselectedElements; _an = numElements ? _layout.angle / ( numElements * 2 ) : _layout.angle / _layout.numElementsInLayout; } /** * circular * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ private function layout( index:Number ):void { const degree:Number = _an * index; const radian:Number = degree * Math.PI / 180; _x = _cx + _ho + ( Math.sin( radian ) * _rx ); _y = _cy + _vo + ( Math.sin( radian ) * _ry ); _z = _rz - ( Math.cos( radian ) * _rz ); _yRotation = _rx && _rotY != 0 ? -( angle( _x, _z, _cx + _ho, _rz ) - 90 ) * _rotY : 0; _xRotation = _ry && _rotX != 0 ? ( angle( _y , _z, _cy + _vo, _rz ) - 90 ) * _rotX : 0; if( _rz < 0 ) { if( _yRotation ) _yRotation += 180; if( _xRotation ) _xRotation += 180; } } public function angle( x1:Number, y1:Number, x2:Number, y2:Number ):Number { return Math.atan2( y2 - y1, x2 - x1 ) * ( 180 / Math.PI ); } /** * updateForIndex * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ public function updateForIndex( i:int, element:IVisualElement, width:Number, height:Number, hMultiplier:Number, vMultiplier:Number ):void { _ox = ( width / 2 ) * ( hMultiplier - 0.5 ) * 2; _oy = ( height / 2 ) * ( vMultiplier - 0.5 ) * 2; layout( ( i - _index ) - _indexOffset ); if( _c > -1 ) { const radian:Number = ( _layout.angle / 2 ) * Math.PI / 180; const maxDepth:Number = _rz - ( Math.cos( radian ) * _rz ) const v:Number = ( _z / maxDepth ) * _ca; _colorTransform.color = _c; _colorTransform.redOffset *= v; _colorTransform.greenOffset *= v; _colorTransform.blueOffset *= v; _colorTransform.redMultiplier = _colorTransform.greenMultiplier = _colorTransform.blueMultiplier = 1 - v; } element.transformAround( new Vector3D( width / 2, height / 2, 0 ), null, null, new Vector3D( _x - _ox, _y - _oy, _z ), null, new Vector3D( _xRotation, _yRotation, 0 ), new Vector3D( _x - _ox, _y - _oy, _z ), false ); } }",12071,True,2503.790748888418,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.controls.listClasses { import mx.collections.ArrayCollection; import mx.collections.ICollectionView; import mx.collections.IList; import mx.collections.ListCollectionView; import mx.collections.XMLListCollection; import mx.core.EdgeMetrics; import mx.core.IUIComponent; import mx.core.ScrollControlBase; import mx.core.ScrollPolicy; import mx.core.UIComponent; import mx.core.mx_internal; import mx.events.CollectionEvent; import mx.events.DragEvent; import mx.utils.UIDUtil; import org.apache.royale.core.ContainerBaseStrandChildren; import org.apache.royale.core.IBead; import org.apache.royale.core.IBeadLayout; import org.apache.royale.core.IBeadView; import org.apache.royale.core.IChild; import org.apache.royale.core.IContainer; import org.apache.royale.core.IContainerBaseStrandChildrenHost; import org.apache.royale.core.IDataProviderItemRendererMapper; import org.apache.royale.core.IFactory; import org.apache.royale.core.IItemRendererClassFactory; import org.apache.royale.core.IItemRendererProvider; import org.apache.royale.core.ILayoutChild; import org.apache.royale.core.ILayoutHost; import org.apache.royale.core.ILayoutParent; import org.apache.royale.core.ILayoutView; import org.apache.royale.core.IListPresentationModel; import org.apache.royale.core.IParent; import org.apache.royale.core.ISelectionModel; import org.apache.royale.core.IStrandWithPresentationModel; import org.apache.royale.core.ValuesManager; import org.apache.royale.events.Event; import org.apache.royale.events.ValueEvent; import org.apache.royale.utils.loadBeadFromValuesManager; use namespace mx_internal; /** * Dispatched when the user clicks on an item in the control. * * @eventType mx.events.ListEvent.ITEM_CLICK * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""itemClick"", type=""mx.events.ListEvent"")] /** * Dispatched when the user double-clicks on an item in the control. * * @eventType mx.events.ListEvent.ITEM_DOUBLE_CLICK * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""itemDoubleClick"", type=""mx.events.ListEvent"")] //-------------------------------------- // Styles //-------------------------------------- /** * The colors to use for the backgrounds of the items in the list. * The value is an array of one or more colors. * The backgrounds of the list items alternate among the colors in the array. * *

    For DataGrid controls, all items in a row have the same background color, * and each row's background color is determined from the array of colors.

    * *

    For the TileList control, which uses a single list to populate a * two-dimensional display, the style can result in a checkerboard appearance, * stripes, or other patterns based on the number of columns and rows and * the number of colors specified. TileList cycles through the colors, placing * the individual item background colors according to the * layout direction. If you have an even number of colors and an even number of * columns for a TileList layed out horizontally, you will get striping. If * the number of columns is an odd number, you will get a checkerboard pattern. *

    * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.0 */ [Style(name=""alternatingItemColors"", type=""Array"", arrayType=""uint"", format=""Color"", inherit=""yes"")] /** * A flag that controls whether items are highlighted as the mouse rolls * over them. * If true, rows are highlighted as the mouse rolls over them. * If false, rows are highlighted only when selected. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.8 */ [Style(name=""useRollOver"", type=""Boolean"", inherit=""no"")] /** * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 * @royalesuppresspublicvarwarning */ public class ListBase extends ScrollControlBase implements IContainerBaseStrandChildrenHost, IContainer, ILayoutParent, ILayoutView, IItemRendererProvider, IStrandWithPresentationModel { //extends UIComponent public function get value():Object { return null; } //---------------------------------- // dragEnabled //---------------------------------- /** * @private * Storage for the dragEnabled property. */ private var _dragEnabled:Boolean = false; /** * A flag that indicates whether you can drag items out of * this control and drop them on other controls. * If true, dragging is enabled for the control. * If the dropEnabled property is also true, * you can drag items and drop them within this control * to reorder the items. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dragEnabled():Boolean { return _dragEnabled; } /** * @private */ public function set dragEnabled(value:Boolean):void { _dragEnabled = value; } //---------------------------------- // dragMoveEnabled //---------------------------------- /** * @private * Storage for the dragMoveEnabled property. */ private var _dragMoveEnabled:Boolean = false; [Inspectable(defaultValue=""false"")] /** * A flag that indicates whether items can be moved instead * of just copied from the control as part of a drag-and-drop * operation. * If true, and the dragEnabled property * is true, items can be moved. * Often the data provider cannot or should not have items removed * from it, so a MOVE operation should not be allowed during * drag-and-drop. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dragMoveEnabled():Boolean { return _dragMoveEnabled; } /** * @private */ public function set dragMoveEnabled(value:Boolean):void { _dragMoveEnabled = value; } //---------------------------------- // menuSelectionMode //---------------------------------- /** * @public * Storage for the menuSelectionMode property. */ public var _menuSelectionMode:Boolean = false; /** * A flag that indicates whether you can drag items out of * this control and drop them on other controls. * If true, dragging is enabled for the control. * If the menuSelectionMode property is also true, * you can drag items and drop them within this control * to reorder the items. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get menuSelectionMode():Boolean { return _menuSelectionMode; } /** * @private */ public function set menuSelectionMode(value:Boolean):void { _menuSelectionMode = value; } //---------------------------------- // dataProvider //---------------------------------- [Bindable(""collectionChange"")] [Inspectable(category=""Data"", defaultValue=""undefined"")] /** * Set of data to be viewed. * This property lets you use most types of objects as data providers. * If you set the dataProvider property to an Array, * it will be converted to an ArrayCollection. If you set the property to * an XML object, it will be converted into an XMLListCollection with * only one item. If you set the property to an XMLList, it will be * converted to an XMLListCollection. * If you set the property to an object that implements the * IList or ICollectionView interface, the object will be used directly. * *

    As a consequence of the conversions, when you get the * dataProvider property, it will always be * an ICollectionView, and therefore not necessarily be the type of object * you used to you set the property. * This behavior is important to understand if you want to modify the data * in the data provider: changes to the original data may not be detected, * but changes to the ICollectionView object that you get back from the * dataProvider property will be detected.

    * * @default null * @see mx.collections.ICollectionView * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 * @royaleignorecoercion org.apache.royale.core.ISelectionModel */ public function get dataProvider():Object { return (model as ISelectionModel).dataProvider; } /** * @royaleignorecoercion org.apache.royale.core.ISelectionModel */ public function set dataProvider(value:Object):void { if (value is Array) { value = new ArrayCollection(value as Array); } else if (value is ICollectionView) { value = ICollectionView(value); } else if (value is IList) { value = new ListCollectionView(IList(value)); } else if (value is XMLList) { value = new XMLListCollection(value as XMLList); } else if (value is XML) { var xl:XMLList = new XMLList(); xl += value; value = new XMLListCollection(xl); } else { // convert it to an array containing this one item var tmp:Array = []; if (value != null) tmp.push(value); value = new ArrayCollection(tmp); } (model as ISelectionModel).dataProvider = value; } //---------------------------------- // dropEnabled //---------------------------------- /** * @private * Storage for the dropEnabled property. */ private var _dropEnabled:Boolean = false; [Inspectable(defaultValue=""false"")] /** * A flag that indicates whether dragged items can be dropped onto the * control. * *

    If you set this property to true, * the control accepts all data formats, and assumes that * the dragged data matches the format of the data in the data provider. * If you want to explicitly check the data format of the data * being dragged, you must handle one or more of the drag events, * such as dragOver, and call the DragEvent's * preventDefault() method to customize * the way the list class accepts dropped data.

    * *

    When you set dropEnabled to true, * Flex automatically calls the showDropFeedback() * and hideDropFeedback() methods to display the drop indicator.

    * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dropEnabled():Boolean { return _dropEnabled; } /** * @private */ public function set dropEnabled(value:Boolean):void { _dropEnabled = value; } //---------------------------------- // labelField //---------------------------------- [Bindable(""labelFieldChanged"")] [Inspectable(category=""Data"", defaultValue=""label"")] /** * The name of the field in the data provider items to display as the label. * By default the list looks for a property named label * on each item and displays it. * However, if the data objects do not contain a label * property, you can set the labelField property to * use a different property in the data object. An example would be * ""FullName"" when viewing a set of people names fetched from a database. * * @default ""label"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 * @royaleignorecoercion org.apache.royale.core.ISelectionModel */ public function get labelField():String { return (model as ISelectionModel).labelField; } /** * @private * @royaleignorecoercion org.apache.royale.core.ISelectionModel */ public function set labelField(value:String):void { (model as ISelectionModel).labelField = value; } //---------------------------------- // labelFunction //---------------------------------- private var _labelFunction:Function; /** * The name of the field in the data provider items to display as the label. * By default the list looks for a property named label * on each item and displays it. * However, if the data objects do not contain a label * property, you can set the labelField property to * use a different property in the data object. An example would be * ""FullName"" when viewing a set of people names fetched from a database. * * @default ""label"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 * @royaleignorecoercion org.apache.royale.core.ISelectionModel */ public function get labelFunction():Function { return _labelFunction; } /** * @private * @royaleignorecoercion org.apache.royale.core.ISelectionModel */ public function set labelFunction(value:Function):void { _labelFunction = value; } //---------------------------------- // selectedIndex //---------------------------------- [Bindable(""change"")] [Bindable(""valueCommit"")] [Inspectable(category=""General"", defaultValue=""-1"")] /** * The index in the data provider of the selected item. * *

    The default value is -1 (no selected item).

    * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 * @royaleignorecoercion org.apache.royale.core.ISelectionModel */ public function get selectedIndex():int { return (model as ISelectionModel).selectedIndex; } /** * @private * @royaleignorecoercion org.apache.royale.core.ISelectionModel */ public function set selectedIndex(value:int):void { // if (!collection || collection.length == 0) // { (model as ISelectionModel).selectedIndex = value; // bSelectionChanged = true; // bSelectedIndexChanged = true; // invalidateDisplayList(); return; // } //commitSelectedIndex(value); } //---------------------------------- // selectedIndices //---------------------------------- [Bindable(""change"")] [Bindable(""valueCommit"")] [Inspectable(category=""General"")] /** * An array of indices in the data provider of the selected items. The * items are in the reverse order that the user selected the items. * @default [ ] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedIndices():Array { // TODO trace(""selectedIndices not implemented""); return null; } /** * @private */ public function set selectedIndices(indices:Array):void { // TODO trace(""selectedIndices not implemented""); } //---------------------------------- // selectedItem //---------------------------------- [Bindable(""change"")] [Bindable(""valueCommit"")] /** * The selected item in the data provider. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedItem():Object { return (model as ISelectionModel).selectedItem; } /** * @private */ public function set selectedItem(item:Object):void { (model as ISelectionModel).selectedItem = item; } //---------------------------------- // selectedItems //---------------------------------- [Bindable(""change"")] [Bindable(""valueCommit"")] /** * An array of references to the selected items in the data provider. The * items are in the reverse order that the user selected the items. * @default [ ] * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get selectedItems():Array { // TODO trace(""selectedItems not implemented""); return null; } /** * @private */ public function set selectedItems(items:Array):void { // TODO trace(""selectedItems not implemented""); } //---------------------------------- // variableRowHeight //---------------------------------- /** * @private * Storage for the variableRowHeight property. */ private var _variableRowHeight:Boolean = false; [Inspectable(category=""General"")] /** * A flag that indicates whether the individual rows can have different * height. This property is ignored by TileList and HorizontalList. * If true, individual rows can have different height values. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get variableRowHeight():Boolean { return _variableRowHeight; } /** * @private */ public function set variableRowHeight(value:Boolean):void { _variableRowHeight = value; // itemsSizeChanged = true; // invalidateDisplayList(); // dispatchEvent(new Event(""variableRowHeightChanged"")); } //---------------------------------- // iconFunction //---------------------------------- /** * @private * Storage for iconFunction property. */ private var _iconFunction:Function; [Bindable(""iconFunctionChanged"")] [Inspectable(category=""Data"")] /** * A user-supplied function to run on each item to determine its icon. * By default the list does not try to display icons with the text * in the rows. However, by specifying an icon function, you can specify * a Class for a graphic that will be created and displayed as an icon * in the row. This property is ignored by DataGrid. * *

    The iconFunction takes a single argument which is the item * in the data provider and returns a Class, as the following example shows:

    * *
    iconFunction(item:Object):Class
    * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.8 */ public function get iconFunction():Function { return _iconFunction; } /** * @private */ public function set iconFunction(value:Function):void { _iconFunction = value; itemsSizeChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""iconFunctionChanged"")); } //---------------------------------- // allowMultipleSelection //---------------------------------- /** * @private * Storage for the allowMultipleSelection property. */ private var _allowMultipleSelection:Boolean = false; [Inspectable(category=""General"", enumeration=""false,true"", defaultValue=""false"")] /** * A flag that indicates whether you can allow more than one item to be * selected at the same time. * If true, users can select multiple items. * There is no option to disallow discontiguous selection. * Standard complex selection options are always in effect * (Shift-click, Ctrl-click). * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get allowMultipleSelection():Boolean { return _allowMultipleSelection; } /** * @private */ public function set allowMultipleSelection(value:Boolean):void { _allowMultipleSelection = value; } //---------------------------------- // showDataTips //---------------------------------- /** * @private * Storage for the showDataTips property. */ private var _showDataTips:Boolean = false; [Bindable(""showDataTipsChanged"")] [Inspectable(category=""Data"", defaultValue=""false"")] /** * A flag that indicates whether dataTips are displayed for text in the rows. * If true, dataTips are displayed. DataTips * are tooltips designed to show the text that is too long for the row. * If you set a dataTipFunction, dataTips are shown regardless of whether the * text is too long for the row. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get showDataTips():Boolean { return _showDataTips; } /** * @private */ public function set showDataTips(value:Boolean):void { _showDataTips = value; // itemsSizeChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""showDataTipsChanged"")); } //---------------------------------- // rowCount //---------------------------------- /** * @private * Storage for the rowCount property. */ private var _rowCount:int = -1; /** * @private */ private var rowCountChanged:Boolean = true; /** * Number of rows to be displayed. * If the height of the component has been explicitly set, * this property might not have any effect. * *

    For a DataGrid control, the rowCount property does * not include the header row.

    * * @default 4 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get rowCount():int { return _rowCount; } /** * @private */ public function set rowCount(value:int):void { explicitRowCount = value; if (_rowCount != value) { setRowCount(value); rowCountChanged = true; invalidateProperties(); invalidateSize(); // itemsSizeChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""rowCountChanged"")); } } /** * Sets the rowCount property without causing * invalidation or setting the explicitRowCount * property, which permanently locks in the number of rows. * * @param v The row count. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function setRowCount(v:int):void { //trace(""setRowCount "" + v); _rowCount = v; } /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function ListBase() { super(); rowHeight = 22; //match Flex? } private var _DCinitialized:Boolean = true; /** * @private */ override public function addedToParent():void { if (!_DCinitialized) { ValuesManager.valuesImpl.init(this); _DCinitialized = true; } super.addedToParent(); // Load the layout bead if it hasn't already been loaded. loadBeadFromValuesManager(IBeadLayout, ""iBeadLayout"", this); // Even though super.addedToParent dispatched ""beadsAdded"", DataContainer still needs its data mapper // and item factory beads. These beads are added after super.addedToParent is called in case substitutions // were made; these are just defaults extracted from CSS. loadBeadFromValuesManager(IDataProviderItemRendererMapper, ""iDataProviderItemRendererMapper"", this); loadBeadFromValuesManager(IItemRendererClassFactory, ""iItemRendererClassFactory"", this); dispatchEvent(new Event(""initComplete"")); } /* * IItemRendererProvider */ private var _itemRenderer:IFactory; /** * The class or factory used to display each item. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function get itemRenderer():IFactory { return _itemRenderer; } public function set itemRenderer(value:IFactory):void { _itemRenderer = value; } private var _strandChildren:ContainerBaseStrandChildren; /** * @private */ public function get strandChildren():IParent { if (_strandChildren == null) { _strandChildren = new ContainerBaseStrandChildren(this); } return _strandChildren; } /** * Refresh all rows on next update. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.4 */ public function invalidateList():void { // not implemented // itemsSizeChanged = true; // invalidateDisplayList(); } public function scrollToIndex(index:int):Boolean { trace(""ListBase:scrollToIndex not implemented""); return false; } /** * @private */ public function childrenAdded():void { dispatchEvent(new ValueEvent(""childrenAdded"")); } /** * Returns the ILayoutHost which is its view. From ILayoutParent. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.8 * @royaleignorecoercion org.apache.royale.core.ILayoutHost */ public function getLayoutHost():ILayoutHost { return view as ILayoutHost; } /** * @private */ private var _presentationModel:IListPresentationModel; /** * The DataGrid's presentation model * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.9 * @royaleignorecoercion org.apache.royale.core.IListPresentationModel * @royaleignorecoercion org.apache.royale.core.IBead */ public function get presentationModel():IBead { if (_presentationModel == null) { var bead:IBead = getBeadByType(IListPresentationModel); if (bead) _presentationModel = bead as IListPresentationModel; else { var c:Class = ValuesManager.valuesImpl.getValue(this, ""iListPresentationModel""); if (c) { _presentationModel = new c() as IListPresentationModel; addBead(_presentationModel as IBead); } } } return _presentationModel; } /* * The following functions are for the SWF-side only and re-direct element functions * to the content area, enabling scrolling and clipping which are provided automatically * in the JS-side. GroupBase handles event dispatching if necessary. */ /** * @private */ COMPILE::SWF override public function addElement(c:IChild, dispatchEvent:Boolean = true):void { var contentView:IParent = getLayoutHost().contentView as IParent; if (contentView == this) return super.addElement(c, dispatchEvent); contentView.addElement(c, dispatchEvent); if (dispatchEvent) this.dispatchEvent(new ValueEvent(""childrenAdded"", c)); } /** * @private */ COMPILE::SWF override public function addElementAt(c:IChild, index:int, dispatchEvent:Boolean = true):void { var contentView:IParent = getLayoutHost().contentView as IParent; if (contentView == this) return super.addElementAt(c, index, dispatchEvent); contentView.addElementAt(c, index, dispatchEvent); if (dispatchEvent) this.dispatchEvent(new ValueEvent(""childrenAdded"", c)); } /** * @private */ COMPILE::SWF override public function getElementIndex(c:IChild):int { var layoutHost:ILayoutHost = view as ILayoutHost; var contentView:IParent = layoutHost.contentView as IParent; if (contentView == this) return super.getElementIndex(c); return contentView.getElementIndex(c); } /** * @private */ COMPILE::SWF override public function removeElement(c:IChild, dispatchEvent:Boolean = true):void { var layoutHost:ILayoutHost = view as ILayoutHost; var contentView:IParent = layoutHost.contentView as IParent; contentView.removeElement(c, dispatchEvent); //TODO This should possibly be ultimately refactored to be more PAYG if(dispatchEvent) this.dispatchEvent(new ValueEvent(""childrenRemoved"", c)); } /** * Returns the item renderer for a given item in the data provider, * if there is one. Since item renderers only exist for items * that are within the set of viewable rows, this method * returns null if the item is not visible. * For a data grid, this returns the first column's renderer. * * @param item The data provider item. * * @return The item renderer or null if the item is not * currently displayed. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.4 */ public function itemToItemRenderer(item:Object):IListItemRenderer { // not implemented //return visibleData[itemToUID(item)]; return null; } /** * Hides the drop indicator under the mouse pointer that indicates that a * drag and drop operation is allowed. * * @param event A DragEvent object that contains information about the * mouse location. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function hideDropFeedback(event:DragEvent):void { //To Do trace(""hideDropFeedback is not implemented""); } /** * Determines if an item is being displayed by a renderer. * * @param item A data provider item. * @return true if the item is being displayed. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function isItemVisible(item:Object):Boolean { return itemToItemRenderer(item) != null; } /** * @private */ COMPILE::SWF override public function get numElements():int { // the view getter below will instantiate the view which can happen // earlier than we would like (when setting mxmlDocument) so we // see if the view bead exists on the strand. If not, nobody // has added any children so numElements must be 0 if (!getBeadByType(IBeadView)) return 0; var layoutHost:ILayoutHost = view as ILayoutHost; var contentView:IParent = layoutHost.contentView as IParent; if (contentView == this) return super.numElements; return contentView.numElements; } /** * @private */ COMPILE::SWF override public function getElementAt(index:int):IChild { var layoutHost:ILayoutHost = view as ILayoutHost; var contentView:IParent = layoutHost.contentView as IParent; if (contentView == this) return super.getElementAt(index); return contentView.getElementAt(index); } /** * @private */ [SWFOverride(returns=""flash.display.DisplayObject"")] COMPILE::SWF override public function getChildAt(index:int):IUIComponent { return getElementAt(index) as IUIComponent; } /* * IStrandPrivate * * These ""internal"" function provide a backdoor way for proxy classes to * operate directly at strand level. While these function are available on * both SWF and JS platforms, they really only have meaning on the SWF-side. * Other subclasses may provide use on the JS-side. * * @see org.apache.royale.core.IContainer#strandChildren */ /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function get $numElements():int { return super.numElements; } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $addElement(c:IChild, dispatchEvent:Boolean = true):void { super.addElement(c, dispatchEvent); } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $addElementAt(c:IChild, index:int, dispatchEvent:Boolean = true):void { super.addElementAt(c, index, dispatchEvent); } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $removeElement(c:IChild, dispatchEvent:Boolean = true):void { super.removeElement(c, dispatchEvent); } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $getElementIndex(c:IChild):int { return super.getElementIndex(c); } /** * @private * @suppress {undefinedNames} * Support strandChildren. */ public function $getElementAt(index:int):IChild { return super.getElementAt(index); } //---------------------------------- // explicitColumnCount //---------------------------------- /** * The column count requested by explicitly setting the * columnCount property. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var explicitColumnCount:int = -1; //---------------------------------- // explicitColumnWidth //---------------------------------- /** * The column width requested by explicitly setting the * columnWidth. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var explicitColumnWidth:Number; //---------------------------------- // explicitRowHeight //---------------------------------- /** * The row height requested by explicitly setting * rowHeight. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var explicitRowHeight:Number; //---------------------------------- // explicitRowCount //---------------------------------- /** * The row count requested by explicitly setting * rowCount. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var explicitRowCount:int = -1; //---------------------------------- // defaultColumnCount //---------------------------------- /** * The default number of columns to display. This value * is used if the calculation for the number of * columns results in a value less than 1 when * trying to calculate the columnCount based on size or * content. * * @default 4 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var defaultColumnCount:int = 4; //---------------------------------- // defaultRowCount //---------------------------------- /** * The default number of rows to display. This value * is used if the calculation for the number of * columns results in a value less than 1 when * trying to calculate the rowCount based on size or * content. * * @default 4 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected var defaultRowCount:int = 4; //---------------------------------- // rowHeight //---------------------------------- /** * @private * Storage for the rowHeight property. */ private var _rowHeight:Number; /** * @private */ private var rowHeightChanged:Boolean = false; [Inspectable(category=""General"")] /** * The height of the rows in pixels. * Unless the variableRowHeight property is * true, all rows are the same height. * If not specified, the row height is based on * the font size and other properties of the renderer. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get rowHeight():Number { return _rowHeight; } /** * @private * @royaleignorecoercion org.apache.royale.core.IListPresentationModel */ public function set rowHeight(value:Number):void { explicitRowHeight = value; if (_rowHeight != value) { _rowHeight = value; (presentationModel as IListPresentationModel).rowHeight = value; /* invalidateSize(); itemsSizeChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""rowHeightChanged"")); */ } } //---------------------------------- // columnWidth //---------------------------------- /** * @private * Storage for the columnWidth property. */ private var _columnWidth:Number; /** * @private */ private var columnWidthChanged:Boolean = false; /** * The width of the control's columns. * This property is used by TileList and HorizontalList controls; * It has no effect on DataGrid controls, where you set the individual * DataGridColumn widths. * * @default 50 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get columnWidth():Number { return _columnWidth; } /** * @private */ public function set columnWidth(value:Number):void { explicitColumnWidth = value; if (_columnWidth != value) { _columnWidth = value; /* invalidateSize(); itemsSizeChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""columnWidthChanged""));*/ } } /** * @royaleignorecoercion org.apache.royale.core.ILayoutChild */ override protected function measure():void { super.measure(); var cc:int = explicitColumnCount < 1 ? defaultColumnCount : explicitColumnCount; var rc:int = explicitRowCount < 1 ? defaultRowCount : explicitRowCount; if (!isNaN(explicitRowHeight)) { measuredHeight = explicitRowHeight * rc // + o.top + o.bottom; //measuredMinHeight = explicitRowHeight * Math.min(rc, 2) + // o.top + o.bottom; } else { if (isNaN(rowHeight) && numChildren > 0) { rowHeight = (getElementAt(0) as ILayoutChild).height; } measuredHeight = rowHeight * rc // + o.top + o.bottom; //measuredMinHeight = rowHeight * Math.min(rc, 2) + // o.top + o.bottom; } if (!isNaN(explicitColumnWidth)) { measuredWidth = explicitColumnWidth * cc // + o.left + o.right; //measuredMinWidth = explicitColumnWidth * Math.min(cc, 1) + // o.left + o.right; } else { if (isNaN(columnWidth) && numChildren > 0) { columnWidth = (getElementAt(0) as ILayoutChild).width; } measuredWidth = columnWidth * cc // + o.left + o.right; //measuredMinWidth = columnWidth * Math.min(cc, 1) + // o.left + o.right; } } /** * Determines the UID for a data provider item. All items * in a data provider must either have a unique ID (UID) * or one will be generated and associated with it. This * means that you cannot have an object or scalar value * appear twice in a data provider. * *

    For example, the following * data provider is not supported because the value ""foo"" * appears twice and the UID for a string is the string itself:

    * *
    var sampleDP:Array = [""foo"", ""bar"", ""foo""]
    * *

    Simple dynamic objects can appear twice if they are two * separate instances. The following is supported because * each of the instances will be given a different UID because * they are different objects:

    * *
    var sampleDP:Array = [{label: ""foo""}, {label: ""foo""}]
    * *

    Note that the following is not supported because the same instance * appears twice.

    * *
             *  var foo:Object = {label: ""foo""};
             *  sampleDP:Array = [foo, foo];
    * * @param data The data provider item. * * @return The UID as a string. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ protected function itemToUID(data:Object):String { if (data == null) return ""null""; return UIDUtil.getUID(data); } //-------------------------------------------------------------------------- // // Methods: Item fields // //-------------------------------------------------------------------------- /** * Returns the string the renderer would display for the given data object * based on the labelField and labelFunction properties. * If the method cannot convert the parameter to a string, it returns a * single space. * * @param data Object to be rendered. * * @return The string to be displayed based on the data. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function itemToLabel(data:Object):String { if (data == null) return "" ""; /* if (labelFunction != null) return labelFunction(data); */ if (data is XML) { try { if ((data as XML)[labelField].length() != 0) data = (data as XML)[labelField]; //by popular demand, this is a default XML labelField //else if (data.@label.length() != 0) // data = data.@label; } catch(e:Error) { } } else if (data is Object) { try { if (data[labelField] != null) data = data[labelField]; } catch(e:Error) { } } if (data is String) return String(data); try { return data.toString(); } catch(e:Error) { } return "" ""; } //---------------------------------- // dataTipField //---------------------------------- /** * @private * Storage for the dataTipField property. */ private var _dataTipField:String = ""label""; [Bindable(""dataTipFieldChanged"")] [Inspectable(category=""Data"", defaultValue=""label"")] /** * Name of the field in the data provider items to display as the * data tip. By default, the list looks for a property named * label on each item and displays it. * However, if the data objects do not contain a label * property, you can set the dataTipField property to * use a different property in the data object. An example would be * ""FullName"" when viewing a * set of people's names retrieved from a database. * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.8 */ public function get dataTipField():String { return _dataTipField; } /** * @private */ public function set dataTipField(value:String):void { _dataTipField = value; itemsSizeChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""dataTipFieldChanged"")); } //---------------------------------- // dataTipFunction //---------------------------------- /** * @private * Storage for the dataTipFunction property. */ protected var itemsSizeChanged:Boolean = false; private var _dataTipFunction:Function; [Bindable(""dataTipFunctionChanged"")] [Inspectable(category=""Data"")] /** * User-supplied function to run on each item to determine its dataTip. * By default, the list looks for a property named label * on each data provider item and displays it. * However, some items do not have a label property * nor do they have another property that can be used for displaying * in the rows. An example is a data set that has lastName and firstName * fields, but you want to display full names. You can supply a * dataTipFunction that finds the appropriate * fields and return a displayable string. The * dataTipFunction is also good for handling formatting * and localization. * *

    The dataTipFunction takes a single argument which is the item * in the data provider and returns a String, as the following example shows:

    * *
    myDataTipFunction(item:Object):String
    * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get dataTipFunction():Function { return _dataTipFunction; } /** * @private */ public function set dataTipFunction(value:Function):void { _dataTipFunction = value; itemsSizeChanged = true; invalidateDisplayList(); dispatchEvent(new Event(""dataTipFunctionChanged"")); } } } ",12091,True,2612.676850907883,median "/* Feathers Copyright 2012-2021 Bowler Hat LLC. All Rights Reserved. This program is free software. You can redistribute and/or modify it in accordance with the terms of the accompanying license agreement. */ package feathers.layout { import feathers.core.IValidating; import flash.errors.IllegalOperationError; import flash.geom.Point; import flash.ui.Keyboard; import starling.display.DisplayObject; import starling.events.Event; /** * Dispatched when a property of the layout changes, indicating that a * redraw is probably needed. * *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    currentTargetThe Object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    datanull
    targetThe Object that dispatched the event; * it is not always the Object listening for the event. Use the * currentTarget property to always access the Object * listening for the event.
    * * @eventType starling.events.Event.CHANGE */ [Event(name=""change"",type=""starling.events.Event"")] /** * Positions items of different dimensions from left to right in multiple * rows. When the width of a row reaches the width of the container, a new * row will be started. Constrained to the suggested width, the flow layout * will change in height as the number of items increases or decreases. * * @see ../../../help/flow-layout.html How to use FlowLayout with Feathers containers * * @productversion Feathers 2.2.0 */ public class FlowLayout extends BaseVariableVirtualLayout implements IVariableVirtualLayout, IDragDropLayout { /** * Constructor. */ public function FlowLayout() { super(); this._hasVariableItemDimensions = true; } /** * @private */ protected var _rowItems:Vector. = new []; /** * Quickly sets both horizontalGap and verticalGap * to the same value. The gap getter always returns the * value of horizontalGap, but the value of * verticalGap may be different. * * @default 0 * * @see #horizontalGap * @see #verticalGap */ public function get gap():Number { return this._horizontalGap; } /** * @private */ public function set gap(value:Number):void { this.horizontalGap = value; this.verticalGap = value; } /** * @private */ protected var _horizontalGap:Number = 0; /** * The horizontal space, in pixels, between items. * * @default 0 */ public function get horizontalGap():Number { return this._horizontalGap; } /** * @private */ public function set horizontalGap(value:Number):void { if(this._horizontalGap == value) { return; } this._horizontalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalGap:Number = 0; /** * The vertical space, in pixels, between items. * * @default 0 */ public function get verticalGap():Number { return this._verticalGap; } /** * @private */ public function set verticalGap(value:Number):void { if(this._verticalGap == value) { return; } this._verticalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _firstHorizontalGap:Number = NaN; /** * The space, in pixels, between the first and second items. If the * value of firstHorizontalGap is NaN, the * value of the horizontalGap property will be used * instead. * * @default NaN * * @see #gap */ public function get firstHorizontalGap():Number { return this._firstHorizontalGap; } /** * @private */ public function set firstHorizontalGap(value:Number):void { if(this._firstHorizontalGap == value) { return; } this._firstHorizontalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _lastHorizontalGap:Number = NaN; /** * The space, in pixels, between the last and second to last items. If * the value of lastHorizontalGap is NaN, the * value of the horizontalGap property will be used instead. * * @default NaN * * @see #gap */ public function get lastHorizontalGap():Number { return this._lastHorizontalGap; } /** * @private */ public function set lastHorizontalGap(value:Number):void { if(this._lastHorizontalGap == value) { return; } this._lastHorizontalGap = value; this.dispatchEventWith(Event.CHANGE); } /** * Quickly sets all padding properties to the same value. The * padding getter always returns the value of * paddingTop, but the other padding values may be * different. * * @default 0 * * @see #paddingTop * @see #paddingRight * @see #paddingBottom * @see #paddingLeft */ public function get padding():Number { return this._paddingTop; } /** * @private */ public function set padding(value:Number):void { this.paddingTop = value; this.paddingRight = value; this.paddingBottom = value; this.paddingLeft = value; } /** * @private */ protected var _paddingTop:Number = 0; /** * The space, in pixels, above of items. * * @default 0 */ public function get paddingTop():Number { return this._paddingTop; } /** * @private */ public function set paddingTop(value:Number):void { if(this._paddingTop == value) { return; } this._paddingTop = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingRight:Number = 0; /** * The space, in pixels, to the right of the items. * * @default 0 */ public function get paddingRight():Number { return this._paddingRight; } /** * @private */ public function set paddingRight(value:Number):void { if(this._paddingRight == value) { return; } this._paddingRight = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingBottom:Number = 0; /** * The space, in pixels, below the items. * * @default 0 */ public function get paddingBottom():Number { return this._paddingBottom; } /** * @private */ public function set paddingBottom(value:Number):void { if(this._paddingBottom == value) { return; } this._paddingBottom = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _paddingLeft:Number = 0; /** * The space, in pixels, to the left of the items. * * @default 0 */ public function get paddingLeft():Number { return this._paddingLeft; } /** * @private */ public function set paddingLeft(value:Number):void { if(this._paddingLeft == value) { return; } this._paddingLeft = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _horizontalAlign:String = HorizontalAlign.LEFT; [Inspectable(type=""String"",enumeration=""left,center,right"")] /** * If the total row width is less than the bounds, the items in the row * can be aligned horizontally. * *

    Note: The HorizontalAlign.JUSTIFY * constant is not supported.

    * * @default feathers.layout.HorizontalAlign.LEFT * * @see feathers.layout.HorizontalAlign#LEFT * @see feathers.layout.HorizontalAlign#CENTER * @see feathers.layout.HorizontalAlign#RIGHT * @see #verticalAlign * @see #rowVerticalAlign */ public function get horizontalAlign():String { return this._horizontalAlign; } /** * @private */ public function set horizontalAlign(value:String):void { if(this._horizontalAlign == value) { return; } this._horizontalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _verticalAlign:String = VerticalAlign.TOP; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * If the total height of the content is less than the bounds, the * content may be aligned vertically. * *

    Note: The VerticalAlign.JUSTIFY * constant is not supported.

    * * @default feathers.layout.VerticalAlign.TOP * * @see feathers.layout.VerticalAlign#TOP * @see feathers.layout.VerticalAlign#MIDDLE * @see feathers.layout.VerticalAlign#BOTTOM * @see #horizontalAlign * @see #rowVerticalAlign */ public function get verticalAlign():String { return this._verticalAlign; } /** * @private */ public function set verticalAlign(value:String):void { if(this._verticalAlign == value) { return; } this._verticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _rowVerticalAlign:String = VerticalAlign.TOP; [Inspectable(type=""String"",enumeration=""top,middle,bottom"")] /** * If the height of an item is less than the height of a row, it can be * aligned vertically. * * @default feathers.layout.VerticalAlign.TOP * * @see feathers.layout.VerticalAlign#TOP * @see feathers.layout.VerticalAlign#MIDDLE * @see feathers.layout.VerticalAlign#BOTTOM * @see #horizontalAlign * @see #verticalAlign */ public function get rowVerticalAlign():String { return this._rowVerticalAlign; } /** * @private */ public function set rowVerticalAlign(value:String):void { if(this._rowVerticalAlign == value) { return; } this._rowVerticalAlign = value; this.dispatchEventWith(Event.CHANGE); } /** * @private */ protected var _widthCache:Array = []; /** * @private */ protected var _heightCache:Array = []; /** * @inheritDoc */ public function layout(items:Vector., viewPortBounds:ViewPortBounds = null, result:LayoutBoundsResult = null):LayoutBoundsResult { //this function is very long because it may be called every frame, //in some situations. testing revealed that splitting this function //into separate, smaller functions affected performance. //since the SWC compiler cannot inline functions, we can't use that //feature either. //since viewPortBounds can be null, we may need to provide some defaults var boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; var boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; var needsWidth:Boolean = explicitWidth !== explicitWidth; //isNaN //let's figure out if we can show multiple rows var supportsMultipleRows:Boolean = true; var availableRowWidth:Number = explicitWidth; if(needsWidth) { availableRowWidth = maxWidth; if(availableRowWidth == Number.POSITIVE_INFINITY) { supportsMultipleRows = false; } } if(this._useVirtualLayout) { //if the layout is virtualized, we'll need the dimensions of the //typical item so that we have fallback values when an item is null if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var i:int = 0; var itemCount:int = items.length; var positionY:Number = boundsY + this._paddingTop; var maxRowWidth:Number = 0; var maxItemHeight:Number = 0; var verticalGap:Number = this._verticalGap; var hasFirstHorizontalGap:Boolean = this._firstHorizontalGap === this._firstHorizontalGap; //!isNaN var hasLastHorizontalGap:Boolean = this._lastHorizontalGap === this._lastHorizontalGap; //!isNaN var secondToLastIndex:int = itemCount - 2; do { if(i > 0) { positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = this._useVirtualLayout ? calculatedTypicalItemHeight : 0; var positionX:Number = boundsX + this._paddingLeft; //we save the items in this row to align them later. this._rowItems.length = 0; var rowItemCount:int = 0; //if there are no items in the row (such as when there are no //items in the container!), then we don't want to subtract the //gap when calculating the row width, so default to 0. var horizontalGap:Number = 0; //this first loop sets the x position of items, and it calculates //the total width of all items for(; i < itemCount; i++) { var item:DisplayObject = items[i]; horizontalGap = this._horizontalGap; if(hasFirstHorizontalGap && i == 0) { horizontalGap = this._firstHorizontalGap; } else if(hasLastHorizontalGap && i > 0 && i == secondToLastIndex) { horizontalGap = this._lastHorizontalGap; } if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; } if(this._useVirtualLayout && !item) { //the item is null, and the layout is virtualized, so we //need to estimate the width of the item. if(this._hasVariableItemDimensions) { if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } } else { //we get here if the item isn't null. it is never null if //the layout isn't virtualized. if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width; itemHeight = item.height; if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { if(itemWidth != cachedWidth) { //update the cache if needed. this will notify //the container that the virtualized layout has //changed, and it the view port may need to be //re-measured. this._widthCache[i] = itemWidth; this.dispatchEventWith(Event.CHANGE); } if(itemHeight != cachedHeight) { this._heightCache[i] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else { if(calculatedTypicalItemWidth >= 0) { item.width = itemWidth = calculatedTypicalItemWidth; } if(calculatedTypicalItemHeight >= 0) { item.height = itemHeight = calculatedTypicalItemHeight; } } } } if(supportsMultipleRows && rowItemCount > 0 && (positionX + itemWidth) > (availableRowWidth - this._paddingRight)) { //we need to restore the previous gap because it will be //subtracted from the x position to get the row width. var previousIndex:int = i - 1; horizontalGap = this._horizontalGap; if(hasFirstHorizontalGap && previousIndex == 0) { horizontalGap = this._firstHorizontalGap; } else if(hasLastHorizontalGap && previousIndex > 0 && previousIndex == secondToLastIndex) { horizontalGap = this._lastHorizontalGap; } //we've reached the end of the row, so go to next break; } if(item) { this._rowItems[this._rowItems.length] = item; item.x = item.pivotX + positionX; } positionX += itemWidth + horizontalGap; //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } rowItemCount++; } //this is the total width of all items in the row var totalRowWidth:Number = positionX - horizontalGap + this._paddingRight - boundsX; if(totalRowWidth > maxRowWidth) { maxRowWidth = totalRowWidth; } rowItemCount = this._rowItems.length; if(supportsMultipleRows) { //in this section, we handle horizontal alignment for the //current row. however, we may need to adjust it later if //the maxRowWidth is smaller than the availableRowWidth. var horizontalAlignOffsetX:Number = 0; if(this._horizontalAlign === HorizontalAlign.RIGHT) { horizontalAlignOffsetX = availableRowWidth - totalRowWidth; } else if(this._horizontalAlign === HorizontalAlign.CENTER) { horizontalAlignOffsetX = Math.round((availableRowWidth - totalRowWidth) / 2); } if(horizontalAlignOffsetX != 0) { for(var j:int = 0; j < rowItemCount; j++) { item = this._rowItems[j]; if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } item.x += horizontalAlignOffsetX; } } } for(j = 0; j < rowItemCount; j++) { item = this._rowItems[j]; var layoutItem:ILayoutDisplayObject = item as ILayoutDisplayObject; if(layoutItem && !layoutItem.includeInLayout) { continue; } //handle all other vertical alignment values. the y position //of all items is set here. switch(this._rowVerticalAlign) { case VerticalAlign.BOTTOM: { item.y = item.pivotY + positionY + maxItemHeight - item.height; break; } case VerticalAlign.MIDDLE: { //round to the nearest pixel when dividing by 2 to //align in the middle item.y = item.pivotY + positionY + Math.round((maxItemHeight - item.height) / 2); break; } default: //top { item.y = item.pivotY + positionY; } } } } while(i < itemCount); //we don't want to keep a reference to any of the items, so clear //this cache this._rowItems.length = 0; if(supportsMultipleRows && (needsWidth || explicitWidth < maxRowWidth)) { //if the maxRowWidth has changed since any row was aligned, the //items in those rows may need to be shifted a bit var contentRowWidth:Number = maxRowWidth; if(contentRowWidth < minWidth) { contentRowWidth = minWidth; } else if(contentRowWidth > maxWidth) { contentRowWidth = maxWidth; } horizontalAlignOffsetX = 0; if(this._horizontalAlign === HorizontalAlign.RIGHT) { horizontalAlignOffsetX = availableRowWidth - contentRowWidth; } else if(this._horizontalAlign === HorizontalAlign.CENTER) { horizontalAlignOffsetX = Math.round((availableRowWidth - contentRowWidth) / 2); } if(horizontalAlignOffsetX != 0) { for(i = 0; i < itemCount; i++) { item = items[i]; if(!item || (item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout)) { continue; } //previously, we used the maxWidth for alignment, //but the max row width may be smaller, so we need //to account for the difference item.x -= horizontalAlignOffsetX; } } } else { contentRowWidth = maxRowWidth; } if(needsWidth) { availableRowWidth = contentRowWidth; } var totalHeight:Number = positionY + maxItemHeight + this._paddingBottom; //the available height is the height of the viewport. if the explicit //height is NaN, we need to calculate the viewport height ourselves //based on the total height of all items. var availableHeight:Number = explicitHeight; if(availableHeight !== availableHeight) //isNaN { availableHeight = totalHeight; if(availableHeight < minHeight) { availableHeight = minHeight; } else if(availableHeight > maxHeight) { availableHeight = maxHeight; } } if(totalHeight < availableHeight && this._verticalAlign != VerticalAlign.TOP) { var verticalAlignOffset:Number = availableHeight - totalHeight; if(this._verticalAlign === VerticalAlign.MIDDLE) { verticalAlignOffset /= 2; } for(i = 0; i < itemCount; i++) { item = items[i]; if(!item || (item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout)) { continue; } item.y += verticalAlignOffset; } } //finally, we want to calculate the result so that the container //can use it to adjust its viewport and determine the minimum and //maximum scroll positions (if needed) if(!result) { result = new LayoutBoundsResult(); } result.contentX = 0; result.contentWidth = maxRowWidth; result.contentY = 0; result.contentHeight = totalHeight; result.viewPortWidth = availableRowWidth; result.viewPortHeight = availableHeight; return result; } /** * @inheritDoc */ public function measureViewPort(itemCount:int, viewPortBounds:ViewPortBounds = null, result:Point = null):Point { if(!result) { result = new Point(); } if(!this._useVirtualLayout) { throw new IllegalOperationError(""measureViewPort() may be called only if useVirtualLayout is true.""); } //this function is very long because it may be called every frame, //in some situations. testing revealed that splitting this function //into separate, smaller functions affected performance. //since the SWC compiler cannot inline functions, we can't use that //feature either. //since viewPortBounds can be null, we may need to provide some defaults var boundsX:Number = viewPortBounds ? viewPortBounds.x : 0; var boundsY:Number = viewPortBounds ? viewPortBounds.y : 0; var minWidth:Number = viewPortBounds ? viewPortBounds.minWidth : 0; var minHeight:Number = viewPortBounds ? viewPortBounds.minHeight : 0; var maxWidth:Number = viewPortBounds ? viewPortBounds.maxWidth : Number.POSITIVE_INFINITY; var maxHeight:Number = viewPortBounds ? viewPortBounds.maxHeight : Number.POSITIVE_INFINITY; var explicitWidth:Number = viewPortBounds ? viewPortBounds.explicitWidth : NaN; var explicitHeight:Number = viewPortBounds ? viewPortBounds.explicitHeight : NaN; //let's figure out if we can show multiple rows var supportsMultipleRows:Boolean = true; var availableRowWidth:Number = explicitWidth; if(availableRowWidth !== availableRowWidth) //isNaN { availableRowWidth = maxWidth; if(availableRowWidth == Number.POSITIVE_INFINITY) { supportsMultipleRows = false; } } if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var i:int = 0; var positionY:Number = boundsY + this._paddingTop; var maxRowWidth:Number = 0; var maxItemHeight:Number = 0; var verticalGap:Number = this._verticalGap; var hasFirstHorizontalGap:Boolean = this._firstHorizontalGap === this._firstHorizontalGap; //!isNaN var hasLastHorizontalGap:Boolean = this._lastHorizontalGap === this._lastHorizontalGap; //!isNaN var secondToLastIndex:int = itemCount - 2; do { if(i > 0) { positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = this._useVirtualLayout ? calculatedTypicalItemHeight : 0; var positionX:Number = boundsX + this._paddingLeft; var rowItemCount:int = 0; //if there are no items in the row (such as when there are no //items in the container!), then we don't want to subtract the //gap when calculating the row width, so default to 0. var horizontalGap:Number = 0; //this first loop sets the x position of items, and it calculates //the total width of all items for(; i < itemCount; i++) { horizontalGap = this._horizontalGap; if(hasFirstHorizontalGap && i == 0) { horizontalGap = this._firstHorizontalGap; } else if(hasLastHorizontalGap && i > 0 && i == secondToLastIndex) { horizontalGap = this._lastHorizontalGap; } if(this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } if(supportsMultipleRows && rowItemCount > 0 && (positionX + itemWidth) > (availableRowWidth - this._paddingRight)) { //we've reached the end of the row, so go to next break; } positionX += itemWidth + horizontalGap; //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } rowItemCount++; } //this is the total width of all items in the row var totalRowWidth:Number = positionX - horizontalGap + this._paddingRight - boundsX; if(totalRowWidth > maxRowWidth) { maxRowWidth = totalRowWidth; } } while(i < itemCount); if(supportsMultipleRows) { if(explicitWidth !== explicitWidth) //isNaN { availableRowWidth = maxRowWidth; if(availableRowWidth < minWidth) { availableRowWidth = minWidth; } else if(availableRowWidth > maxWidth) { availableRowWidth = maxWidth; } } } else { availableRowWidth = maxRowWidth; } var totalHeight:Number = positionY + maxItemHeight + this._paddingBottom; //the available height is the height of the viewport. if the explicit //height is NaN, we need to calculate the viewport height ourselves //based on the total height of all items. var availableHeight:Number = explicitHeight; if(availableHeight !== availableHeight) //isNaN { availableHeight = totalHeight; if(availableHeight < minHeight) { availableHeight = minHeight; } else if(availableHeight > maxHeight) { availableHeight = maxHeight; } } result.x = availableRowWidth; result.y = availableHeight; return result; } /** * @inheritDoc */ public function getNearestScrollPositionForIndex(index:int, scrollX:Number, scrollY:Number, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { result = this.calculateMaxScrollYAndRowHeightOfIndex(index, items, x, y, width, height, result); var maxScrollY:Number = result.x; var rowHeight:Number = result.y; result.x = 0; var bottomPosition:Number = maxScrollY - (height - rowHeight); if(scrollY >= bottomPosition && scrollY <= maxScrollY) { //keep the current scroll position because the item is already //fully visible result.y = scrollY; } else { var topDifference:Number = Math.abs(maxScrollY - scrollY); var bottomDifference:Number = Math.abs(bottomPosition - scrollY); if(bottomDifference < topDifference) { result.y = bottomPosition; } else { result.y = maxScrollY; } } return result; } /** * @inheritDoc */ public function calculateNavigationDestination(items:Vector., index:int, keyCode:uint, bounds:LayoutBoundsResult):int { var result:int = index; if(keyCode == Keyboard.HOME) { if(items.length > 0) { result = 0; } } else if(keyCode == Keyboard.END) { result = items.length - 1; } else if(keyCode == Keyboard.UP) { result--; } else if(keyCode == Keyboard.DOWN) { result++; } if(result < 0) { return 0; } if(result >= items.length) { return items.length - 1; } return result; } /** * @inheritDoc */ public function getScrollPositionForIndex(index:int, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { result = this.calculateMaxScrollYAndRowHeightOfIndex(index, items, x, y, width, height, result); var maxScrollY:Number = result.x; var rowHeight:Number = result.y; if(this._useVirtualLayout) { if(this._hasVariableItemDimensions) { var itemHeight:Number = this._heightCache[index]; if(itemHeight !== itemHeight) //isNaN { itemHeight = this._typicalItem.height; } } else { itemHeight = this._typicalItem.height; } } else { itemHeight = items[index].height; } if(!result) { result = new Point(); } result.x = 0; result.y = maxScrollY - Math.round((height - itemHeight) / 2); return result; } /** * @inheritDoc */ public function getDropIndex(x:Number, y:Number, items:Vector., boundsX:Number, boundsY:Number, width:Number, height:Number):int { if(this._useVirtualLayout) { //if the layout is virtualized, we'll need the dimensions of the //typical item so that we have fallback values when an item is null if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var horizontalGap:Number = this._horizontalGap; var verticalGap:Number = this._verticalGap; var maxItemHeight:Number = 0; var positionY:Number = this._paddingTop; var i:int = 0; var itemCount:int = items.length; do { if(i > 0) { positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = this._useVirtualLayout ? calculatedTypicalItemHeight : 0; var positionX:Number = this._paddingLeft; var rowItemCount:int = 0; for(; i < itemCount; i++) { var item:DisplayObject = items[i]; if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; } if(this._useVirtualLayout && !item) { //the item is null, and the layout is virtualized, so we //need to estimate the width of the item. if(this._hasVariableItemDimensions) { if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } } else { //we get here if the item isn't null. it is never null if //the layout isn't virtualized. if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width; itemHeight = item.height; if(this._useVirtualLayout && this._hasVariableItemDimensions) { if(this._hasVariableItemDimensions) { if(itemWidth != cachedWidth) { this._widthCache[i] = itemWidth; this.dispatchEventWith(Event.CHANGE); } if(itemHeight != cachedHeight) { this._heightCache[i] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else { if(calculatedTypicalItemWidth >= 0) { itemWidth = calculatedTypicalItemWidth; } if(calculatedTypicalItemHeight >= 0) { itemHeight = calculatedTypicalItemHeight; } } } } var endOfRow:Boolean = rowItemCount > 0 && (positionX + itemWidth) > (width - this._paddingRight); if((endOfRow || x < (positionX + (itemWidth / 2))) && y < (positionY + itemHeight + (gap / 2))) { return i; } if(endOfRow) { //we've reached the end of the row, so go to next break; } //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } positionX += itemWidth + horizontalGap; rowItemCount++; } } while(i < itemCount); return itemCount; } /** * @inheritDoc */ public function positionDropIndicator(dropIndicator:DisplayObject, index:int, x:Number, y:Number, items:Vector., width:Number, height:Number):void { if(dropIndicator is IValidating) { IValidating(dropIndicator).validate(); } var horizontalGap:Number = this._horizontalGap; var verticalGap:Number = this._verticalGap; var maxItemHeight:Number = 0; var positionY:Number = this._paddingTop; var i:int = 0; var itemCount:int = items.length; do { if(i > 0) { if(y < (positionY + itemHeight + (verticalGap / 2))) { //if the x/y position is closer to the previous row, //then display the drop indicator at the end of that row var item:DisplayObject = items[i - 1]; dropIndicator.x = item.x + item.width - dropIndicator.width / 2; dropIndicator.y = item.y; dropIndicator.height = item.height; return; } positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = 0; var positionX:Number = this._paddingLeft; var rowItemCount:int = 0; for(; i < itemCount; i++) { item = items[i]; var itemWidth:Number = item.width; var itemHeight:Number = item.height; if(rowItemCount > 0 && (positionX + itemWidth) > (width - this._paddingRight)) { //we've reached the end of the row, so go to next break; } //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } if(i == index) { dropIndicator.x = item.x - dropIndicator.width / 2; dropIndicator.y = item.y; dropIndicator.height = item.height; return; } positionX += itemWidth + horizontalGap; rowItemCount++; } } while(i < itemCount); var lastItem:DisplayObject = items[itemCount - 1]; dropIndicator.x = lastItem.x + lastItem.width - dropIndicator.width / 2; dropIndicator.y = lastItem.y; dropIndicator.height = lastItem.height; } /** * @inheritDoc */ override public function resetVariableVirtualCache():void { this._widthCache.length = 0; this._heightCache.length = 0; } /** * @inheritDoc */ override public function resetVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { delete this._widthCache[index]; delete this._heightCache[index]; if(item) { this._widthCache[index] = item.width; this._heightCache[index] = item.height; this.dispatchEventWith(Event.CHANGE); } } /** * @inheritDoc */ override public function addToVariableVirtualCacheAtIndex(index:int, item:DisplayObject = null):void { var widthValue:* = (item !== null) ? item.width : undefined; var heightValue:* = (item !== null) ? item.height : undefined; this._widthCache.insertAt(index, widthValue); this._heightCache.insertAt(index, heightValue); } /** * @inheritDoc */ override public function removeFromVariableVirtualCacheAtIndex(index:int):void { this._widthCache.removeAt(index); this._heightCache.removeAt(index); } /** * @inheritDoc */ public function getVisibleIndicesAtScrollPosition(scrollX:Number, scrollY:Number, width:Number, height:Number, itemCount:int, result:Vector. = null):Vector. { if(result) { result.length = 0; } else { result = new []; } if(!this._useVirtualLayout) { throw new IllegalOperationError(""getVisibleIndicesAtScrollPosition() may be called only if useVirtualLayout is true.""); } if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; var resultLastIndex:int = 0; var i:int = 0; var positionY:Number = this._paddingTop; var maxItemHeight:Number = 0; var verticalGap:Number = this._verticalGap; var maxPositionY:Number = scrollY + height; var hasFirstHorizontalGap:Boolean = this._firstHorizontalGap === this._firstHorizontalGap; //!isNaN var hasLastHorizontalGap:Boolean = this._lastHorizontalGap === this._lastHorizontalGap; //!isNaN var secondToLastIndex:int = itemCount - 2; do { if(i > 0) { positionY += maxItemHeight + verticalGap; if(positionY >= maxPositionY) { //the following rows will not be visible, so we can stop break; } } //this section prepares some variables needed for the following loop maxItemHeight = calculatedTypicalItemHeight; var positionX:Number = this._paddingLeft; var rowItemCount:int = 0; //this first loop sets the x position of items, and it calculates //the total width of all items for(; i < itemCount; i++) { var horizontalGap:Number = this._horizontalGap; if(hasFirstHorizontalGap && i == 0) { horizontalGap = this._firstHorizontalGap; } else if(hasLastHorizontalGap && i > 0 && i == secondToLastIndex) { horizontalGap = this._lastHorizontalGap; } if(this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; } if(this._hasVariableItemDimensions) { if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } if(rowItemCount > 0 && (positionX + itemWidth) > (width - this._paddingRight)) { //we've reached the end of the row, so go to next break; } if((positionY + itemHeight) > scrollY) { result[resultLastIndex] = i; resultLastIndex++; } positionX += itemWidth + horizontalGap; //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } rowItemCount++; } } while(i < itemCount); return result; } /** * @private */ protected function calculateMaxScrollYAndRowHeightOfIndex(index:int, items:Vector., x:Number, y:Number, width:Number, height:Number, result:Point = null):Point { if(!result) { result = new Point(); } if(this._useVirtualLayout) { //if the layout is virtualized, we'll need the dimensions of the //typical item so that we have fallback values when an item is null if(this._typicalItem is IValidating) { IValidating(this._typicalItem).validate(); } var calculatedTypicalItemWidth:Number = this._typicalItem ? this._typicalItem.width : 0; var calculatedTypicalItemHeight:Number = this._typicalItem ? this._typicalItem.height : 0; } var horizontalGap:Number = this._horizontalGap; var verticalGap:Number = this._verticalGap; var maxItemHeight:Number = 0; var positionY:Number = y + this._paddingTop; var i:int = 0; var itemCount:int = items.length; var isLastRow:Boolean = false; do { if(isLastRow) { break; } if(i > 0) { positionY += maxItemHeight + verticalGap; } //this section prepares some variables needed for the following loop maxItemHeight = this._useVirtualLayout ? calculatedTypicalItemHeight : 0; var positionX:Number = x + this._paddingLeft; var rowItemCount:int = 0; for(; i < itemCount; i++) { var item:DisplayObject = items[i]; if(this._useVirtualLayout && this._hasVariableItemDimensions) { var cachedWidth:Number = this._widthCache[i]; var cachedHeight:Number = this._heightCache[i]; } if(this._useVirtualLayout && !item) { //the item is null, and the layout is virtualized, so we //need to estimate the width of the item. if(this._hasVariableItemDimensions) { if(cachedWidth !== cachedWidth) //isNaN { var itemWidth:Number = calculatedTypicalItemWidth; } else { itemWidth = cachedWidth; } if(cachedHeight !== cachedHeight) //isNaN { var itemHeight:Number = calculatedTypicalItemHeight; } else { itemHeight = cachedHeight; } } else { itemWidth = calculatedTypicalItemWidth; itemHeight = calculatedTypicalItemHeight; } } else { //we get here if the item isn't null. it is never null if //the layout isn't virtualized. if(item is ILayoutDisplayObject && !ILayoutDisplayObject(item).includeInLayout) { continue; } if(item is IValidating) { IValidating(item).validate(); } itemWidth = item.width; itemHeight = item.height; if(this._useVirtualLayout && this._hasVariableItemDimensions) { if(this._hasVariableItemDimensions) { if(itemWidth != cachedWidth) { this._widthCache[i] = itemWidth; this.dispatchEventWith(Event.CHANGE); } if(itemHeight != cachedHeight) { this._heightCache[i] = itemHeight; this.dispatchEventWith(Event.CHANGE); } } else { if(calculatedTypicalItemWidth >= 0) { itemWidth = calculatedTypicalItemWidth; } if(calculatedTypicalItemHeight >= 0) { itemHeight = calculatedTypicalItemHeight; } } } } if(rowItemCount > 0 && (positionX + itemWidth) > (width - this._paddingRight)) { //we've reached the end of the row, so go to next break; } //we don't check this at the beginning of the loop because //it may break to start a new row and then redo this item if(i == index) { isLastRow = true; } //we compare with > instead of Math.max() because the rest //arguments on Math.max() cause extra garbage collection and //hurt performance if(itemHeight > maxItemHeight) { //we need to know the maximum height of the items in the //case where the height of the view port needs to be //calculated by the layout. maxItemHeight = itemHeight; } positionX += itemWidth + horizontalGap; rowItemCount++; } } while(i < itemCount); result.setTo(positionY, maxItemHeight); return result; } } } ",12304,True,2576.9402372354925,median "/** * VERSION: 1.911 * DATE: 2010-06-03 * AS3 * UPDATES AND DOCUMENTATION AT: http://www.greensock.com/transformmanageras3/ **/ package com.greensock.transform { import com.greensock.events.TransformEvent; import com.rockdot.library.view.textfield.UITextField; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.getDefinitionByName; [Event(name=""tmMove"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmScale"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmRotate"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmMouseDown"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmDelete"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmSelectionChange"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmClickOff"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmSeizeCursor"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmReleaseCursor"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmDepthChange"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmDestroy"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmFinishInteractiveMove"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmFinishInteractiveScale"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmFinishInteractiveRotate"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmStartInteractiveMove"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmStartInteractiveScale"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmStartInteractiveRotate"", type=""com.greensock.events.TransformEvent"")] [Event(name=""tmDoubleClick"", type=""com.greensock.events.TransformEvent"")] /** * FlexTransformManager works with TransformManager and makes it easy to add interactive scaling/rotating/moving of * DisplayObjects to your Flex application. It uses an intuitive interface that's similar to most modern drawing applications. * When the user clicks on a managed DisplayObject, a selection box will be drawn around it along with 8 handles for * scaling/rotating. When the mouse is placed just outside of any of the scaling handles, the cursor will change * to indicate that they're in rotation mode. Just like most other applications, the user can hold down the SHIFT * key to select multiple items, to constrain scaling proportions, or to limit the rotation to 45 degree increments. * All the work is done by the TransformManager instance which is compatible with Flash, but FlexTransformManager is * basically a wrapper that makes it compatible with Flex.

    * * FEATURES INCLUDE:
    *
      *
    • Select multiple items and scale/rotate/move them all simultaneously.
    • *
    • Perform virtually any action (transformations, selections, etc.) through code.
    • *
    • Depth management which allows you to programmatically push the selected items forward or backward in the stacking order
    • *
    • Set minScaleX, maxScaleX, minScaleY, and maxScaleY properties on each item
    • *
    • Arrow keys move the selection
    • *
    • You can set the scaleMode of any TransformItem to SCALE_WIDTH_AND_HEIGHT so that the width/height properties are altered instead of scaleX/scaleY. This can be helpful for text-related components because altering the width/height changes only the container's dimensions while retaining the text's size.
    • *
    • There is a 10-pixel wide draggable edge around around the border that users can drag. This is particularly helpful with TextFields/TextAreas.
    • *
    • Define bounds within which the DisplayObjects must stay, and FlexTransformManager will not let the user scale/rotate/move them beyond those bounds
    • *
    • Automatically bring the selected item(s) to the front in the stacking order
    • *
    • The DELETE and BACKSPACE keys can be used to delete the selected DisplayObjects
    • *
    • Lock certain kinds of transformations like rotation, scale, and/or movement
    • *
    • Lock the proportions of the DisplayObjects so that users cannot distort them when scaling
    • *
    • Scale from the DisplayObject's center or from its corners
    • *
    • Listen for Events like SCALE, MOVE, ROTATE, SELECTION_CHANGE, DEPTH_CHANGE, CLICK_OFF, START_INTERACTIVE_MOVE, START_INTERACTIVE_SCALE, START_INTERACTIVE_ROTATE, FINISH_INTERACTIVE_MOVE, FINISH_INTERACTIVE_SCALE, FINISH_INTERACTIVE_ROTATE, DOUBLE_CLICK, SEIZE_CURSOR, RELEASE_CURSOR, and DESTROY
    • *
    • Set the selection box line color and handle thickness
    • *
    • Cursor will automatically change to indicate scale or rotation mode
    • *
    • Optionally hide the center handle
    • *
    • Export transformational data for each item's scale, rotation, and position as well as the TranformManager's settings in XML format so that you can easily save it to a database (or wherever). Then apply it anytime to revert objects to a particular state.
    • *
    • VERY easy to use. In fact, all it takes is one line of code to get it up and running with the default settings.
    • *
    * * NOTES / LIMITATIONS:
    *
      *
    • All DisplayObjects that are managed by a particular FlexTransformManager instance must have the same parent (you can create multiple FlexTransformManager instances if you want)
    • *
    • TextFields cannot be flipped (have negative scales).
    • *
    • TextFields cannot be skewed. Therefore, when a TextField is part of a multi-selection, scaling will be disabled because it could skew the TextField (imagine if a TextField is at a 45 degree angle, and then you selected another item and scaled vertically - your TextField would end up getting skewed).
    • *
    • Due to a limitation in the way Flash reports bounds, items that are extremely close or exactly on top of a boundary (if you define bounds) will be moved about 0.1 pixel away from the boundary when you select them. If an item fills the width and/or height of the bounds, it will be scaled down very slightly (about 0.2 pixels total) to move it away from the bounds and allow accurate collision detection.
    • *

    * * EXAMPLES:

    * To make two Images (myImage1 and myImage2) transformable using the default settings:

    * * <?xml version=""1.0"" encoding=""utf-8""?><br />
    * <mx:Application xmlns:mx=""http://www.adobe.com/2006/mxml"" layout=""absolute"" xmlns:transform=""com.greensock.transform.*"">
    * <transform:FlexTransformManager id=""myManager"" width=""500"" height=""500"">
    * <mx:Image source=""../libs/image1.png"" id=""myImage1"" autoLoad=""true"" x=""100"" y=""100"" />
    * <mx:Image source=""../libs/image2.png"" id=""myImage2"" autoLoad=""true"" x=""0"" y=""300"" />
    * </transform:FlexTransformManager>
    * </mx:Application>

    * * * To make the two Images transformable, constrain their scaling to be proportional (even if the user is not holding * down the shift key), call the onScale function everytime one of the objects is scaled, lock the rotation value of each * Image (preventing rotation), and allow the delete key to appear to delete the selected Image from the stage:

    * * <?xml version=""1.0"" encoding=""utf-8""?>
    * <mx:Application xmlns:mx=""http://www.adobe.com/2006/mxml"" layout=""absolute"" xmlns:transform=""com.greensock.transform.*"" creationComplete=""init()"">
    * <mx:Script>
    * <![CDATA[
    * import com.greensock.events.TransformEvent;
    * private function init():void {
    * myManager.addEventListener(TransformEvent.SCALE, onScale, false, 0, true);
    * }
    * private function onScale($e:TransformEvent):void {
    * trace(""Scaled "" + $e.items.length + "" items"");
    * }
    * ]]>
    * </mx:Script>
    * <transform:FlexTransformManager id=""myManager"" width=""500"" height=""500"" allowDelete=""true"" constrainScale=""true"" lockRotation=""true"">
    * <mx:Image source=""../libs/image1.png"" id=""image1"" autoLoad=""true"" x=""50"" y=""50"" />
    * <mx:Image source=""../libs/image1.png"" id=""image2"" autoLoad=""true"" x=""100"" y=""200"" />
    * </transform:FlexTransformManager>
    * </mx:Application>

    * * Copyright 2010, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/eula.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com */ public class FlexTransformManager extends Canvas { public static const VERSION:Number = 1.911; /** @private **/ protected static var _flexTF:UITextField; //Just ensures that the UITextField class is embedded for use in TransformItem. /** @private **/ protected static var _initted:Boolean; /** @private **/ protected static var _nonStandardScalingClasses:Array; //Classes that will be treated like TextFields where their width and height is scaled instead of scaleX/scaleY /** @private In Flex 4, children are instantiated in a delayed manner, so we need to keep track of the selectedTargetObjects so that we can plug them in as soon as the instance is added to the stage. **/ protected var _selectedTargetObjects:Array; /** @private **/ protected var _manager:TransformManager; /** * Constructor * * @param $vars An object specifying any properties that should be set upon instantiation, like {scaleFromCenter:true, lockRotation:true, bounds:new Rectangle(0, 0, 500, 300)}. */ public function FlexTransformManager($vars:Object = null) { super(); if (!_initted) { if (TransformManager.VERSION < 1.9) { trace(""TransformManager Error: You have an outdated TransformManager-related class file. You may need to clear your ASO files. Please make sure you're using the latest version of TransformManager, FlexTransformItem, and FlexTransformItemTF, available from www.greensock.com.""); } _nonStandardScalingClasses = []; //these classes will be scaled by changing their width/height instead of scaleX/scaleY (this is preferred for certain text-related components so that only the container resizes instead of the text. addNonStandardScalingClass(""mx.controls.TextArea"", TransformManager.SCALE_WIDTH_AND_HEIGHT, true); addNonStandardScalingClass(""spark.components.TextArea"", TransformManager.SCALE_WIDTH_AND_HEIGHT, true); addNonStandardScalingClass(""mx.controls.TextInput"", TransformManager.SCALE_WIDTH_AND_HEIGHT, true); addNonStandardScalingClass(""spark.components.TextInput"", TransformManager.SCALE_WIDTH_AND_HEIGHT, true); addNonStandardScalingClass(""mx.core.UITextField"", TransformManager.SCALE_WIDTH_AND_HEIGHT, true); addNonStandardScalingClass(""mx.controls.RichTextEditor"", TransformManager.SCALE_WIDTH_AND_HEIGHT, true); addNonStandardScalingClass(""spark.components.RichEditableText"", TransformManager.SCALE_WIDTH_AND_HEIGHT, true); addNonStandardScalingClass(""mx.controls.Label"", TransformManager.SCALE_WIDTH_AND_HEIGHT, false); addNonStandardScalingClass(""spark.components.Label"", TransformManager.SCALE_WIDTH_AND_HEIGHT, false); _initted = true; } _manager = new TransformManager($vars); super.verticalScrollPolicy = ""off""; super.horizontalScrollPolicy = ""off""; this.addEventListener(Event.ADDED_TO_STAGE, onAddToStage, false, 1, true); } /** @private **/ protected static function addNonStandardScalingClass($classPath:String, $scaleMode:String, $hasSelectableText:Boolean):void { var type:Object; try { type = getDefinitionByName($classPath); } catch ($e:Error) { } if (type != null) { _nonStandardScalingClasses[_nonStandardScalingClasses.length] = {type:type, scaleMode:$scaleMode, hasSelectableText:$hasSelectableText}; } } /** @private **/ protected function onAddToStage($e:Event):void { for (var i:int = this.numChildren - 1; i > -1; i--) { autoAddChild(this.getChildAt(i)); } if (_manager.bounds == null) { _manager.bounds = new Rectangle(0, 0, this.width, this.height); } if (_selectedTargetObjects != null) { _manager.selectedTargetObjects = _selectedTargetObjects; } } /** * In order for a DisplayObject to be managed by FlexTransformManger, it must first be added via addItem(). When the * DisplayObject is added, a TransformItem instance is automatically created and associated with the DisplayObject. * If you need to set item-specific settings like minScaleX, maxScaleX, etc., you would set those via the TransformItem * instance. addItem() returns a TransformItem instance, but you can retrieve it anytime with the getItem() * method (just pass it your DisplayObject, like var myItem:TransformItem = myManager.getItem(myDisplayObject). * * @param $targetObject The DisplayObject to be managed * @param $scaleMode Either TransformManager.SCALE_NORMAL for normal scaleX/scaleY scaling or TransformManager.SCALE_WIDTH_AND_HEIGHT if you prefer that FlexTransformManager alters the width/height properties instead. * @param $hasSelectableText If true, this prevents dragging of the object unless clicking on the edges/border or center handle, and allows the DELETE key to be pressed without deleting the object itself. It will also force the scaleMode to TransformManager.SCALE_WIDTH_AND_HEIGHT. * @return TransformItem instance */ public function addItem($targetObject:DisplayObject, $scaleMode:String=""scaleNormal"", $hasSelectableText:Boolean=false):TransformItem { if ($targetObject.parent != this) { super.addChildAt($targetObject, this.numChildren); } return _manager.addItem($targetObject, $scaleMode, $hasSelectableText); } /** * Same as addItem() but accepts an Array containing multiple DisplayObjects. * * @param $targetObjects An Array of DisplayObject to be managed * @param $scaleMode Either TransformManager.SCALE_NORMAL for normal scaleX/scaleY scaling or TransformManager.SCALE_WIDTH_AND_HEIGHT if you prefer that FlexTransformManager alters the width/height properties instead. * @param $hasSelectableText If true, this prevents dragging of the objects unless clicking on the edges/border or center handle, and allows the DELETE key to be pressed without deleting the object itself. It will also force the scaleMode to TransformManager.SCALE_WIDTH_AND_HEIGHT. * @return An Array of corresponding TransformItems that are created */ public function addItems($targetObjects:Array, $scaleMode:String=""scaleNormal"", $hasSelectableText:Boolean=false):Array { for (var i:int = 0; i < $targetObjects.length; i++) { if ($targetObjects[i].parent != this) { super.addChild($targetObjects[i]); } } return _manager.addItems($targetObjects, $scaleMode, $hasSelectableText); } /** * Adds a child and performs an addItem() so that the new child is managed. * * @param $child The child DisplayObject * @return DisplayObject */ override public function addChild($child:DisplayObject):DisplayObject { var mc:DisplayObject = super.addChild($child); autoAddChild($child); return mc; } /** @private **/ protected function autoAddChild($child:DisplayObject):void { var i:int, ignored:Array = _manager.ignoredObjects; for (i = 0; i < ignored.length; i++) { if (ignored[i] == $child) { return; } } if (_manager != null && $child.name != ""__dummyBox_mc"" && $child.name != ""__selection_mc"" && $child.name.substr(0, 9) != ""__tmProxy"") { var scaleMode:String = TransformManager.SCALE_NORMAL, hasSelectableText:Boolean = false; for (i = _nonStandardScalingClasses.length - 1; i > -1; i--) { if ($child is _nonStandardScalingClasses[i].type) { scaleMode = _nonStandardScalingClasses[i].scaleMode; hasSelectableText = _nonStandardScalingClasses[i].hasSelectableText; } } addItem($child, scaleMode, hasSelectableText); } } /** * Adds a child at a particular index and then performs an addItem() to ensure the item is managed * * @param $child The child DisplayObject to add * @param $index The index number in the display list at which to add the child * @return DisplayObject */ override public function addChildAt($child:DisplayObject, $index:int):DisplayObject { var mc:DisplayObject = super.addChildAt($child, $index); autoAddChild($child); return mc; } /** * Removes an item. Calling this on an item will NOT delete the DisplayObject - it just prevents it from being affected by this FlexTransformManager anymore. * * @param $item Either the DisplayObject or the associated TransformItem that should be removed */ public function removeItem($item:*):void { _manager.removeItem($item); } /** * Removes a child DisplayObject * * @param $child Child to remove * @return DisplayObject */ override public function removeChild($child:DisplayObject):DisplayObject { _manager.removeItem($child); return super.removeChild($child); } /** * Removes a child from a particular index number in the display list * * @param $index Index number from which to remove the child * @return DisplayObject */ override public function removeChildAt($index:int):DisplayObject { _manager.removeItem(this.getChildAt($index)); return super.removeChildAt($index); } /** * Allows you to have FlexTransformManager ignore clicks on a particular DisplayObject (handy for buttons, color pickers, etc.). The DisplayObject CANNOT be a child of a targetObject * * @param $object DisplayObject that should be ignored */ public function addIgnoredObject($object:DisplayObject):void { _manager.addIgnoredObject($object); } /** * Removes an ignored DisplayObject so that its clicks are no longer ignored. * * @param $object DisplayObject that should not be ignored anymore */ public function removeIgnoredObject($object:DisplayObject):void { _manager.removeIgnoredObject($object); } /** * Allows listening for the following events: *
      *
    • TransformEvent.MOVE
    • *
    • TransformEvent.SCALE
    • *
    • TransformEvent.ROTATE
    • *
    • TransformEvent.DELETE
    • *
    • TransformEvent.SELECTION_CHANGE
    • *
    • TransformEvent.CLICK_OFF
    • *
    • TransformEvent.SEIZE_CURSOR
    • *
    • TransformEvent.RELEASE_CURSOR
    • *
    • TransformEvent.DEPTH_CHANGE
    • *
    • TransformEvent.DESTROY
    • *
    • TransformEvent.START_INTERACTIVE_MOVE
    • *
    • TransformEvent.START_INTERACTIVE_SCALE
    • *
    • TransformEvent.START_INTERACTIVE_ROTATE
    • *
    • TransformEvent.FINISH_INTERACTIVE_MOVE
    • *
    • TransformEvent.FINISH_INTERACTIVE_SCALE
    • *
    • TransformEvent.FINISH_INTERACTIVE_ROTATE
    • *
    • TransformEvent.DOUBLE_CLICK
    • *
    * * @param $type Event type * @param $listener Listener function * @param $useCapture Use capture phase * @param $priority Priority * @param $useWeakReference Use weak reference */ override public function addEventListener($type:String, $listener:Function, $useCapture:Boolean=false, $priority:int=0, $useWeakReference:Boolean=false):void { var isTransform:Boolean = false; switch ($type) { case TransformEvent.CLICK_OFF: case TransformEvent.DELETE: case TransformEvent.DEPTH_CHANGE: case TransformEvent.DESELECT: case TransformEvent.DESTROY: case TransformEvent.MOUSE_DOWN: case TransformEvent.MOVE: case TransformEvent.ROTATE: case TransformEvent.SCALE: case TransformEvent.SEIZE_CURSOR: case TransformEvent.RELEASE_CURSOR: case TransformEvent.SELECTION_CHANGE: case TransformEvent.START_INTERACTIVE_MOVE: case TransformEvent.START_INTERACTIVE_SCALE: case TransformEvent.START_INTERACTIVE_ROTATE: case TransformEvent.FINISH_INTERACTIVE_MOVE: case TransformEvent.FINISH_INTERACTIVE_SCALE: case TransformEvent.FINISH_INTERACTIVE_ROTATE: case TransformEvent.DOUBLE_CLICK: case TransformEvent.UPDATE: _manager.addEventListener($type, $listener, $useCapture, $priority, $useWeakReference); isTransform = true; break; } if (!isTransform) { super.addEventListener($type, $listener, $useCapture, $priority, $useWeakReference); } } /** * Removes an Event listener * * @param $type Type of Event * @param $listener Listener * @param $useCapture Use capture phase */ override public function removeEventListener($type:String, $listener:Function, $useCapture:Boolean=false):void { var isTransform:Boolean = false; switch ($type) { case TransformEvent.CLICK_OFF: case TransformEvent.DELETE: case TransformEvent.DEPTH_CHANGE: case TransformEvent.DESELECT: case TransformEvent.DESTROY: case TransformEvent.MOUSE_DOWN: case TransformEvent.MOVE: case TransformEvent.ROTATE: case TransformEvent.SCALE: case TransformEvent.SEIZE_CURSOR: case TransformEvent.RELEASE_CURSOR: case TransformEvent.SELECTION_CHANGE: case TransformEvent.START_INTERACTIVE_MOVE: case TransformEvent.START_INTERACTIVE_SCALE: case TransformEvent.START_INTERACTIVE_ROTATE: case TransformEvent.FINISH_INTERACTIVE_MOVE: case TransformEvent.FINISH_INTERACTIVE_SCALE: case TransformEvent.FINISH_INTERACTIVE_ROTATE: case TransformEvent.DOUBLE_CLICK: case TransformEvent.UPDATE: _manager.removeEventListener($type, $listener, $useCapture); isTransform = true; break; } if (!isTransform) { super.removeEventListener($type, $listener, $useCapture); } } /** Removes all children **/ override public function removeAllChildren():void { _manager.removeAllItems(); super.removeAllChildren(); } /** * Selects a particular TransformItem or DisplayObject (you must have already added the DisplayObject * to FlexTransformManager in order for it to be selectable - use addItem() for that) * * @param $item The TransformItem or DisplayObject that should be selected * @param $addToSelection If true, any currently selected items will remain selected and the new item/DisplayObject will be added to the selection. * @return The TransformItem that was selected. */ public function selectItem($item:*, $addToSelection:Boolean=false):void { _manager.selectItem($item, $addToSelection); } /** * Selects an Array of TransformItems and/or DisplayObjects. (you must have already added the DisplayObjects * to FlexTransformManager in order for it to be selectable - use addItem() or addItems() for that) * * @param $items An Array of TransformItems and/or DisplayObjects to be selected * @param $addToSelection If true, any currently selected items will remain selected and the new items/DisplayObjects will be added to the selection. * @return An Array of TransformItems that were selected */ public function selectItems($items:Array, $addToSelection:Boolean=false):void { _manager.selectItems($items, $addToSelection); } /** * Deselects a TransformItem or DisplayObject. * * @param $item The TransformItem or DisplayObject that should be deselected * @return The TransformItem that was deselected */ public function deselectItem($item:*):void { _manager.deselectItem($item); } /** * Deletes all selected items. * * @param $e Accepts an optional Event in case you want to use this as an event handler */ public function deleteSelection($e:Event = null):void { _manager.deleteSelection($e); } /** Deselects all items **/ public function deselectAll():void { _manager.deselectAll(); } /** * Determines whether or not a particular DisplayObject or TranformItem is currently selected. * * @param $item The TransformItem or DisplayObject whose selection status needs to be checked * @return If true, the item/DisplayObject is currently selected */ public function isSelected($item:*):Boolean { return _manager.isSelected($item); } /** * Refreshes the selection box/handles. * * @param $centerOrigin If true, the origin (axis of rotation/scaling) will be automatically centered. */ public function updateSelection($centerOrigin:Boolean=true):void { _manager.updateSelection($centerOrigin); } /** * Gets the TransformItem associated with a particular DisplayObject (if any). This can be useful if you * need to set item-specific properties like minScaleX/maxScaleX, etc. * * @param $targetObject The DisplayObject with which the TransformItem is associated * @return The associated TransformItem */ public function getItem($targetObject:DisplayObject):TransformItem { return _manager.getItem($targetObject); } /** Moves the selection down one level. **/ public function moveSelectionDepthDown():void { _manager.moveSelectionDepthDown(); } /** Moves the selection up one level. **/ public function moveSelectionDepthUp():void { _manager.moveSelectionDepthUp(); } /** * Gets the center point of the current selection * * @return Center Point of the current selection */ public function getSelectionCenter():Point { return _manager.getSelectionCenter(); } /** * Gets the bounding Rectangle of the current selection (not including handles) * * @param targetCoordinateSpace The display object that defines the coordinate system to use. * @return Bounding Rectangle of the current selection (not including handles) */ public function getSelectionBounds(targetCoordinateSpace:DisplayObject=null):Rectangle { return _manager.getSelectionBounds(targetCoordinateSpace); } /** * Gets the bounding Rectangle of the current selection (including handles) * * @param targetCoordinateSpace The display object that defines the coordinate system to use. * @return Bounding Rectangle of the current selection (including handles) */ public function getSelectionBoundsWithHandles(targetCoordinateSpace:DisplayObject=null):Rectangle { return _manager.getSelectionBoundsWithHandles(targetCoordinateSpace); } /** * Gets the width of the selection as if it were not rotated. * * @return The unrotated selection width */ public function getUnrotatedSelectionWidth():Number { return _manager.getUnrotatedSelectionWidth(); } /** * Gets the height of the selection as if it were not rotated. * * @return The unrotated selection height */ public function getUnrotatedSelectionHeight():Number { return _manager.getUnrotatedSelectionHeight(); } /** * Moves the selected items by a certain number of pixels on the x axis and y axis * * @param $x Number of pixels to move the selected items along the x-axis (can be negative or positive) * @param $y Number of pixels to move the selected items along the y-axis (can be negative or positive) * @param $dispatchEvents If false, no MOVE Events will be dispatched */ public function moveSelection($x:Number, $y:Number, $dispatchEvents:Boolean=true):void { _manager.moveSelection($x, $y, $dispatchEvents); } /** * Scales the selected items along the x- and y-axis using multipliers. Keep in mind that these are * not absolute values, so if a selected item's scaleX is 2 and you scaleSelection(2, 1), its new * scaleX would be 4 because 2 * 2 = 4. * * @param $sx Multiplier for scaling along the selection box's x-axis (which may or may not be the same as the selected item's y-axis, depending on whether or not multiple items are selected and if any are rotated) * @param $sy Multiplier for scaling along the selection box's y-axis (which may or may not be the same as the selected item's y-axis, depending on whether or not multiple items are selected and if any are rotated) * @param $dispatchEvents If false, no SCALE events will be dispatched */ public function scaleSelection($sx:Number, $sy:Number, $dispatchEvents:Boolean=true):void { _manager.scaleSelection($sx, $sy, $dispatchEvents); } /** * Rotates the selected items by a particular angle (in Radians). This is NOT an absolute value, so if one * of the selected items' rotation property is Math.PI and you rotateSelection(Math.PI), the new * angle would be Math.PI * 2. * * @param $angle Angle (in Radians) that should be added to the selected items' current rotation * @param $dispatchEvents If false, no ROTATE events will be dispatched */ public function rotateSelection($angle:Number, $dispatchEvents:Boolean=true):void { _manager.rotateSelection($angle, $dispatchEvents); } /** Destroys the FlexTransformManager instance, removing all items and preparing it for garbage collection **/ public function destroy():void { _manager.destroy(); _manager = null; if (this.parent != null) { this.parent.removeChild(this); } } //---- XML EXPORTING AND APPLYING ------------------------------------------------------------------------------ /** * A common request is to capture the current state of each item's scale/rotation/position and the TransformManager's * settings in an easy-to-store format so that the data can be reloaded and applied later; exportFullXML() * returns an XML object containing exactly that. The TransformManager's settings and each item's transform data is * stored in the following format:
    * @example <transformManager> <settings allowDelete=""1"" allowMultiSelect=""1"" autoDeselect=""1"" constrainScale=""0"" lockScale=""1"" scaleFromCenter=""0"" lockRotation=""0"" lockPosition=""0"" arrowKeysMove=""0"" forceSelectionToFront=""1"" lineColor=""3381759"" handleColor=""16777215"" handleSize=""8"" paddingForRotation=""12"" hideCenterHandle=""0""/> <items> <item name=""mc1"" level=""1"" a=""0.9999847412109375"" b=""0"" c=""0"" d=""0.9999847412109375"" tx=""79.2"" ty=""150.5"" xOffset=""-23.4"" yOffset=""-34.35"" rawWidth=""128.6"" rawHeight=""110.69999999999999"" scaleMode=""scaleNormal"" hasSelectableText=""0"" minScaleX=""-Infinity"" maxScaleX=""Infinity"" minScaleY=""-Infinity"" maxScaleY=""Infinity""/> <item name=""mc2"" level=""18"" a=""0.7987213134765625"" b=""0.2907257080078125"" c=""-0.2907257080078125"" d=""0.7987213134765625"" tx=""222.5"" ty=""92.25"" xOffset=""0"" yOffset=""0"" rawWidth=""287.85"" rawHeight=""215.8"" scaleMode=""scaleNormal"" hasSelectableText=""0"" minScaleX=""-Infinity"" maxScaleX=""Infinity"" minScaleY=""-Infinity"" maxScaleY=""Infinity""/> <item name=""text_ti"" level=""4"" a=""1"" b=""0"" c=""0"" d=""1"" tx=""32"" ty=""303.95"" xOffset=""-2"" yOffset=""-2"" rawWidth=""188"" rawHeight=""37.2"" scaleMode=""scaleWidthAndHeight"" hasSelectableText=""1"" minScaleX=""-Infinity"" maxScaleX=""Infinity"" minScaleY=""-Infinity"" maxScaleY=""Infinity""/> </items> </transformManager> * * You can use applyFullXML() to reapply the exported XML. * * @see #exportItemXML() * @see #applyItemXML() * @see #applyFullXML() * @see #exportSettingsXML() * @see #applySettingsXML() * @return An XML representation of the current state of the TransformManager instance and all of the items it is managing. */ public function exportFullXML():XML { return _manager.exportFullXML(); } /** * Applies XML generated by exportFullXML() to the TransformManager instance including all settings * and each item's scale/rotation/position. This does not load any external images/assets - you must do that separately. * Typically it's best to fully load the assets first and add them to the display list before calling applyFullXML(). * When applyFullXML() is called, it attempts to find the targetObjects in the display list based on their names, * but for each one that cannot be found, a new Sprite will be created and added as a placeholder, filled with the * placeholderColor and named identically. An array of those placeholders (if any) is returned by * applyFullXML() which makes it easy to loop through and load your images/assets directly into those * placeholder Sprites. Feel free to add visual preloaders, alter the look of the Sprites, etc.

    * * @see #exportItemXML() * @see #applyItemXML() * @see #exportFullXML() * @see #exportSettingsXML() * @see #applySettingsXML() * @param xml An XML object containing data about the settings and each item's position/scale/rotation. This XML is typically created using exportFullXML(). * @param defaultParent If no items have been added to the TransformManager yet, it won't know which DisplayObjectContainer to look in for targetObjects, so it is important to explicitly tell TransformManager what default parent to use. * @param placeholderColor If an item's targetObject cannot be found in the display list (based on its name), it will create a new Sprite and fill it with this color, using it as a placeholder. * @return An array of placeholders that were created for missing targetObjects (if any). You can loop through these and load your assets accordingly. Keep in mind that the placeholders will have the same name as was defined in the XML (from the original targetObject). */ public function applyFullXML(xml:XML, defaultParent:DisplayObjectContainer, placeholderColor:uint=0xCCCCCC):Array { return _manager.applyFullXML(xml, defaultParent, placeholderColor); } /** * Exports transform data (scale/rotation/position) of a particular DisplayObject in XML format so that * it can be saved to a database or elsewhere easily and then reapplied later. If you'd like to export all * settings and every item's data, use the exportFullXML() instead. exportItemXML() * returns an XML object in the following format:
    * @example <item name=""mc1"" level=""1"" a=""0.98"" b=""0"" c=""0"" d=""0.9"" tx=""79.2"" ty=""150.5"" xOffset=""-23.4"" yOffset=""-34.35"" rawWidth=""128.6"" rawHeight=""110.7"" scaleMode=""scaleNormal"" hasSelectableText=""0"" minScaleX=""-Infinity"" maxScaleX=""Infinity"" minScaleY=""-Infinity"" maxScaleY=""Infinity""/> * * @see #applyItemXML() * @see #exportFullXML() * @see #applyFullXML() * @see #exportSettingsXML() * @see #applySettingsXML() * @param targetObject The DisplayObject whose transform data you'd like to export. * @return An XML object describing the targetObject's transform data (scale/rotation/position) and a few other TransformManager-related settings. */ public function exportItemXML(targetObject:DisplayObject):XML { return _manager.exportItemXML(targetObject); } /** * Applies XML generated by exportItemXML() to the TransformManager instance including all transform * data like scale/rotation/position. This does not load any external images/assets - you must do that separately. * Typically it's best to fully load the asset first and add them to the display list before calling applyItemXML(). * When applyItemXML() is called, it attempts to find the targetObject in the display list based on * its name, but if it cannot be found, a new Sprite will be created and added as a placeholder, filled with the * placeholderColor and named identically. To load all of the settings and every item's transform * data, use applyFullXML() instead.

    * * @see #exportItemXML() * @see #exportFullXML() * @see #applyFullXML() * @see #exportSettingsXML() * @see #applySettingsXML() * @param xml An XML object containing data about the item's position/scale/rotation. This XML is typically created using exportItemXML(). * @param defaultParent If no items have been added to the TransformManager yet, it won't know which DisplayObjectContainer to look in for targetObject, so it is important to explicitly tell TransformManager what default parent to use. * @param placeholderColor If the targetObject cannot be found in the display list (based on its name), it will create a new Sprite and fill it with this color, using it as a placeholder. * @return The DisplayObject associated with the item (a placeholder Sprite if the targeObject wasn't found in the display list). */ public function applyItemXML(xml:XML, defaultParent:DisplayObjectContainer=null, placeholderColor:uint=0xCCCCCC):DisplayObject { return _manager.applyItemXML(xml, defaultParent, placeholderColor); } /** * Exports the TransformManager's settings in XML format so that it can be saved to a database or elsewhere easily * and then reapplied later. exportSettingsXML() * returns an XML object in the following format:
    * @example <settings allowDelete=""1"" allowMultiSelect=""1"" autoDeselect=""1"" constrainScale=""0"" lockScale=""1"" scaleFromCenter=""0"" lockRotation=""0"" lockPosition=""0"" arrowKeysMove=""0"" forceSelectionToFront=""1"" lineColor=""3381759"" handleColor=""16777215"" handleSize=""8"" paddingForRotation=""12"" hideCenterHandle=""0""/> * * @see #exportItemXML() * @see #applyItemXML() * @see #exportFullXML() * @see #applyFullXML() * @see #applySettingsXML() * @return An XML object containing settings data about the TransformManager. */ public function exportSettingsXML():XML { return _manager.exportSettingsXML(); } /** * Applies settings XML generated by exportSettingsXML() to the TransformManager instance. * This determines things like allowDelete, autoDeselect, lockScale, lockPosition, etc.

    * * @see #exportItemXML() * @see #applyItemXML() * @see #exportFullXML() * @see #applyFullXML() * @see #exportSettingsXML() * @see #applySettingsXML() * @param xml An XML object containing settings data about the TransformManager (typically exported by exportSettingsXML()). */ public function applySettingsXML(xml:XML):void { _manager.applySettingsXML(xml); } //---- GETTERS / SETTERS ----------------------------------------------------------------------------------------------------- /** The TransformManager instance associated with the FlexTransformManager **/ public function get manager():TransformManager { return _manager; } /** Enable or disable the entire FlexTransformManager. **/ override public function get enabled():Boolean { return _manager.enabled; } override public function set enabled($b:Boolean):void { //Gives us a way to enable/disable all FlexTransformItems if (_manager != null) { _manager.enabled = $b; } super.enabled = $b; } /** width **/ override public function set width($n:Number):void { if (this.height != 0) { _manager.bounds = new Rectangle(0, 0, $n, this.height); } else if (this.parent != null) { _manager.bounds = new Rectangle(0, 0, $n, this.parent.height); } super.width = $n; } /** height **/ override public function set height($n:Number):void { if (this.width != 0) { _manager.bounds = new Rectangle(0, 0, this.width, $n); } else if (this.parent != null) { _manager.bounds = new Rectangle(0, 0, this.parent.width, $n); } super.height = $n; } /** @private **/ override public function set verticalScrollPolicy($value:String):void { trace(""FlexTransformManager must have verticalScrollPolicy set to 'off'.""); } /** @private **/ override public function set horizontalScrollPolicy($value:String):void { trace(""FlexTransformManager must have horizontalScrollPolicy set to 'off'.""); } /** The scaleX of the overall selection box **/ public function get selectionScaleX():Number { return _manager.selectionScaleX; } public function set selectionScaleX($n:Number):void { _manager.selectionScaleX = $n; } /** The scaleY of the overall selection box **/ public function get selectionScaleY():Number { return _manager.selectionScaleY; } public function set selectionScaleY($n:Number):void { _manager.selectionScaleY = $n; } /** The rotation of the overall selection box **/ public function get selectionRotation():Number { return _manager.selectionRotation; } public function set selectionRotation($n:Number):void { _manager.selectionRotation = $n; } /** The x-coordinte of the overall selection box (same as the origin) **/ public function get selectionX():Number { return _manager.selectionX; } public function set selectionX($n:Number):void { _manager.selectionX = $n; } /** The y-coordinte of the overall selection box (same as the origin) **/ public function get selectionY():Number { return _manager.selectionY; } public function set selectionY($n:Number):void { _manager.selectionY = $n; } /** All of the TransformItem instances that are managed by this FlexTransformManager (regardless of whether or not they're selected) **/ public function get items():Array { return _manager.items; } /** All of the targetObjects (DisplayObjects) that are managed by this FlexTransformManager (regardless of whether or not they're selected) **/ public function get targetObjects():Array { return _manager.targetObjects; } /** The currently selected targetObjects (DisplayObjects). For the associated TransformItems, use selectedItems. **/ public function get selectedTargetObjects():Array { return _manager.selectedTargetObjects; } public function set selectedTargetObjects($a:Array):void { _manager.selectedTargetObjects = _selectedTargetObjects = $a; } /** The currently selected TransformItems (for the associated DisplayObjects, use selectedTargetObjects) **/ public function get selectedItems():Array { return _manager.selectedItems; } public function set selectedItems($a:Array):void { _manager.selectedItems = $a; } /** To constrain items to only scaling proportionally, set this to true [default: false] **/ public function get constrainScale():Boolean { return _manager.constrainScale; } public function set constrainScale($b:Boolean):void { _manager.constrainScale = $b; } /** Prevents scaling [default: false] **/ public function get lockScale():Boolean { return _manager.lockScale; } public function set lockScale($b:Boolean):void { _manager.lockScale = $b; } /** If true, scaling occurs from the center of the selection instead of the corners. [default: false] **/ public function get scaleFromCenter():Boolean { return _manager.scaleFromCenter; } public function set scaleFromCenter($b:Boolean):void { _manager.scaleFromCenter = $b; } /** Prevents rotating [default: false] **/ public function get lockRotation():Boolean { return _manager.lockRotation; } public function set lockRotation($b:Boolean):void { _manager.lockRotation = $b; } /** Prevents moving [default: false] **/ public function get lockPosition():Boolean { return _manager.lockPosition; } public function set lockPosition($b:Boolean):void { _manager.lockPosition = $b; } /** If true, multiple items can be selected (by holding down the SHIFT or CONTROL keys and clicking) [default: true] **/ public function get allowMultiSelect():Boolean { return _manager.allowMultiSelect; } public function set allowMultiSelect($b:Boolean):void { _manager.allowMultiSelect = $b } /** If true, when the user presses the DELETE (or BACKSPACE) key, the selected item(s) will be deleted (except items with hasSelectableText set to true) [default: false] **/ public function get allowDelete():Boolean { return _manager.allowDelete; } public function set allowDelete($b:Boolean):void { _manager.allowDelete = $b; } /** When the user clicks anywhere OTHER than on one of the TransformItems, all are deselected [default: true] **/ public function get autoDeselect():Boolean { return _manager.autoDeselect; } public function set autoDeselect($b:Boolean):void { _manager.autoDeselect = $b; } /** Controls the line color of the selection box and handles [default: 0x3399FF] **/ public function get lineColor():uint { return _manager.lineColor; } public function set lineColor($n:uint):void { _manager.lineColor = $n; } /** Controls the fill color of the handle [default: 0xFFFFFF] **/ public function get handleFillColor():uint { return _manager.handleFillColor; } public function set handleFillColor($n:uint):void { _manager.handleFillColor = $n; } /** Controls the handle size (in pixels) [default: 8] **/ public function get handleSize():Number { return _manager.handleSize; } public function set handleSize($n:Number):void { _manager.handleSize = $n; } /** Determines the amount of space outside each of the four corner scale handles that will trigger rotation mode [default: 12] **/ public function get paddingForRotation():Number { return _manager.paddingForRotation; } public function set paddingForRotation($n:Number):void { _manager.paddingForRotation = $n; } /** A Rectangle defining the boundaries for movement/scaling/rotation. [default:null] **/ public function get bounds():Rectangle { return _manager.bounds; } public function set bounds($r:Rectangle):void { _manager.bounds = $r; } /** When true, new selections are forced to the front of the display list of the container DisplayObjectContainer [default: true] **/ public function get forceSelectionToFront():Boolean { return _manager.forceSelectionToFront; } public function set forceSelectionToFront($b:Boolean):void { _manager.forceSelectionToFront = $b; } /** If true, the arrow keys on the keyboard will move the selected items when pressed [default: false] **/ public function get arrowKeysMove():Boolean { return _manager.arrowKeysMove; } public function set arrowKeysMove($b:Boolean):void { _manager.arrowKeysMove = $b; } /** The TransformManager instances associated with this FlexTransformManager **/ public function get transformManager():TransformManager { return _manager; } /** Sometimes you want FlexTransformManager to ignore clicks on certain DisplayObjects, like buttons, color pickers, etc. Those items should populate the ignoreObjects Array. The DisplayObject CANNOT be a child of a targetObject. **/ public function get ignoredObjects():Array { return _manager.ignoredObjects; } public function set ignoredObjects($a:Array):void { _manager.ignoredObjects = $a; } /** To hide the center scale handle, set this to true [default: false **/ public function get hideCenterHandle():Boolean { return _manager.hideCenterHandle; } public function set hideCenterHandle($b:Boolean):void { _manager.hideCenterHandle = $b; } } }",12117,False,2153.2372104430788,median "/** * VERSION: 1.698 * DATE: 2012-03-29 * AS3 (AS2 version is also available) * UPDATES AND DOCS AT: http://www.greensock.com/timelinemax/ **/ package com.greensock { import com.greensock.core.*; import com.greensock.OverwriteManager; import com.greensock.events.TweenEvent; import flash.events.*; /** * TimelineMax extends TimelineLite, offering exactly the same functionality plus useful * (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, * currentLabel, addCallback(), removeCallback(), tweenTo(), tweenFromTo(), getLabelAfter(), getLabelBefore(), * and getActive() (and probably more in the future). It is the ultimate sequencing tool. * Think of a TimelineMax instance like a virtual MovieClip timeline or a container where * you place tweens (or other timelines) over the course of time. You can: * *
      *
    • build sequences easily by adding tweens with the append(), prepend(), insert(), appendMultiple(), * prependMultiple(), and insertMultiple() methods. Tweens can overlap as much as you want and you have * complete control over where they get placed on the timeline.
    • * *
    • add labels, play(), stop(), gotoAndPlay(), gotoAndStop(), restart(), tweenTo() and even reverse()!
    • * *
    • nest timelines within timelines as deeply as you want.
    • * *
    • set the progress of the timeline using its currentProgress property. For example, to skip to * the halfway point, set myTimeline.currentProgress = 0.5.
    • * *
    • tween the currentTime, totalTime, currentProgress, or totalProgress * property to fastforward/rewind the timeline. You could * even attach a slider to one of these properties to give the user the ability to drag * forwards/backwards through the whole timeline.
    • * *
    • add onStart, onUpdate, onComplete, onReverseComplete, and/or onRepeat callbacks using the * constructor's vars object.
    • * *
    • speed up or slow down the entire timeline with its timeScale property. You can even tween * this property to gradually speed up or slow down the timeline.
    • * *
    • use the insertMultiple(), appendMultiple(), or prependMultiple() methods to create * complex sequences including various alignment modes and staggering capabilities. * Works great in conjunction with TweenMax.allTo() too.
    • * *
    • base the timing on frames instead of seconds if you prefer. Please note, however, that * the timeline's timing mode dictates its childrens' timing mode as well.
    • * *
    • kill the tweens of a particular object inside the timeline with killTweensOf() or get the tweens of an object * with getTweensOf() or get all the tweens/timelines in the timeline with getChildren()
    • * *
    • set the timeline to repeat any number of times or indefinitely. You can even set a delay * between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse * every other cycle.
    • * *
    • listen for START, UPDATE, REPEAT, REVERSE_COMPLETE, and COMPLETE events.
    • * *
    • get the active tweens in the timeline with getActive().
    • * *
    • add callbacks (function calls) anywhere in the timeline that call a function of your choosing when * the ""virtual playhead"" passes a particular spot.
    • * *
    • Get the currentLabel or find labels at various positions in the timeline * using getLabelAfter() and getLabelBefore()
    • *
    * * EXAMPLE:

    * * import com.greensock.~~;

    * * //create the timeline and add an onComplete call to myFunction when the timeline completes
    * var myTimeline:TimelineMax = new TimelineMax({onComplete:myFunction});

    * * //add a tween
    * myTimeline.append(new TweenLite(mc, 1, {x:200, y:100}));

    * * //add another tween at the end of the timeline (makes sequencing easy)
    * myTimeline.append(new TweenLite(mc, 0.5, {alpha:0}));

    * * //repeat the entire timeline twice
    * myTimeline.repeat = 2;

    * * //delay the repeat by 0.5 seconds each time.
    * myTimeline.repeatDelay = 0.5;

    * * //pause the timeline (stop() works too)
    * myTimeline.pause();

    * * //reverse it anytime...
    * myTimeline.reverse();

    * * //Add a ""spin"" label 3-seconds into the timeline.
    * myTimeline.addLabel(""spin"", 3);

    * * //insert a rotation tween at the ""spin"" label (you could also define the insert point as the time instead of a label)
    * myTimeline.insert(new TweenLite(mc, 2, {rotation:""360""}), ""spin"");

    * * //go to the ""spin"" label and play the timeline from there...
    * myTimeline.gotoAndPlay(""spin"");

    * * //call myCallbackwhen the ""virtual playhead"" travels past the 1.5-second point. * myTimeline.addCallback(myCallback, 1.5); * * //add a tween to the beginning of the timeline, pushing all the other existing tweens back in time
    * myTimeline.prepend(new TweenMax(mc, 1, {tint:0xFF0000}));

    * * //nest another TimelineMax inside your timeline...
    * var nestedTimeline:TimelineMax = new TimelineMax();
    * nestedTimeline.append(new TweenLite(mc2, 1, {x:200}));
    * myTimeline.append(nestedTimeline);

    * * * insertMultiple() and appendMultiple() provide some very powerful sequencing tools as well, * allowing you to add an Array of tweens/timelines and optionally align them with SEQUENCE or START * modes, and even stagger them if you want. For example, to insert 3 tweens into the timeline, aligning their start times but * staggering them by 0.2 seconds,

    * * myTimeline.insertMultiple([new TweenLite(mc, 1, {y:""100""}), * new TweenLite(mc2, 1, {x:120}), * new TweenLite(mc3, 1, {alpha:0.5})], * 0, * TweenAlign.START, * 0.2);

    * * You can use the constructor's vars object to do all the setup too, like:

    * * var myTimeline:TimelineMax = new TimelineMax({tweens:[new TweenLite(mc1, 1, {y:""100""}), TweenMax.to(mc2, 1, {tint:0xFF0000})], align:TweenAlign.SEQUENCE, onComplete:myFunction, repeat:2, repeatDelay:1});

    * * If that confuses you, don't worry. Just use the append(), insert(), and prepend() methods to build your * sequence. But power users will likely appreciate the quick, compact way they can set up sequences now.

    * * * NOTES: *
      *
    • TimelineMax automatically inits the OverwriteManager class to prevent unexpected overwriting behavior in sequences. * The default mode is AUTO, but you can set it to whatever you want with OverwriteManager.init() * (see http://www.greensock.com/overwritemanager/)
    • *
    • TimelineMax adds about 4.9k to your SWF (not including OverwriteManager).
    • *
    * * Copyright 2012, GreenSock. All rights reserved. This work is subject to the terms in http://www.greensock.com/terms_of_use.html or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership. * * @author Jack Doyle, jack@greensock.com **/ public class TimelineMax extends TimelineLite implements IEventDispatcher { /** @private **/ public static const version:Number = 1.698; /** @private **/ protected var _repeat:int; /** @private **/ protected var _repeatDelay:Number; /** @private **/ protected var _cyclesComplete:int; /** @private **/ protected var _dispatcher:EventDispatcher; /** @private **/ protected var _hasUpdateListener:Boolean; /** * Works in conjunction with the repeat property, determining the behavior of each cycle; when yoyo is true, * the timeline will go back and forth, appearing to reverse every other cycle (this has no affect on the reversed property though). * So if repeat is 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. * But if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. **/ public var yoyo:Boolean; /** * Constructor.

    * * SPECIAL PROPERTIES
    * The following special properties may be passed in via the constructor's vars parameter, like * new TimelineMax({paused:true, onComplete:myFunction, repeat:2, yoyo:true}) * *
      *
    • delay : Number Amount of delay in seconds (or frames for frames-based timelines) before the timeline should begin.
    • * *
    • useFrames : Boolean If useFrames is set to true, the timeline's timing mode will be based on frames. * Otherwise, it will be based on seconds/time. NOTE: a TimelineLite's timing mode is * always determined by its parent timeline.
    • * *
    • paused : Boolean Sets the initial paused state of the timeline (by default, timelines automatically begin playing immediately)
    • * *
    • reversed : Boolean If true, the timeline will be reversed initially. This does NOT force it to the very end and start * playing backwards. It simply affects the orientation of the timeline, so if reversed is set to * true initially, it will appear not to play because it is already at the beginning. To cause it to * play backwards from the end, set reversed to true and then set the currentProgress property to 1 immediately * after creating the timeline.
    • * *
    • tweens : Array To immediately insert several tweens into the timeline, use the tweens special property * to pass in an Array of TweenLite/TweenMax/TimelineLite/TimelineMax instances. You can use this in conjunction * with the align and stagger special properties to set up complex sequences with minimal code. * These values simply get passed to the insertMultiple() method.
    • * *
    • align : String Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately through the constructor. The value simply gets passed to the * insertMultiple() method. The default is TweenAlign.NORMAL. Options are: *
        *
      • TweenAlign.SEQUENCE: aligns the tweens one-after-the-other in a sequence
      • *
      • TweenAlign.START: aligns the start times of all of the tweens (ignores delays)
      • *
      • TweenAlign.NORMAL: aligns the start times of all the tweens (honors delays)
      • *
      The align special property does not force all child tweens/timelines to maintain * relative positioning, so for example, if you use TweenAlign.SEQUENCE and then later change the duration * of one of the nested tweens, it does not force all subsequent timelines to change their position * on the timeline. The align special property only affects the alignment of the tweens that are * initially placed into the timeline through the tweens special property of the vars object.
    • * *
    • stagger : Number Only used in conjunction with the tweens special property when multiple tweens are * to be inserted immediately. It staggers the tweens by a set amount of time (in seconds) (or * in frames if useFrames is true). For example, if the stagger value is 0.5 and the align * property is set to TweenAlign.START, the second tween will start 0.5 seconds after the first one * starts, then 0.5 seconds later the third one will start, etc. If the align property is * TweenAlign.SEQUENCE, there would be 0.5 seconds added between each tween. This value simply gets * passed to the insertMultiple() method. Default is 0.
    • * *
    • onStart : Function A function that should be called when the timeline begins (the currentProgress won't necessarily * be zero when onStart is called. For example, if the timeline is created and then its currentProgress * property is immediately set to 0.5 or if its currentTime property is set to something other than zero, * onStart will still get fired because it is the first time the timeline is getting rendered.)
    • * *
    • onStartParams : Array An Array of parameters to pass the onStart function.
    • * *
    • onUpdate : Function A function that should be called every time the timeline's time/position is updated * (on every frame while the timeline is active)
    • * *
    • onUpdateParams : Array An Array of parameters to pass the onUpdate function
    • * *
    • onComplete : Function A function that should be called when the timeline has finished
    • * *
    • onCompleteParams : Array An Array of parameters to pass the onComplete function
    • * *
    • onReverseComplete : Function A function that should be called when the timeline has reached its starting point again after having been reversed
    • * *
    • onReverseCompleteParams : Array An Array of parameters to pass the onReverseComplete functions
    • * *
    • onRepeat : Function A function that should be called every time the timeline repeats
    • * *
    • onRepeatParams : Array An Array of parameters to pass the onRepeat function
    • * *
    • autoRemoveChildren : Boolean If autoRemoveChildren is set to true, as soon as child tweens/timelines complete, * they will automatically get killed/removed. This is normally undesireable because * it prevents going backwards in time (like if you want to reverse() or set the * currentProgress value to a lower value, etc.). It can, however, improve speed and memory * management. TweenLite's root timelines use autoRemoveChildren:true.
    • * *
    • repeat : int Number of times that the timeline should repeat. To repeat indefinitely, use -1.
    • * *
    • repeatDelay : Number Amount of time in seconds (or frames for frames-based timelines) between repeats.
    • * *
    • yoyo : Boolean Works in conjunction with the repeat property, determining the behavior of each * cycle. When yoyo is true, the timeline will go back and forth, appearing to reverse * every other cycle (this has no affect on the reversed property though). So if repeat is * 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But * if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
    • * *
    • onStartListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it begins. * This is the same as doing myTimeline.addEventListener(TweenEvent.START, myFunction);
    • * *
    • onUpdateListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent every time it * updates values. This is the same as doing myTimeline.addEventListener(TweenEvent.UPDATE, myFunction);
    • * *
    • onCompleteListener : Function A function to which the TimelineMax instance should dispatch a TweenEvent when it completes. * This is the same as doing myTimeline.addEventListener(TweenEvent.COMPLETE, myFunction);
    • *
    * * @param vars optionally pass in special properties like useFrames, onComplete, onCompleteParams, onUpdate, onUpdateParams, onStart, onStartParams, tweens, align, stagger, delay, autoRemoveChildren, onCompleteListener, onStartListener, onUpdateListener, repeat, repeatDelay, and/or yoyo. */ public function TimelineMax(vars:Object=null) { super(vars); _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; _cyclesComplete = 0; this.yoyo = Boolean(this.vars.yoyo == true); this.cacheIsDirty = true; if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } } /** * If you want a function to be called at a particular time or label, use addCallback. When you add * a callback, it is technically considered a zero-duration tween, so if you getChildren() there will be * a tween returned for each callback. You can discern a callback from other tweens by the fact that * their target is a function and the duration is zero. * * @param function the function to be called * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label at which the callback should be inserted. For example, myTimeline.addCallback(myFunction, 3) would call myFunction() 3-seconds into the timeline, and myTimeline.addCallback(myFunction, ""myLabel"") would call it at the ""myLabel"" label. * @param params an Array of parameters to pass the callback * @return TweenLite instance */ public function addCallback(callback:Function, timeOrLabel:*, params:Array=null):TweenLite { var cb:TweenLite = new TweenLite(callback, 0, {onComplete:callback, onCompleteParams:params, overwrite:0, immediateRender:false}); insert(cb, timeOrLabel); return cb; } /** * Removes a callback from a particular time or label. If timeOrLabel is null, all callbacks of that * particular function are removed from the timeline. * * @param function callback function to be removed * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label from which the callback should be removed. For example, myTimeline.removeCallback(myFunction, 3) would remove the callback from 3-seconds into the timeline, and myTimeline.removeCallback(myFunction, ""myLabel"") would remove it from the ""myLabel"" label, and myTimeline.removeCallback(myFunction, null) would remove ALL callbacks of that function regardless of where they are on the timeline. * @return true if any callbacks were successfully found and removed. false otherwise. */ public function removeCallback(callback:Function, timeOrLabel:*=null):Boolean { if (timeOrLabel == null) { return killTweensOf(callback, false); } else { if (typeof(timeOrLabel) == ""string"") { if (!(timeOrLabel in _labels)) { return false; } timeOrLabel = _labels[timeOrLabel]; } var a:Array = getTweensOf(callback, false), success:Boolean; var i:int = a.length; while (--i > -1) { if (a[i].cachedStartTime == timeOrLabel) { remove(a[i] as TweenCore); success = true; } } return success; } } /** * Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops. For * example, to make the TimelineMax play to the ""myLabel2"" label, simply do:

    * * myTimeline.tweenTo(""myLabel2"");

    * * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween to the 5-second point on the * timeline and then call a function named myFunction and pass in a parameter that's references this * TimelineMax and use a Strong.easeOut ease, you'd do:

    * * myTimeline.tweenTo(5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

    * * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method.

    * * If you plan to sequence multiple playhead tweens one-after-the-other, it is typically better to use * tweenFromTo() so that you can define the starting point and ending point, allowing the * duration to be accurately determined immediately. * * @see #tweenFromTo() * @param timeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(5) would play from wherever the timeline is currently to the 5-second point whereas myTimeline.tweenTo(""myLabel"") would play to wherever ""myLabel"" is on the timeline. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenTo() sets it internally) * @return TweenLite instance that handles tweening the timeline to the desired time/label. */ public function tweenTo(timeOrLabel:*, vars:Object=null):TweenLite { var varsCopy:Object = {ease:easeNone, overwrite:2, useFrames:this.useFrames, immediateRender:false}; for (var p:String in vars) { varsCopy[p] = vars[p]; } varsCopy.onInit = onInitTweenTo; varsCopy.onInitParams = [null, this, NaN]; varsCopy.currentTime = parseTimeOrLabel(timeOrLabel); var tl:TweenLite = new TweenLite(this, (Math.abs(Number(varsCopy.currentTime) - this.cachedTime) / this.cachedTimeScale) || 0.001, varsCopy); tl.vars.onInitParams[0] = tl; return tl; } /** * Creates a linear tween that essentially scrubs the playhead from a particular time or label to another * time or label and then stops. If you plan to sequence multiple playhead tweens one-after-the-other, * tweenFromTo() is better to use than tweenTo() because it allows the duration * to be determined immediately, ensuring that subsequent tweens that are appended to a sequence are * positioned appropriately. For example, to make the TimelineMax play from the label ""myLabel1"" to the ""myLabel2"" * label, and then from ""myLabel2"" back to the beginning (a time of 0), simply do:

    * * var playheadTweens:TimelineMax = new TimelineMax();
    * playheadTweens.append( myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") );
    * playheadTweens.append( myTimeline.tweenFromTo(""myLabel2"", 0);

    * * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay, * just pass in a vars object with the appropriate properties. For example, to tween from the start (0) to the * 5-second point on the timeline and then call a function named myFunction and pass in a parameter * that's references this TimelineMax and use a Strong.easeOut ease, you'd do:

    * * myTimeline.tweenFromTo(0, 5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});

    * * Remember, this method simply creates a TweenLite instance that tweens the currentTime property of your timeline. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that tweenFromTo() * does NOT affect the timeline's reversed property. So if your timeline is oriented normally * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards * but the reversed property will not change to true. Also note that tweenFromTo() * pauses the timeline immediately before tweening its currentTime property, and it stays paused after the tween completes. * If you need to resume playback, you could always use an onComplete to call the resume() method. * * @see #tweenTo() * @param fromTimeOrLabel The beginning time in seconds (or frame if the timeline is frames-based) or label from which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param toTimeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(0, 5) would play from 0 (the beginning) to the 5-second point whereas myTimeline.tweenFromTo(""myLabel1"", ""myLabel2"") would play from ""myLabel1"" to ""myLabel2"". * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenFromTo() sets it internally) * @return TweenLite instance that handles tweening the timeline between the desired times/labels. */ public function tweenFromTo(fromTimeOrLabel:*, toTimeOrLabel:*, vars:Object=null):TweenLite { var tl:TweenLite = tweenTo(toTimeOrLabel, vars); tl.vars.onInitParams[2] = parseTimeOrLabel(fromTimeOrLabel); tl.duration = Math.abs(Number(tl.vars.currentTime) - tl.vars.onInitParams[2]) / this.cachedTimeScale; return tl; } /** @private **/ private static function onInitTweenTo(tween:TweenLite, timeline:TimelineMax, fromTime:Number):void { timeline.paused = true; if (!isNaN(fromTime)) { timeline.currentTime = fromTime; } if (tween.vars.currentTime != timeline.currentTime) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all. tween.duration = Math.abs(Number(tween.vars.currentTime) - timeline.currentTime) / timeline.cachedTimeScale; } } /** @private **/ private static function easeNone(t:Number, b:Number, c:Number, d:Number):Number { return t / d; } /** @private **/ override public function renderTime(time:Number, suppressEvents:Boolean=false, force:Boolean=false):void { if (this.gc) { this.setEnabled(true, false); } else if (!this.active && !this.cachedPaused) { this.active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done. } var totalDur:Number = (this.cacheIsDirty) ? this.totalDuration : this.cachedTotalDuration, prevTime:Number = this.cachedTime, prevTotalTime:Number = this.cachedTotalTime, prevStart:Number = this.cachedStartTime, prevTimeScale:Number = this.cachedTimeScale, tween:TweenCore, isComplete:Boolean, rendered:Boolean, repeated:Boolean, next:TweenCore, dur:Number, prevPaused:Boolean = this.cachedPaused; if (time >= totalDur) { if ((prevTotalTime != totalDur || this.cachedDuration == 0) && _rawPrevTime != time) { this.cachedTotalTime = totalDur; if (!this.cachedReversed && this.yoyo && _repeat % 2 != 0) { this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); } else { this.cachedTime = this.cachedDuration; forceChildrenToEnd(this.cachedDuration, suppressEvents); } isComplete = !this.hasPausedChild() && !this.cachedReversed; rendered = true; if (this.cachedDuration == 0 && isComplete && (time == 0 || _rawPrevTime < 0)) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; } } } else if (time <= 0) { if (time < 0) { this.active = false; if (this.cachedDuration == 0 && _rawPrevTime > 0) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the ""playhead"" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time). force = true; isComplete = true; } } else if (time == 0 && !this.initted) { force = true; } if (prevTotalTime != 0 && _rawPrevTime != time) { this.cachedTotalTime = 0; this.cachedTime = 0; forceChildrenToBeginning(0, suppressEvents); rendered = true; if (this.cachedReversed) { isComplete = true; } } } else { this.cachedTotalTime = this.cachedTime = time; } _rawPrevTime = time; if (_repeat != 0) { var cycleDuration:Number = this.cachedDuration + _repeatDelay; var prevCycles:int = _cyclesComplete; if ((_cyclesComplete = (this.cachedTotalTime / cycleDuration) >> 0) == (this.cachedTotalTime / cycleDuration) && _cyclesComplete != 0) { _cyclesComplete--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning) } repeated = Boolean(prevCycles != _cyclesComplete); if (isComplete) { if (this.yoyo && _repeat % 2) { this.cachedTime = 0; } } else if (time > 0) { this.cachedTime = this.cachedTotalTime - (_cyclesComplete * cycleDuration); //originally this.cachedTotalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!) if (this.yoyo && _cyclesComplete % 2) { this.cachedTime = this.cachedDuration - this.cachedTime; } else if (this.cachedTime >= this.cachedDuration) { this.cachedTime = this.cachedDuration; } if (this.cachedTime < 0) { this.cachedTime = 0; } } else { _cyclesComplete = 0; } if (repeated && !isComplete && (this.cachedTotalTime != prevTotalTime || force)) { /* make sure children at the end/beginning of the timeline are rendered properly. If, for example, a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So we need to push the timeline to the end (and/or beginning depending on its yoyo value). */ var forward:Boolean = Boolean(!this.yoyo || (_cyclesComplete % 2 == 0)); var prevForward:Boolean = Boolean(!this.yoyo || (prevCycles % 2 == 0)); var wrap:Boolean = Boolean(forward == prevForward); if (prevCycles > _cyclesComplete) { prevForward = !prevForward; } if (prevForward) { prevTime = forceChildrenToEnd(this.cachedDuration, suppressEvents); if (wrap) { prevTime = forceChildrenToBeginning(0, true); } } else { prevTime = forceChildrenToBeginning(0, suppressEvents); if (wrap) { prevTime = forceChildrenToEnd(this.cachedDuration, true); } } rendered = false; } } if (this.cachedTime == prevTime && !force) { return; } else if (!this.initted) { this.initted = true; } if (prevTotalTime == 0 && this.cachedTotalTime != 0 && !suppressEvents) { if (this.vars.onStart) { this.vars.onStart.apply(null, this.vars.onStartParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START)); } } if (rendered) { //already rendered, so ignore } else if (this.cachedTime > prevTime) { tween = _firstChild; while (tween) { next = tween.nextNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= this.cachedTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } else { tween = _lastChild; while (tween) { next = tween.prevNode; //record it here because the value could change after rendering... if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering break; } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= prevTime && !tween.gc)) { if (!tween.cachedReversed) { tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false); } else { dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration; tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false); } } tween = next; } } if (_hasUpdate && !suppressEvents) { this.vars.onUpdate.apply(null, this.vars.onUpdateParams); } if (_hasUpdateListener && !suppressEvents) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE)); } if (repeated && !suppressEvents) { if (this.vars.onRepeat) { this.vars.onRepeat.apply(null, this.vars.onRepeatParams); } if (_dispatcher) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REPEAT)); } } if (isComplete && (prevStart == this.cachedStartTime || prevTimeScale != this.cachedTimeScale) && (totalDur >= this.totalDuration || this.cachedTime == 0)) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline) or if it added more tweens to the timeline, we shouldn't run complete() because it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would have called complete() if it was necessary at the new time. The only exception is the timeScale property. complete(true, suppressEvents); } } /** * Forces the timeline to completion. * * @param skipRender to skip rendering the final state of the timeline, set skipRender to true. * @param suppressEvents If true, no events or callbacks will be triggered for this render (like onComplete, onUpdate, onReverseComplete, etc.) */ override public function complete(skipRender:Boolean=false, suppressEvents:Boolean=false):void { super.complete(skipRender, suppressEvents); if (_dispatcher && !suppressEvents) { if (this.cachedReversed && this.cachedTotalTime == 0 && this.cachedDuration != 0) { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REVERSE_COMPLETE)); } else { _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE)); } } } /** * Returns the tweens/timelines that are currently active in the timeline. * * @param nested determines whether or not tweens and/or timelines that are inside nested timelines should be returned. If you only want the ""top level"" tweens/timelines, set this to false. * @param tweens determines whether or not tweens (TweenLite and TweenMax instances) should be included in the results * @param timelines determines whether or not timelines (TimelineLite and TimelineMax instances) should be included in the results * @return an Array of active tweens/timelines */ public function getActive(nested:Boolean=true, tweens:Boolean=true, timelines:Boolean=false):Array { var a:Array = [], all:Array = getChildren(nested, tweens, timelines), i:int, tween:TweenCore; var l:int = all.length; var cnt:int = 0; for (i = 0; i < l; i += 1) { tween = all[i]; //note: we cannot just check tween.active because timelines that contain paused children will continue to have ""active"" set to true even after the playhead passes their end point (technically a timeline can only be considered complete after all of its children have completed too, but paused tweens are...well...just waiting and until they're unpaused we don't know where their end point will be). if (!tween.cachedPaused && tween.timeline.cachedTotalTime >= tween.cachedStartTime && tween.timeline.cachedTotalTime < tween.cachedStartTime + tween.cachedTotalDuration / tween.cachedTimeScale && !OverwriteManager.getGlobalPaused(tween.timeline)) { a[cnt++] = all[i]; } } return a; } /** @inheritDoc **/ override public function invalidate():void { _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0; _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0; this.yoyo = Boolean(this.vars.yoyo == true); if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) { initDispatcher(); } setDirtyCache(true); super.invalidate(); } /** * Returns the next label (if any) that occurs AFTER the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time after which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is after the time passed to getLabelAfter() */ public function getLabelAfter(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var l:int = labels.length; for (var i:int = 0; i < l; i += 1) { if (labels[i].time > time) { return labels[i].name; } } return null; } /** * Returns the previous label (if any) that occurs BEFORE the time parameter. It makes no difference * if the timeline is reversed. A label that is positioned exactly at the same time as the time * parameter will be ignored. * * @param time Time before which the label is searched for. If you do not pass a time in, the currentTime will be used. * @return Name of the label that is before the time passed to getLabelBefore() */ public function getLabelBefore(time:Number=NaN):String { if (!time && time != 0) { //faster than isNan() time = this.cachedTime; } var labels:Array = getLabelsArray(); var i:int = labels.length; while (--i > -1) { if (labels[i].time < time) { return labels[i].name; } } return null; } /** @private Returns an Array of label objects, each with a ""time"" and ""name"" property, in the order that they occur in the timeline. **/ protected function getLabelsArray():Array { var a:Array = []; for (var p:String in _labels) { a[a.length] = {time:_labels[p], name:p}; } a.sortOn(""time"", Array.NUMERIC); return a; } //---- EVENT DISPATCHING ---------------------------------------------------------------------------------------------------------- /** @private **/ protected function initDispatcher():void { if (_dispatcher == null) { _dispatcher = new EventDispatcher(this); } if (this.vars.onStartListener is Function) { _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true); } if (this.vars.onUpdateListener is Function) { _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true); _hasUpdateListener = true; } if (this.vars.onCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true); } if (this.vars.onRepeatListener is Function) { _dispatcher.addEventListener(TweenEvent.REPEAT, this.vars.onRepeatListener, false, 0, true); } if (this.vars.onReverseCompleteListener is Function) { _dispatcher.addEventListener(TweenEvent.REVERSE_COMPLETE, this.vars.onReverseCompleteListener, false, 0, true); } } /** @private **/ public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void { if (_dispatcher == null) { initDispatcher(); } if (type == TweenEvent.UPDATE) { _hasUpdateListener = true; } _dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); } /** @private **/ public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { if (_dispatcher != null) { _dispatcher.removeEventListener(type, listener, useCapture); } } /** @private **/ public function hasEventListener(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.hasEventListener(type); } /** @private **/ public function willTrigger(type:String):Boolean { return (_dispatcher == null) ? false : _dispatcher.willTrigger(type); } /** @private **/ public function dispatchEvent(e:Event):Boolean { return (_dispatcher == null) ? false : _dispatcher.dispatchEvent(e); } //---- GETTERS / SETTERS ------------------------------------------------------------------------------------------------------- /** @inheritDoc **/ override public function set currentProgress(n:Number):void { this.currentTime = this.duration * n; } /** * Value between 0 and 1 indicating the overall progress of the timeline according to its totalDuration * where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished. currentProgress, * by contrast, describes the progress according to the timeline's duration which does not * include repeats and repeatDelays. For example, if a TimelineMax instance is set * to repeat once, at the end of the first cycle totalProgress would only be 0.5 * whereas currentProgress would be 1. If you tracked both properties over the course of the * tween, you'd see currentProgress go from 0 to 1 twice (once for each cycle) in the same * time it takes the totalProgress property to go from 0 to 1 once. **/ public function get totalProgress():Number { return this.cachedTotalTime / this.totalDuration; } public function set totalProgress(n:Number):void { setTotalTime(this.totalDuration * n, false); } /** * Duration of the timeline in seconds (or frames for frames-based timelines) including any repeats * or repeatDelays. ""duration"", by contrast, does NOT include repeats and repeatDelays. **/ override public function get totalDuration():Number { if (this.cacheIsDirty) { var temp:Number = super.totalDuration; //just forces refresh //Instead of Infinity, we use 999999999999 so that we can accommodate reverses. this.cachedTotalDuration = (_repeat == -1) ? 999999999999 : this.cachedDuration * (_repeat + 1) + (_repeatDelay * _repeat); } return this.cachedTotalDuration; } /** @private **/ override public function set currentTime(n:Number):void { if (_cyclesComplete == 0) { setTotalTime(n, false); } else if (this.yoyo && (_cyclesComplete % 2 == 1)) { setTotalTime((this.duration - n) + (_cyclesComplete * (this.cachedDuration + _repeatDelay)), false); } else { setTotalTime(n + (_cyclesComplete * (this.duration + _repeatDelay)), false); } } /** Number of times that the timeline should repeat; -1 repeats indefinitely. **/ public function get repeat():int { return _repeat; } public function set repeat(n:int):void { _repeat = n; setDirtyCache(true); } /** Amount of time in seconds (or frames for frames-based timelines) between repeats **/ public function get repeatDelay():Number { return _repeatDelay; } public function set repeatDelay(n:Number):void { _repeatDelay = n; setDirtyCache(true); } /** The closest label that is at or before the current time. **/ public function get currentLabel():String { return getLabelBefore(this.cachedTime + 0.00000001); } } }",12300,False,2080.360318351287,median "// Copyright (c) 2013 Adobe Systems Inc // 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. package com.adobe.flascc { import flash.profiler.Telemetry; import flash.utils.*; import com.adobe.flascc.kernel.*; import com.adobe.flascc.vfs.*; import C_Run.*; class ThunkMaker { private var modPkgName:String; private var thunkSet:Dictionary; private var start:int; private var end:int; private var index:int; public function ThunkMaker(modPkgName:String, thunkSet:Dictionary, start:int, end:int, index:int):void { this.modPkgName = modPkgName; this.thunkSet = thunkSet; this.start = start; this.end = end; this.index = index; } public function thunk():void { delete CModule.modThunks[modPkgName]; //trace(""thunking for "" + modPkgName + "" ("" + index + "")""); var m:CModule = CModule.getModuleByPackage(modPkgName); // var removed:int = 0; m.getScript(); // init! // remove all remaining thunks for this range for(var j:int = start; j < end; j++) if(thunkSet[ptr2fun[j]]) { delete thunkSet[ptr2fun[j]]; ptr2fun[j] = null; // removed++; } //trace(""removed "" + removed + "" thunks""); if(index >= 0) ptr2fun[index](); }; } /** * Contains convenience functions for reading and writting to domainMemory; also manages any flascc-specific global state (for example, the VFS and Posix interface implementations.) */ public class CModule { /** * Returns the ByteArray object using as RAM */ public static function get ram():ByteArray { return C_Run.ram; } /** * Returns a boolean indicating whether Flash out of memory conditions when growing the domainMemory ByteArray will throw an ActionScript exception. The default is false, malloc will return an appropriate failure and new/new[] will throw a std::badalloc C++ exception. */ public static function get throwWhenOutOfMemory():Boolean { return C_Run.throwWhenOutOfMemory } /** * Sets a boolean indicating whether Flash out of memory conditions when growing the domainMemory ByteArray will throw an ActionScript exception or cause malloc to fail. The default is false, malloc will return an appropriate failure and new/new[] will throw a std::badalloc C++ exception. */ public static function set throwWhenOutOfMemory(x:Boolean):void { C_Run.throwWhenOutOfMemory = x } /** * Returns true if the current environment supports * use of ActionScript Workers with flascc content */ public static function get canUseWorkers():Boolean { return C_Run.workerClass; } /** * @private */ static protected var weakResolvers:Vector. = new Vector.; /** * @private */ public static function resolveWeaks(f:Function):void { weakResolvers.unshift(f); while(weakResolvers.length) { var resolver:Function = weakResolvers.pop(); if(!resolver()) weakResolvers.unshift(f); } } private static var workerSprite:* = null /** * Console should use this function to check if the SWF * has been launched as an isolate so it can act appropriately */ public static function runningAsWorker():Boolean { var inWorker:Boolean = false if(!CModule.rootSprite) throw new Error(""specify a rootSprite using \\""CModule.rootSprite = ...\\""""); try { C_Run.workerSWFBytes = CModule.rootSprite.loaderInfo.bytes if(C_Run.workerClass[""current""].getSharedProperty(""flascc.ram"")) inWorker = true; } catch(e:*) { inWorker = false; } if(inWorker) { workerSprite = new C_Run.AlcWorkerSprite(); } return inWorker } /** * @private */ public static var recordFixups:Boolean = false; /** * @private */ public static var regsInitted:Boolean = false; /** * Lookup the specified publicly defined C/C++ symbol * * @param s The name of the symbol to lookup, for example, ""malloc"" * * @return The address of the symbol. If the symbol was a POD type you can read it's * value using one of the read functions. If the symbol was a function then you can call it using callI. */ public static function getPublicSymbol(name:String):int { namespace ns = ""C_Run""; return ns::[""_""+name]; } /** * relies on metadata -- won't return info in stripped builds * returns an Array of sym descriptors * sym descriptor is an Array of form: * [nmStyleType, symName(, sectName, value)] * @private */ public static function getSymsUsingMD():Array { var esyms:Dictionary = mapCsymsWithExplicitValues(); var result:Array = []; for each(var module:CModule in modules) result = result.concat(module.getSymsUsingMDWithExplicitSyms(esyms)); return result; } /*** * @private */ static var preppedForThreadedExec:Boolean = false; /*** * @private */ public static function prepForThreadedExec():void { if(preppedForThreadedExec) return; //trace('ptr2fun: ' + ptr2fun.constructor); if(typeof(ptr2fun) == ""undefined"" || ptr2fun is Array) // sparse function mapping? explicitly init every module... { //trace(""faulting in all modules: "" + (ptr2fun_init.constructor) + ' (' + threadId + ')'); explicitlyInitAllModules(); } preppedForThreadedExec = true; } /*** * @private */ static var explicitlyInittedAllModules:Boolean = false; /*** * @private */ public static function explicitlyInitAllModules():void { if (explicitlyInittedAllModules) return; var resumeLibs:Boolean = false; try { AlcDbgHelper.pauseLibraryNotifications(); resumeLibs = true; } catch (e:*) {} try { for each(var m:* in getModuleVector()) //type is * to avoid cyclic depend on CModule script.. m.getScript(); } finally { try { if (resumeLibs) AlcDbgHelper.resumeLibraryNotifications(); } catch (e:*) {} } explicitlyInittedAllModules = true; } // package name => base thunk /*** * @private */ static const modThunks:Dictionary = new Dictionary; /*** * @private */ static function makeThunk(modPkgName:String, thunkSet:Dictionary, start:int, end:int, index:int):Function { return new ThunkMaker(modPkgName, thunkSet, start, end, index).thunk; } /** * note that this coexists peacefully w/ allocText-based function ptrs * because allocText always returns a negative number and setting * ptr2fun_init[someNegNumber] doesn't affect ptr2fun_init.length * @private */ public static function allocFunPtrs(modPkgName:String, n:int, align:int):int { // TODO -- anything to do for threads here? should be totally deterministic, I guess! if(align < 1) align = 1; ptr2fun_init.length = int((ptr2fun_init.length + align - 1) / align) * align; var result:int = ptr2fun_init.length; ptr2fun_init.length += n; // real package (i.e., not SWIG allocing some temp stuff) + worker support? put a bunch of thunks in to fault in modules if(modPkgName != null && workerClass) { // set of all thunks var thunkSet:Dictionary = new Dictionary; for(var i:int = result; i < result + n; i++) { // thunk function that will forcibly init the script // and then call the right function var thunk:Function = makeThunk(modPkgName, thunkSet, result, result + n, i); thunkSet[thunk] = true; ptr2fun_init[i] = thunk; } var modThunk:Function = makeThunk(modPkgName, thunkSet, result, result + n, -1); modThunks[modPkgName] = modThunk; thunkSet[modThunk] = true; } return result; } /** * @private */ static protected var text:int = int(0xf0000000); // 3.75G (don't clash w/ real data) /** * allocate a region in ""text"" space (i.e., code space) * @private */ public static function allocTextSect(modPkgName:String, sectName:String, size:int):int { // TODO -- anything to do for threads here? should be totally deterministic, I guess! var result:int = (text + 15) & ~15; // align per module text = result + size; return result; } /** * allocate space in domainMemory for data * @private */ public static function allocDataSect(modPkgName:String, sectName:String, size:int, align:int):int { var result:int; if(workerClass) { var propName:String = ""flascc.sect."" + modPkgName + ""."" + sectName; result = workerClass.current.getSharedProperty(propName); //trace(""allocDataSect tid: "" + threadId + "" / "" + modPkgName + ""."" + sectName + "" = "" + result); } if(!result) { if(align < 1) align = 1; result = sbrk(size, align); } return result; } /** * @private */ public static function describeType(value:*):XML { try { var flashutilsNS:Namespace = new Namespace(""flash.utils""); return (flashutilsNS::[""describeType""])(value); } catch(e:*) {} var avmplusNS:Namespace = new Namespace(""avmplus""); return (avmplusNS::[""describeType""])(value, avmplusNS::[""FLASH10_FLAGS""]); } /** * Write the low 8 bits of value into domainMemory. * @param ptr The address of the location in domainMemory to write to * @param value The value to write (only the low 8 bits are written) */ public static function write8(ptr:int, value:int):void { ram_init.position = ptr; ram_init.writeByte(value); } /** * Write the low 16 bits of value into domainMemory. * @param ptr The address of the location in domainMemory to write to * @param value The value to write (only the low 16 bits are written) */ public static function write16(ptr:int, value:int):void { ram_init.position = ptr; ram_init.writeShort(value); } /** * Write a 32 bit value into domainMemory * @param ptr The address of the location in domainMemory to write to * @param value The value to write */ public static function write32(ptr:int, value:int):void { ram_init.position = ptr; ram_init.writeInt(value); } /** * Write a Number as a 32 bit float into domainMemory * @param ptr The address of the location in domainMemory to write to * @param value The value to write at the address (will be rounded to the nearest 32bit floating point value) */ public static function writeFloat(ptr:int, value:Number):void { ram_init.position = ptr; ram_init.writeFloat(value); } /** * Write a Number as a 64 bit float into domainMemory * @param ptr The address of the location in domainMemory to write to * @param value The value to write at the address */ public static function writeDouble(ptr:int, value:Number):void { ram_init.position = ptr; ram_init.writeDouble(value); } /** * Copy the contents of an object that implements the IDataInput interface (ByteArray, FileStream, Socket etc) into domainMemory. * @param ptr The address of the location in domainMemory to start writting to * @param length The number of bytes to copy from the source bytearray (starting from source.position) * @param source The IDataInput to copy data from (the current position in this IDataInput will be used, and will increase by length) */ public static function writeBytes(ptr:int, length:uint, source:IDataInput):void { source.readBytes(ram_init, ptr, length); } /** * Read an 8 bit value from domainMemory with zero padding to extend it to a 32 bit signed integer. This will always result in positive integers. * @param ptr The address of the location in domainMemory to read from * @return An 8 bit integer zero padded to 32 bit. */ public static function read8(ptr:int):int { ram_init.position = ptr; return ram_init.readUnsignedByte(); } /** * Read a 16 bit value from domainMemory with zero padding to extend it to a 32 bit signed integer. This will always result in positive integers. * @param ptr The address of the location in domainMemory to read from * @return A 16 bit integer zero padded to 32 bit. */ public static function read16(ptr:int):int { ram_init.position = ptr; return ram_init.readUnsignedShort(); } /** * Read a 32 bit value from domainMemory. * @param ptr The address of the location in domainMemory to read from * @return A 32 bit integer. */ public static function read32(ptr:int):int { ram_init.position = ptr; return ram_init.readInt(); } /** * Read a 32 bit floating point value from domainMemory * @param ptr The address of the location in domainMemory to read from * @return A signed 32 bit floating point value */ public static function readFloat(ptr:int):Number { ram_init.position = ptr; return ram_init.readFloat(); } /** * Read a 64 bit floating point value from domainMemory * @param ptr The address of the location in domainMemory to read from * @return A signed 64 bit floating point value */ public static function readDouble(ptr:int):Number { ram_init.position = ptr; return ram_init.readDouble(); } /** * Copy data from domainMemory into an object implementing the IDataOutput interface (ByteArray, FileStream, Socket etc) * @param ptr The address of the location in domainMemory to start reading from. * @param length The number of bytes to copy from the domainMemory (starting from ptr) * @param dst The IDataOutput to copy data into (the current position in this IDataOutput will be respected and will increase by length) */ public static function readBytes(ptr:int, length:uint, dst:IDataOutput):void { dst.writeBytes(ram_init, ptr, length); } /** * @private */ public static function push32(value:int):void { ESP -= 4; write32(ESP, value); } /** * @private */ public static function pop32():int { var result:int = read32(ESP); ESP += 4; return result; } /** * Allocate size bytes of data within the domainMemory ByteArray. The memory must be freed using CModule.free(). * @return A pointer to a region of memory within domainMemory size bytes long. * * Internally this calls the libc implementation of malloc() so the returned value should be treated as though it had been allocated in C with malloc(). */ public static function malloc(size:int):int { var args:Vector. = new Vector.; args.push(size); return callI(_malloc, args); } /** * Free a pointer that was previously allocated using CModule.malloc(). * * Internally this calls the libc implementation of free() so it can be used to free pointers allocated in C with malloc(). */ public static function free(ptr:int):void { var args:Vector. = new Vector.; args.push(ptr); callI(_free, args); } /** * should inline asm using me indicate that esp is clobbered? * @private */ public static function alloca(size:int):int { ESP = int((ESP - size) / stackAlign) * stackAlign; return ESP; } /** * Write an actionscript string as UTF8 data into domainMemory * @param ptr The location in domainMemory where the string will be written. You must ensure that this * points to a buffer in the flascc world that has enough space to hold the string * data or this method will overwrite other data within your program. Consider using * mallocString instead as it will allocate the correct amount of space. * @return The number of bytes written */ public static function writeString(ptr:int, s:String):int { ram_init.position = ptr; ram_init.writeUTFBytes(s); return ram_init.position - ptr; } /** * Read UTF8 data from domainMemory and construct an Actionscript String * @param ptr The location in domainMemory to start reading from * @param length The number of bytes to read * @return A String constructed from the UTF8 data found between ptr and ptr+length */ public static function readString(ptr:int, length:int):String { ram_init.position = ptr; var s:String = ram_init.readUTFBytes(length); //trace(s); return s; } /** * @private */ public static function writeLatin1String(ptr:int, s:String):int { ram_init.position = ptr; ram_init.writeUTFBytes(s); //XXX ram_init.writeMultiByte(s, ""iso-8859-1""); return ram_init.position - ptr; } /** * @private */ public static function readLatin1String(ptr:int, length:int):String { ram_init.position = ptr; var s:String = ram_init.readUTFBytes(length);//XXX ram_init.readMultiByte(length, ""iso-8859-1""); //trace(s); return s; } /** * Read count integers from the offset ptr in domainMemory into a Vector of ints. * @param ptr The offset in domainMemory to read from * @param count The number of 32 bit integers to read * @return A Vector of ints read from domainMemory */ public static function readIntVector(ptr:int, count:int):Vector. { var r:Vector. = new Vector.; ram_init.position = ptr; while(count--) r.push(ram_init.readInt()); return r; } /** * Write a Vector of ints into domainMemory starting at offset ptr. * @param ptr The offset in domainMemory to start writing to * @param vec The Vector of ints to write into domainMemory */ public static function writeIntVector(ptr:int, vec:Vector.):void { ram_init.position = ptr; for(var i:int = 0; i < vec.length; i++) ram_init.writeInt(vec[i]); } /** * @private */ static protected const scratchBA:ByteArray = new ByteArray; /** * Allocate a buffer in domainMemory and write an actionscript string as UTF8 data into that buffer. * @param s The string you want to copy into domainMemory * @return The pointer to the buffer in domainMemory that contains the string. This must be manually * freed by passing this pointer to ""free()"" */ public static function mallocString(s:String):int { scratchBA.position = 0; scratchBA.writeUTFBytes(s); scratchBA.writeByte(0); var length:int = scratchBA.position; var ptr:int = malloc(length); ram_init.position = ptr; ram_init.writeBytes(scratchBA, 0, length); if(length > 0x1000) scratchBA.length = 0x1000; return ptr; } /** * @private */ public static function allocaString(s:String):int { scratchBA.position = 0; scratchBA.writeUTFBytes(s); scratchBA.writeByte(0); var length:int = scratchBA.position; var ptr:int = alloca(length); ram_init.position = ptr; ram_init.writeBytes(scratchBA, 0, length); if(length > 0x1000) scratchBA.length = 0x1000; return ptr; } /** * @private */ public static function mallocLatin1String(s:String):int { var length:int = s.length; var ptr:int = malloc(length+1); ram_init.position = ptr; ram_init.writeUTFBytes(s);//XXX ram_init.writeMultiByte(s, ""iso-8859-1""); ram_init[ptr+length] = 0; return ptr; } /** * @private */ public static function allocaLatin1String(s:String):int { var length:int = s.length; var ptr:int = alloca(length+1); ram_init.position = ptr; ram_init.writeUTFBytes(s);//XXX ram_init.writeMultiByte(s, ""iso-8859-1""); ram_init[ptr+length] = 0; return ptr; } /** * @private */ public static function regFun(ptr:int, f:Function):void { if(ptr == 0) throw new Error(""Error: Attempting to register the null function pointer""); // trace(""regFun "" + uint(ptr).toString(16)); ptr2fun_init[ptr] = f; } /** * Low level API for calling a C/C++ function from Actionscript, returning a 32-bit value * @param functionPtr The address of the function. You can find the address of a C/C++ * function by passing the name of the function to getPublicSym. * @param args A Vector containing 32-bit values to pass on the stack to * the function. These could either be primitive integer data, or pointers. * To pass more complex data types (including AS3 types) you should use the * function annotation syntax explained in the interop tutorial to give the * function a mopre natural AS3 function signature. * @param stack An optional pointer to the base of the stack. A value of 0 means use the * current ESP. * @param preserveStack Indicates whether the stack pointer should unwind back to the value it was * before the function was called. * @return The integer return value of the function. As above, to return complex (possibly AS3) * types you should annotate the function as explained in the interop tutorial * to give the function a more natural signature and return type. */ public static function callI(functionPtr:int, args:Vector., stack:int = 0, preserveStack:Boolean = false):int { var esp:int = ESP; try { // optional stack param if(stack) ESP = stack; // align stack ESP = int(ESP / stackAlign) * stackAlign; // align for args var argAlign:int = (stackAlign - ((args.length * 4) % stackAlign)) % stackAlign; ESP -= argAlign; for(var i:int = args.length-1; i >= 0; i--) push32(args[i]); (ptr2fun_init[functionPtr])(); } finally { if(!preserveStack) ESP = esp; } return eax; } /** * Low level API for calling a C/C++ function from Actionscript returning a 64-bit floating point value * @param functionPtr The address of the function. You can find the address of a C/C++ * function by passing the name of the function to getPublicSym. * @param args A Vector containing 32-bit values to pass on the stack to * the function. These could ewither be primitive integer data, or pointers. * To pass more complex data types (including AS3 types) you should use the * function annotation syntax explained in the interop tutorial to give the * function a mopre natural AS3 function signature. * @param stack An optional pointer to the base of the stack. A value of 0 means use the * current ESP. * @param preserveStack Indicates whether the stack pointer should unwind back to the value it was * before the function was called. * @return The 64-bit floating point return value of the function. As above, to return complex (possibly AS3) * types you should annotate the function as explained in the interop tutorial * to give the function a more natural signature and return type. */ public static function callN(functionPtr:int, args:Vector., stack:int = 0, preserveStack:Boolean = false):Number { callI(functionPtr, args, stack); return st0; } /** * @private */ static protected const modules:Vector. = new Vector.; private static var seenModuleInit:Boolean; /** * @private */ public static function regModule(sections:Object, init:Function, modSyms:Array, modPackage:String):CModule { if(seenModuleInit) trace(""WARNING: module registration after module initialization has begun""); // trace(""registered module""); var mod:CModule = new CModule(sections, init, modSyms, modPackage); modules.push(mod); return mod; } /** * @private */ public static function getModuleByPackage(s:String):CModule { for each(var m:CModule in modules) if(m.modPackage == s) return m; return null; } /** * @private */ public static function getModuleVector():Vector. { return modules.concat(); } private var sections:Object; // section map private var init:Function; // initialization function to force the module to init private var script:Object; // global/script object for this module private var modSyms:Array; private var modPackage:String; private var fixups:Vector.; /** * @private */ public const oncep:int; /** * @private */ public function CModule(sections:Object, init:Function, modSyms:Array, modPackage:String) { this.sections = sections; this.init = init; this.modSyms = modSyms; this.modPackage = modPackage; // grab a byte to use as our ""run once"" state this.oncep = (workerClass ? workerClass.current.getSharedProperty(""flascc."" + modPackage + "".oncep"") : 0) || sbrk(1, 1); if(recordFixups) fixups = new Vector.; } /** * @private */ public function once(f:Function, ...args:Array):void { if(workerClass) threadArbMutexLock(); try { if(!read8(oncep)) { write8(oncep, 1); f.apply(undefined, args); } } finally { if(workerClass) threadArbMutexUnlock(); } } private static var telemetrySupported:Boolean; try { if(Telemetry != null) { telemetrySupported = true; } } catch (e:*) { telemetrySupported = false; } /** * @private * Send a telemetry metric if Monocle is currently attached * See the Flash API reference for information about these parameters */ public static function sendMetric(metric:String, value:*):void { try { if(telemetrySupported) { Telemetry.sendMetric(metric, value); } } catch (e:*) { trace(""failed to send metric '""+metric+""' value '""+value+""'""); } } /** * @private * Send a telemetry span metric if Monocle is currently attached * See the Flash API reference for information about these parameters */ public static function sendSpanMetric(metric:String, startSpanMarker:Number, value:*=null):void { if(telemetrySupported) { Telemetry.sendMetric(metric, startSpanMarker, value); } } /** * @private */ public function fixup32(ptr:int, value:int):void { if(fixups) fixups.push(ptr); write32(ptr, value); } /** * @private */ public function fixup16(ptr:int, value:int):void { write16(ptr, value); } /** * @private */ public function fixup8(ptr:int, value:int):void { write8(ptr, value); } /** * @private */ public function getFixups():Vector. { return fixups ? fixups.concat() : null; } /** * @private */ public function getSections():Object { var o:Object = {}; for(var s:String in sections) o[s] = sections[s].concat(); return o; } /** * ""sectName/value"" => explicit value for Csym metadata in this module * and populate ""map"" */ private function mapCsymsWithExplicitValues(map:Dictionary):void { var ns:Namespace var value:uint if(!script) return; // don't map anything for un-initted scripts if(modSyms) { for(var i:int=0; i 5456/*explicit value*/ + 1234/*section offset*/ map[_sect + ""/"" + value] = uint(_off + sections[_sect][0]); } } else { var scriptXML:XML = CModule.describeType(script); var csymsXML:XMLList = scriptXML..metadata.(@name == ""Csym""); for each(var s:XML in csymsXML) { var parent:XML = s.parent(); if(!parent || parent.name() != ""constant"") continue; var argsXML:XMLList = s..arg; if(argsXML.length() < 4) // [type, name, section, value] continue; var args:Array = []; for each(var a:XML in argsXML) args.push(String(a.@value)); var cname:String = parent.@name; ns = new Namespace(String(parent.@uri)); value = script.ns::[cname]; // value of the constant // "".text/12"" => 5456/*explicit value*/ + 1234/*section offset*/ map[args[2] + ""/"" + value] = uint(uint(args[3]) + sections[args[2]][0]); } } } private static var cachedCSyms:Dictionary = new Dictionary; private static var toBeMapped:Vector. = modules; private static function mapCsymsWithExplicitValues():Dictionary { var module:CModule; var newToBeMapped:Vector. = new Vector.; for each (module in toBeMapped) { if (module.script) { module.mapCsymsWithExplicitValues(cachedCSyms); } else { newToBeMapped.push(module); } } toBeMapped = newToBeMapped; return cachedCSyms; } /** * relies on metadata -- won't return info in stripped builds * returns an Array of sym descriptors * sym descriptor is an Array of form: * [nmStyleType, symName(, sectName, value)] * @private */ public function getSymsUsingMD():Array { var esyms:Dictionary = CModule.mapCsymsWithExplicitValues(); return getSymsUsingMDWithExplicitSyms(esyms); } private function getSymsUsingMDWithExplicitSyms(esyms:Dictionary):Array { var script:Object = getScript(); var result:Array = []; var ns:Namespace var value:uint var sv:String if(modSyms) { for(var i:int=0; i = new Vector.; if(size) getScript(); // ensure module is initialized for(var p:int = ctorsSect[0]; size >= 4; size -=4, p += 4) { var fun:int = read32(p); if(fun) callI(fun, args); } } } /** * @private */ public function runDtors():void { var dtorsSect:* = sections["".dtors""]; if(dtorsSect) { var size:int = dtorsSect[1]; var p:int = dtorsSect[0]; var args:Vector. = new Vector.; if(size) getScript(); // ensure module is initialized for(; size >= 4; size -=4, p += 4) { var fun:int = read32(p); if(fun) callI(fun, args); } } } /** * Some fake definitions so that the types look correct in the ASDocs * even though they are actually just ""Object"" due to us wanting the * same abc to work in both the shell and player. */ CONFIG::asdocs { import flash.display.Sprite; /** * Return the current kernel implementation * @return An object that implements the Posix interface defined by PlayerKernel */ public static function get kernel():IKernel {} /** * Set the current kernel implementation * @param kernel The object satisfying IKernel to act as the current flascc Kernel */ public static function set kernel(kernel:IKernel):void {} /** * A reference to the current rootSprite so that flascc code has an easy way of getting to the stage regardless of what preloaders might be employed. */ public static var rootSprite:Sprite; } /** * The actual definitions with duck typed parameters. */ CONFIG::actual { public static var rootSprite:Object; private static var _kernel:Object = null; public static function get kernel():Object { if (!_kernel) { try { _kernel = new flash.utils.ShellPosix(); } catch (e:ReferenceError) { _kernel = new com.adobe.flascc.kernel.PlayerKernel(); } } return _kernel; } public static function set kernel(kernel:Object):void { _kernel = kernel } } /** * A reference to the current Console object, it is set when one of the start methods is called */ public static var activeConsole:Object; private static var _vfs:Object = null; /** * The current VFS implementation * @return An object that implements the IVFS interface */ public static function get vfs():IVFS { if (!_vfs) { _vfs = new com.adobe.flascc.vfs.DefaultVFS(); } return _vfs; } public static function set vfs(fs:IVFS):void { _vfs = fs; } /** * Copies each string into a unique buffer in domainMemory * @param strs A Vector containing the Actionscript strings t be copied into domainMemory * @retun A Vector containing pointers to each of the allocated strings within domainMemory. * As with mallocString() these are manually managed buffers and the caller is * responsible for freeing each pointer using free(). */ private static function mallocStrings(strs:Vector.):Vector. { var result:Vector. = new Vector.; for(var i:int = 0; i < strs.length; i++) result.push(mallocString(strs[i])); return result; } /** * Copies each string into a unique buffer in domainMemory * @param strs A Vector containing the Actionscript strings t be copied into domainMemory * @retun A Vector containing pointers to each of the allocated strings within domainMemory. * As with mallocString() these are manually managed buffers and the caller is * responsible for freeing each pointer using free(). */ private static function mallocPtrArray(ptrs:Vector.):int { if(ptrs.length == 0) return 0; var result:int = malloc(ptrs.length * 4); ram_init.position = result; for(var i:int = 0; i < ptrs.length; i++) ram_init.writeInt(ptrs[i]); return result; } /** * @private */ private static function allocaStrings(strs:Vector.):Vector. { var result:Vector. = new Vector.; for(var i:int = 0; i < strs.length; i++) result.push(allocaString(strs[i])); return result; } /** * @private */ private static function allocaPtrArray(ptrs:Vector.):int { if(ptrs.length == 0) return 0; var result:int = alloca(ptrs.length * 4); ram_init.position = result; for(var i:int = 0; i < ptrs.length; i++) ram_init.writeInt(ptrs[i]); return result; } /** * @private */ public static function runCtors():void { // run in reverse! for each (var mod:CModule in getModuleVector().reverse()) mod.runCtors(); } /** * @private */ public static function runDtors():void { for each (var mod:CModule in getModuleVector()) mod.runDtors(); } /** * This method services any pending uiThunk requests that background threads * have queued up. A good place to call this would be in the enterFrame handler. */ public static function serviceUIRequests():void { var fun:int = read32(_flascc_uiTickProc); if(fun) callI(fun, new []); } /** * Calls the libc __start1 function which, in turn, causes main() to execute. * @param console The current Console object * @param args A vector of Strings that are used to fill the argv array given to main. The first String is typically used to specify the name of the application. * @param env A vector of Strings that are used to populate the environment variables accesible by getenv(). There should be an even number of Strings in this Vector as they are treated as name/value pairs. * @param preserveStack Indicates whether the C stack should be preserved after the call to __start1. If this is set to false the stack depth will return to the value when start() was called upon return. * @return The exit code of the C application */ public static function start(console:Object, args:Vector., env:Vector., preserveStack:Boolean = true):int { if(console) { if(activeConsole) throw new Error(""calling start with a console with an already active console""); activeConsole = console; } var esp:int = ESP; var result:int; try { // TODO: leaks if you invoke main multiple times... var eargs:Vector. = allocaStrings(args); eargs.push(0); eargs = eargs.concat(allocaStrings(env)); eargs.push(0); var argv:int = allocaPtrArray(eargs); esp = ESP; var fargs:Vector. = new Vector.; fargs.push(0, args.length, argv); result = callI(__start1, fargs); } catch(exitCode:Exit) { result = exitCode.code; } finally { if(!preserveStack) ESP = esp; } return result; } /** * Calls the libc __start1 function which, in turn, causes main() to execute. Unlike start(), this method handles the case where the main C run loop has been broken by a call to ""AS3_GoAsync"" within the C code. This allows main to return without allowing C/C++ static initializers to run. This should be used when you want to run long running code with a broken run-loop, or run some code as a library. * @param console The current Console object * @param args A vector of Strings that are used to fill the argv array given to main. The first String is typically used to specify the name of the application. * @param env A vector of Strings that are used to populate the environment variables accesible by getenv(). There should be an even number of Strings in this Vector as they are treated as name/value pairs. * @param preserveStack Inidcates whether the C stack should be preserved after the call to __start1. If this is set to false the stack depth will return to the value when start() was called upon return. */ public static function startAsync(console:Object = null, args:Vector. = null, env:Vector. = null, preserveStack:Boolean = true):void { if(activeConsole) throw new Error(""calling startAsync with an active console""); if(!args) args = new Vector. if(!env) env = new Vector. // try to set us as the ui thread try { C_Run.workerClass[""current""].setSharedProperty(""flascc.uiThread.threadId"", realThreadId); } catch(e:*) {} try { CModule.start(console, args, env, preserveStack); } catch(e:GoingAsync) { } catch(e:*) { activeConsole = undefined; throw e; } } /** * Creates a background Worker and runs the libc function __start1 within that Worker. This allows you to run main without breaking the run loop, but requires the SWF to be version 18 or higher (Flash Runtime 11.5). * @param console The current Console object * @param args A vector of Strings that are used to fill the argv array given to main. The first String is typically used to specify the name of the application. * @param env A vector of Strings that are used to populate the environment variables accesible by getenv(). There should be an even number of Strings in this Vector as they are treated as name/value pairs. * @param afterStackSize The amount of stack space to allocate for the ui thread (code that will run the uiThunk callbacks and also any calls to callI coming from the main Worker). */ public static function startBackground(console:Object = null, args:Vector. = null, env:Vector. = null, afterStackSize:int = 65536):void { if(console) { if(activeConsole) throw new Error(""calling startBackground with a console with an already active console""); activeConsole = console; } if(afterStackSize < 8192 || afterStackSize % pageSize) throw new Error(""invalid stack size""); if(!args) args = new Vector. if(!env) env = new Vector. var esp:int = ESP; try { // TODO: leaks if you invoke main multiple times... var eargs:Vector. = allocaStrings(args); eargs.push(0); eargs = eargs.concat(allocaStrings(env)); eargs.push(0); var argv:int = allocaPtrArray(eargs); esp = ESP; var fargs:Vector. = new Vector.; fargs.push(0, args.length, argv); var tesp:int = esp; var w:* = newThread(0, tesp, __start1, fargs); threadId = realThreadId = 1; // change tid to 1 after newThread! w.setSharedProperty(""flascc.uiThread.threadId"", threadId); var stack:int = sbrk(afterStackSize, pageSize); esp = ESP_init = stack + afterStackSize; w.setSharedProperty(""flascc.uiThread.esp_init"", esp); w.setSharedProperty(""flascc.uiThread.stackSize"", afterStackSize); w.setSharedProperty(""flascc.uiThread.tcbpp"", stack); threadArbMutexLock(); w.start(); // serviceUIRequests shouldn't need much stack here as it will only be servicing posix requests // for very early startup, so we use 4k at the bottom ESP = stack + 4096; // give ourself a bit of stack for serviceUIRequests do // spin (servicing ui requests) until we get our tcbp { threadArbCondWait(1); serviceUIRequests(); } while(!(tcbp = read32(stack))); // signal that we got it and are no longer relying on the mini-stack // (meaning serviceUIRequests can handle more arbitrary requests) write32(stack, 0); threadArbCondsNotify(-1); threadArbMutexUnlock(); } finally { ESP = esp; } } // set up worker init stuff workerInits.push(function(worker:*):void { //trace(""workerInit: "" + threadId); prepForThreadedExec(); var v:Vector. = getModuleVector(); // set section data into worker's start args for each(var m:CModule in v) { var pkgName:String = m.modPackage; var sects:Object = m.getSections(); for(var sname:String in sects) worker.setSharedProperty(""flascc.sect."" + pkgName + ""."" + sname, sects[sname][0]); worker.setSharedProperty(""flascc."" + pkgName + "".oncep"", m.oncep); } }); //trace(""workerInit added: "" + threadId); } /** * @private */ public class GoingAsync {} /** * @private */ class PtrLink { public const ptr:int = 0; public var next:PtrLink; public function PtrLink(ptr:int) { this.ptr = ptr; } } try { new AlcDbgHelper } catch(e:*) {} } package C_Run { import com.adobe.flascc.CModule; [Csym(""U"", ""__start1"")] [Csym(""U"", ""_malloc"")] [Csym(""U"", ""_free"")] [Csym(""U"", ""_flascc_uiTickProc"")] [Csym(""D"", ""__DYNAMIC"")] /** * no dyld yet * @private */ public const __DYNAMIC:int = 0; /** * setjmp id for calling function (calling setjmp) * @private */ public var sjid:int; /** * thread control block for current thread * @private */ public var tcbp:int = -1; /** * @private */ public function longjmp(ptr:int, retval:int):void { var id:int = CModule.read32(ptr+4); var esp:int = CModule.read32(ptr+8); //trace(""longjmp: "" + esp + ""/"" + retval); throw new LongJmp(esp, id, retval); } /** * @private */ public function setjmp(ptr:int, id:int, esp:int):int { CModule.write32(ptr+4, id); CModule.write32(ptr+8, esp); //trace(""setjmp: "" + esp); return 0; } } ",12216,False,2408.89869681527,median "= TimeBook - User Guide :site-section: UserGuide :toc: :toc-title: :toc-placement: preamble :toclevels: 3 :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full :experimental: ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: :important-caption: :exclamation: endif::[] :repoURL: https://github.com/AY1920S1-CS2103T-T10-4/main By: `Team TimeBook` Since: `Aug 2019` Licence: `MIT` Our team is still working on the User Guide. Keep a look out for more cool and exciting features coming soon! == Introduction Thank you for checking out TimeBook! // tag::ppp-introduction[] TimeBook is a desktop application that is morphed from AddressBook Level 3 (AB3). TimeBook is a scheduling application that aims to help busy NUS undergraduates keep track of the schedules of you and your friends. It also can find the common free time and venues among you and your friends. TimeBook will have the following features: . A graphical user interface (GUI) but most of the interactions with the application would happen using command line interface (CLI). . Allows users to add the schedules of his or her friends and organise them into groups. . Deconflict different schedules of different people and different groups to find the common free time among them. . Integration with NUSmods API to allow users to enter their NUSmods timetable link to add it to their schedule. . Integration with Google Maps API to allow the application to evaluate the best venue for the group to meet up during the free time in their schedules. // end::ppp-introduction[] == Understanding this guide === Basic Information This guide explains how you can use *TimeBook* to the fullest extent to assist you to plan for your group's meeting. You can find the steps needed to start scheduling group activities with your friends or loved ones in the <> and general *lifecycle* usage of our application. If you happen to stumble upon some difficulties, our <> (FAQ) is here to address that. If you are an experienced *Command Line Interface (CLI)* user, you can hop right into using the application by looking at our <>. Otherwise, take a look at the <> section to obtain more information on how to use our application. We have used the following symbols to help you better understand our application usage. (For now we have not picked our symbols yet.) [width=""80%"",cols=""^3, ^10"",options=""header""] |==== | Symbol | What it means | image:./icons/important.png[] | Important information that you may want to note. | image:./icons/lightbulb.png[] | Shortcuts or hacks that would improve your experience using this application. | image:./icons/warning.png[] | Warning! Be careful if you encounter this symbol. |==== == Quick Start ==== image:./icons/important.png[] Make sure that your screen resolution height is at least 720 pixels before you continue this section! ==== . Ensure you have Java `11` or above installed in your Computer. . Download the latest `timebook.jar` link:{repoURL}/releases[here]. . Copy the file to the folder you want to use as the home folder for your TimeBook. . Double-click the file to start the app. + The GUI should appear in a few seconds. image:Ui.png[width=""790""] + . Type the command in the command box and press kbd:[Enter] to execute it. + e.g. typing *`help`* and pressing kbd:[Enter] will open the help window. . Some example commands you can try: * *`list`* : lists all information in TimeBook. * *`addperson`* `n/John Doe p/98765432 em/johnd@example.com a/John street, block 123, #01-01` : adds a contact named `John Doe` to the TimeBook. * *`deleteperson`* `n/John Doe` : deletes the person named `John Doe` from the TimeBook. * *`addgroup`* `g/CS2103` : adds a new group called `CS2103` to the TimeBook. * *`addtogroup`* `n/John Doe` `g/CS2103` : Adds a person `John Doe` into the group `CS2103`. * *`exit`* : exits the app + [IMPORTANT] ==== include::UserGuide.adoc[tag=user-profile-full] ==== . Refer to <> for details of each command. == Inexperienced CLI user Unlike most applications, where you use your mouse to interact with the application such as scrolling and clicking, our application mostly use the *Command Line Interface*. Most of the time, you would be interacting with the application through typing commands in the command box of the application. You can play around with the commands in <> to get yourself warmed up. == GUI Components In this section, you will learn more about the different components of our application. Here is an overview of all of the components in our application: image::guiComponents.png[] === MenuBar You may use the menu bar to access file or exit the application. image::menuBar.png[] === Schedule Display The schedule display is the main component that you will be looking at to look schedules of yours or others! image::scheduleDisplay.png[] ==== How to read the schedule view Unsure of how to read the combined schedules of your friends in TimeBook? Here is a simple example to guide you! TimeBook ensures that the leftmost column will always start from today's date. Each unnumbered coloured block belongs to someone's schedule in the group. For example, the image below highlights all of Charlie's schedule. image::charlieBusyTimeslot.png[] Take note of the numbered green boxes you see below! [[FreeTimeSlot-Scheule]] image::freeTimeslot.png[] These are the common free time slot that you and your *entire* group members share! You can use these numbered green boxes to arrange your meetings or share it with your group members to pick. **** image:./icons/important.png[] Note that the labels for each of the coloured block will become hidden if each block becomes too small! To get more information about the coloured block, you can just hover your mouse over it! + **** === Tabs Tabs will contain your contacts and your groups. You can use it to see all your existing contacts and groups! image::tabs.png[] === Result Display Box This box shows you whether your command executed is successful or unsuccessful. If you encounter an error message here, look at our <> section to see what is the cause of error. image::resultDisplayBox.png[] === Command Box Type your commands here to execute them! image::commandBox.png[] // tag::suggestions-autocomplete[] === Suggestions Autocomplete TimeBook comes with a helpful feature that provides suggested commands or relevant values so you can spend less time typing commands and more time on your group meetings. When you type a command, TimeBook will show a dropdown with similarly matching commands. For example, you type in the command `add`. TimeBook will then suggest commands such as `addevent`, `addgroup`, `addperson` like so: image::command-suggestions/user-guide-example-step1.png[width=50%,pdfwidth=50vw] If you meant to type the `addevent` command, you can immediately select it by pressing the kbd:[Tab] key. Otherwise, you can pick other options by using the kbd:[Up] or kbd:[Down] arrow keys and then hit the kbd:[Tab] key to confirm your selection. For now, try selecting the `addtogroup` command using the kbd:[Down] and kbd:[Tab] keys. TimeBook will complete the command like this: image::command-suggestions/user-guide-example-step2.png[width=50%,pdfwidth=50vw] ***** image:./icons/lightbulb.png[] You can type an abbreviated version of any command as long as the letters are in order! For example, instead of typing `addtogroup`, try `atg`. ***** Remember how TimeBook can also suggest relevant values? Let's try that by specifying a person's name using the `n/` parameter like so: image::command-suggestions/user-guide-example-step3.png[width=50%,pdfwidth=50vw] Again, TimeBook provides useful suggestions, in this case, the names of the people we've previously added. Now, try using the kbd:[Tab] key to immediately fill in ""Bobby"". image::command-suggestions/user-guide-example-step4.png[width=50%,pdfwidth=50vw] Now, let's complete the `addtogroup` command. Let's add Bobby to the Friends group by typing `g/` and using the suggestions to help us pick the Friends group. [width=""100%"",cols=""^3,^1,^3"",frame=""none"",grid=""none"",valign=""middle""] |======= a|image::command-suggestions/user-guide-example-step5.png[] | –kbd:[Tab]–> a|image::command-suggestions/user-guide-example-step6.png[] |======= Let's say we change our mind and don't want to add Bobby to the Friends group. No problem, just remove Bobby's name and pick someone else using the familiar kbd:[Up], kbd:[Down] and kbd:[Tab] keys. TimeBook is smart enough to only fill in the name parameter and won't mess up the rest of your command. [width=""100%"",cols=""^3,^1,^3"",frame=""none"",grid=""none"",valign=""middle""] |======= a|image::command-suggestions/user-guide-example-step7.png[] | –kbd:[Tab]–> a|image::command-suggestions/user-guide-example-step8.png[] |======= Congratulations! You've now mastered the suggestions feature using just three simple keys, the kbd:[Up] and kbd:[Down] arrow keys to navigate between suggestions and the kbd:[Tab] key to select it. // end::suggestions-autocomplete[] The following sections will explain all the commands we have in TimeBook and what they do. [[Features]] == Commands ==== *Command Format* * Words in `UPPER_CASE` are the parameters to be supplied by you e.g. in `addperson n/NAME`, `NAME` is a parameter which can be used as `addperson n/John Doe`. * Items in square brackets are optional e.g `n/NAME [t/TAG]` can be used as `n/John Doe t/friend` or as `n/John Doe`. * Items with `…`​ after them can be used multiple times including zero times e.g. `[t/TAG]...` can be used as `{nbsp}` (i.e. 0 times), `t/friend`, `t/friend t/family` etc. * Parameters can be in any order e.g. if the command specifies `n/NAME p/PHONE_NUMBER`, `p/PHONE_NUMBER n/NAME` is also acceptable. ==== === Navigation ==== Home: `home` You can return back to the home page to see your upcoming schedule for today. Format: `home` ==== Switch tabs: `switch-tab` You can switch the tab of *Person* and *Group* using this command. Format: `switch-tab` ==== Viewing help: `help` Format: `help` ==== Exiting the program: `exit` Exits the program. + Format: `exit` ___ === Person Management [[edit-user-command]] ==== Editing your details: `edituser` [IMPORTANT] ==== include::UserGuide.adoc[tag=user-profile-brief] To personalize TimeBook and make it yours, use the `edituser` command as described below. ==== ____ Lets start off by editing our profile by using the command `edituser`! ____ Format: `edituser [n/NAME] [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` **** * The `n/` prefix (optional) specifies your `name` ** Names must be alphanumeric * The `p/` prefix (optional) specifies your `phone number` ** Phone numbers must only contain numbers and must be at least 3 digits long * The `em/` prefix (optional) specifies your `email address` ** Emails should be of the format local-part@domain and adhere to the following constraints: 1. The local-part should only contain alphanumeric characters and these special characters, excluding the parentheses, (!#$%&'*+/=?`{|}~^.-) . 2. This is followed by a '@' and then a domain name. The domain name must: - be at least 2 characters long - start and end with alphanumeric characters - consist of alphanumeric characters, a period or a hyphen for the characters in between, if any. * The `a/` prefix (optional) specifies your `address` ** An address can take any values * The `r/` prefix (optional) specifies a `remark` ** A remark must be alphanumeric * The `tag/` prefix (optional) specifies your `tag` ** You can have multiple tags ** A tag must be alphanumeric and cannot contain spaces * At least one of the optional fields must be provided. * When editing tags, your existing tags will be removed (i.e. adding of tags is not cumulative). * You can remove all your tags by typing `tag/` without specifying any tags after it. **** Suppose our name is `Alice`, we can edit our profile like this! Example: * `edituser n/Alice p/91239123 a/Kent Ridge Drive em/alice@gmail.com r/Student` image::scheduler/edituser.png[width=100%] After editing our profile, this is what we should see! ==== Adding a person: `addperson` ____ The first thing to do in TimeBook is to add people that you know! It could be friends, family and even your colleagues! ____ To add a new person into TimeBook, simply use the command `addperson` and specify his or her name! You can also optionally specify his or her phone number, email address, home address, a remark and tags. Format: `addperson n/NAME [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` **** * The `n/` prefix specifies the `name` of the person to add * The `p/` prefix (optional) specifies a `phone number` * The `em/` prefix (optional) specifies an `email address` * The `a/` prefix (optional) specifies an `address` * The `r/` prefix (optional) specifies a `remark` * The `tag/` prefix (optional) specifies a `tag` ** A person can have multiple tags **** Suppose we met our new friend `Fred` and want to add him into TimeBook, simply use this command! Example: * `addperson n/Fred p/91234567 em/fred@example.com a/kent ridge drive r/friend tag/Friends tag/Colleague` image::scheduler/addperson.png[width=100%] After adding `Fred` into the TimeBook, his name will appear on the list of people on tabs in the side panel! ==== Editing a person: `editperson` ____ Accidentally added the wrong info of a person into TimeBook? No worries, you can simple edit an existing person with our `editperson` command! ____ To edit an existing person, simply use the `editperson` command and specify the name of the person you wish to edit with the `ed/` prefix! Then, simply edit each of the fields of a person with their corresponding prefixes! Format: `editperson ed/PERSON_NAME [n/NAME] [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` **** * The `ed/` tag specifies the person to be edited ** This person must exist in the TimeBook * At least one of the optional fields must be provided. * When editing tags, the existing tags of the person will be removed i.e adding of tags is not cumulative. * You can remove all the person's tags by typing `tag/` without specifying any tags after it. * Note: `TAG` cannot have white space in the argument. **** Suppose we added Fred's name wrongly, and he wants to be called `Freddie`. Additionally, he has also changed his phone number, and he wants to be your best friend! To update his particulars, simply execute this command! Example: * `editperson ed/Fred n/Freddie p/85868784 r/best friend tag/bestfriend` image::scheduler/editperson.png[width=100%] After editing a person, this is what you will see! Freddie's details has been updated accordingly! ==== Deleting a person: `deleteperson` ____ Want to delete a person from TimeBook? That's easy! Simply use our `deleteperson` command! ____ To delete a person from TimeBook, simply use the `deleteperson` command and specify the name of the person you wish to delete! Format: `deleteperson n/NAME` **** * the `n/` tag specifies the name of the person to be deleted * Only one person can be deleted at a time **** Suppose our business with Freddie is over, we can simply delete him from TimeBook! Examples: * `deleteperson n/Freddie` image::scheduler/deleteperson.png[width=100%] As you can see, after deleting Freddie, he is removed from our persons tab! // tag::showperson[] ==== Show person: `show` Want to arrange a private meeting with someone in TimeBook? You can see the schedule of this person up to 4 weeks in advance using the `show` command. + Format: `show n/NAME` **** * Shows the full name, address, email, phone number and schedule of this person. **** Example: . Type `show n/Bobby` in the command line as shown below: + + .Command box image::showpersoncommand.png[] . Hit the kbd:[Enter] key and you should see details of the person! You should see a window similar to the one below. + .Result after executing the `show` command for Bobby image::showpersonresult.png[] // tag::navigationforshow[] ***** image:./icons/lightbulb.png[] You can use the command `scroll` to help you scroll the schedule view without touching your mouse! image:./icons/lightbulb.png[] You can use the command `togglenext` see the schedule for next week! You may see this schedule up to 4 weeks in advance. After you've reached the fourth week's schedule, the next `togglenext` command will start back on the first week's schedule. image:./icons/important.png[] Unfortunately, TimeBook does not let you see a schedule that has already passed. ***** // end::navigationforshow[] // end::showperson[] === Schedule Management // tag::addmod[] // tag::addmod-short[] ==== Add Module to Schedule: `addmod` Want to add an NUS module to you or your friend's schedule on TimeBook? You can do so with the `addmod` command! If you already have your timetable on NUSMods, check out <>! Format: `addmod [n/NAME] m/MODULE_CODE cl/CLASS_1_TYPE:CLASS_1_NUMBER,...` **** * Currently supports academic year 2019/2020 and semester 1 only. * If the NAME is not provided, then the modules will be added to the default user, which is you! * image:./icons/warning.png[]: Just like adding a normal event via `addevent`, the module will only be added if the specified classes does not clash with any events in the person's schedule. **** Examples: * `addmod m/CS2103T cl/LEC:G01` + This adds CS2103T lecture G01 to your schedule. * `addmod n/John m/CS3230 cl/LEC:1,TUT:08` + This adds CS3230 lecture 1 and tutorial 08 to John's schedule. * `addmod n/John m/CS2100 cl/LEC:1,TUT:01,LAB:08` + This adds CS2100 lecture 1, tutorial 01 and lab 08 to John's schedule. // end::addmod-short[] *How do I add an NUS module to my schedule?* . Suppose you want to add CS3230 lecture 1 and tutorial 08 to your schedule. You can add the classes to your schedule easily by first typing `addmod m/CS3230 cl/LEC:1,TUT:08` into the command box, then pressing btn:[Enter] to execute it! + image::nusmods/addmod1.PNG[] . If you manage to successfully add the module and its classes into the person's schedule, you will see the person's schedule appearing with the newly added timeslots: + image::nusmods/addmod2.PNG[] // end::addmod[] // tag::addmods[] ==== Add Modules via NUSMods Link: `addmods` Already have your modules timetable on NUSMods? Great, you can easily add your modules timetable into TimeBook with the `addmods` command! Format: `addmods [n/NAME] link/NUSMODS_SHARE_LINK` **** * Reads the specified `NUSMODS_SHARE_LINK` to get the modules and classes, then adds the classes into the person's schedule. * If the NAME is not provided, then the modules will be added to the default user, which is you! * Currently supports academic year 2019/2020 and semester 1 only. * image:./icons/warning.png[]: Just like adding a normal event via `addevent`, the module will only be added if the specified classes does not clash with any events in the person's schedule. **** *Examples:* * `addmods link/https://nusmods.com/timetable/sem-1/share?CS2101=&CS2103T=LEC:G05&CS3230=LEC:1,TUT:08&CS3243=TUT:07,LEC:1&GEQ1000=TUT:D17` + This will add the modules in the NUSMods link to your schedule. * `addmods n/John link/https://nusmods.com/timetable/sem-1/share?CS2101=&CS2103T=LEC:G05&CS3230=LEC:1,TUT:08&CS3243=TUT:07,LEC:1&GEQ1000=TUT:D17` + This will add the modules in the NUSMods link to John's schedule. * `addmods n/Bob link/https://nusmods.com/timetable/sem-1/share?CS2101=&CS2103T=LEC:G05&CS3230=LEC:1,TUT:08&CS3243=TUT:07,LEC:1&GEQ1000=TUT:D17` + This will add the modules in the NUSMods link to Bob's schedule. *How do I add my team member John's NUSMods timetable to TimeBook?* . Well that is simple, add John's NUSMods timetable by first typing `addmods n/John link/` into the command box, then copy and paste his NUSMods link. Finally, press btn:[Enter] to execute it. + image::nusmods/addmods1.PNG[] . If the command succeeds, you will see John's schedule update with the newly added timeslots from his NUSMods timetable: + image::nusmods/addmods2.PNG[] // end::addmods[] ==== Add Event to Schedule: `addevent` ____ Have an event outside of your NUSmods timetable? Simply add them in using the `addevent` command! ____ To add an event into TimeBook, simply specify the name of that event, and the time slots of that event! Format: * `addevent [n/NAME] e/EVENT_NAME t/DATETIME...` **** * The `n/` (optional) prefix specifies the name of the person whom we want to add an event to. * If the `n/` prefix is not specified, TimeBook will add the event to your schedule! * The `e/` prefix specifies the name of the event to be added. ** An event name must be alphanumeric and must not be blank * The `t/` prefix specifies the time slot of that event. ** Format: `DATE-STARTTIME-ENDTIME-LOCATION` *** Date format: `ddMMyyyy` *** Start/End time format: `HHmm` *** Location: Can take in any values. ** An event can have multiple time slots. ** A time slot must be between `0800` to `2000` hrs. ** A time slot must not have a clash with an existing event. **** Suppose Bobby has to meet his project mates to work on his project, let's try adding that event into our TimeBook! Example: * `addevent n/Bobby e/Project Meeting t/10112019-1200-1400-COM1 t/13112019-1000-1200-AS6` image::scheduler/addevent.png[width=100%] After adding the event into our TimeBook, Bobby's schedule is automatically updated! ==== Delete an Event from a Schedule: `deleteevent` ____ What should I do if an event is cancelled? Simply delete it from TimeBook with our `deletevent` command! ____ To delete an event, simply execute the `deleteevent` command and specify the event to delete and the person to delete it from! Format: * `deleteevent [n/NAME] e/EVENT_NAME` **** * The `n/` (optional) prefix specifies the name of the person whom we want to delete an event from. * If the `n/` prefix is not specified, TimeBook will try to delete the event from your schedule! * image:./icons/lightbulb.png[] You can delete a module by specifying the module code! A module's event name is its module code! **** Suppose Bobby wants to drop CS2105 from his timetable as he finds it too hard to cope with so many modules. We can simply delete it! Example: * `deleteevent n/Bobby e/CS2105` image::scheduler/deleteevent.png[width=100%] After deleting that event from TimeBook, Bobby's schedule is automatically updated! //tag::schedule-command[] ==== Generate a Schedule: `schedule` ____ Want to see a schedule between you and your friends? Simple use the `schedule` command! ____ To generate a schedule for you and your friends, simply execute the `schedule` command and specify who to add to this schedule! Format: * `schedule n/NAME...` **** * The `n/` prefix specifies the name of the person whom we want to add to this schedule * You can add multiple people into a schedule **** Lets try and generate a schedule between you, Bobby and Charlie! Execute the following command! Example: * `schedule n/Bobby n/Charlie` image::scheduler/schedule.png[width=100%] When executing the command, TimeBook will calculate the free time slots among the schedule members! //end::schedule-command[] === Group Management ==== Adding a group: `addgroup` ____ In TimeBook, we allow you to organise your contacts too! This can be done through making groups! This can be done using our `addgroup` command! ____ To add a new group into TimeBook, simply execute the `addgroup` command and specify the name of the group you want to make! Format: * `addgroup g/GROUP_NAME [d/GROUP_DESCRIPTION] [role/USER_ROLE]` **** * image:./icons/important.png[] Whenever a new group is created, you are automatically added into that group! * The `g/` prefix specifies the name of the group you want to create. ** A group name must be alphanumeric * The `d/` prefix (optional) gives a description to the group ** A group description must be alphanumeric * The `role/` prefix (optional) specifies the role you play in that group ** A role must be alphanumeric **** Suppose you want to create a new group for your CS2103 project, and you are appointed as the leader for this group! Let's try to add a new group with the following command! Example: * `addgroup g/CS2103 d/A CS2103 project group role/Leader` image::scheduler/addgroup.png[width=100%] When a new group is added, it is automatically added into the list of groups! ==== Editing a group: `editgroup` ____ The details for your group has changed? Edit it with our `editgroup` command! ____ To edit an existing group, simply use the `editgroup` command and specify the name of the group you wish to edit with the `ed/` prefix! Format: `editgroup ed/GROUP [g/GROUP_NAME] [d/GROUP_DESCRIPTION] [role/USER_ROLE]` **** * The `ed/` tag specifies the group to be edited ** This group must exist in the TimeBook * At least one of the optional fields must be provided. **** Suppose we entered the details for our group wrongly, no worries we can edit them! Example: * `editgroup ed/CS2103 g/CS3203 d/A CS3203 project group role/Member` image::scheduler/editgroup.png[width=100%] When a group is edited, it is automatically updated as shown above! ==== Add Person to Group: `addtogroup` ____ After you have created your group, you can add people into the group with our `addtogroup` command! ____ To add a person into a group, simply execute the `addtogroup` command, and specify the person's name and the group's name! Format: `addtogroup n/PERSON_NAME g/GROUP_NAME [role/ROLE]` **** * The `n/` prefix specifies the name of the existing `person` in TimeBook * The `g/` prefix specifies the name of the existing `group` in TimeBook * The `role/` prefix (optional) specifies the role this person would play in the group **** Let's add a new person Denise into our CS3203 project group! Example: * `addtogroup n/Denise g/CS3203 role/Manager` image::scheduler/addtogroup.png[width=100%] When a new person is added into the group, it automatically updates the group's schedule as well! ==== Delete a Person from Group: `deletefromgroup` ____ What if I want to remove a person from my group? You can! With our `deletefromgroup` command! ____ To delete a person from a group, simply execute the `deletefromgroup` command, and specify the person's name and the group's name and the person will be removed from the group! Format: * `deletefromgroup n/NAME g/GROUP_NAME` **** * The `n/` prefix specifies the name of the `person` * The `g/` prefix specifies the name of the `group` * This person must be in the group * image:./icons/important.png[] deleting a person from group does not delete your contacts! Your contacts still exists in your persons tab! **** Let's remove Charlie from our group! We can simply execute the following command! Example: * `deletefromgroup n/Charlie g/CS3203` image::scheduler/deletefromgroup.png[width=100%] When a person is removed from the group, the group's schedule will automatically be updated as well! ==== Deleting a group: `deletegroup` ____ The project is over, and there is no need for this group anymore? Delete it! ____ To delete a group, simply execute the `deletegroup` command and specify the group's name! Format: * `deletegroup g/GROUP_NAME` **** * The `g/` prefix specifies the name of the `group` * image:./icons/important.png[] deleting a group does not delete your contacts! Your contacts still exists in your persons tab! **** Let's delete CS3203 group from our TimeBook! Simply use this command! Example: * `deletegroup g/CS3203` image::scheduler/deletegroup.png[width=100%] Deleteing a group will automatically update your groups tab! // tag::showgroup1[] ==== Show group: `show` Want to see your group's schedules to plan for your next group meeting? The `show` command is what you need to see the schedules of your group members! You can view a group's schedule up to 4 weeks in advance. + Format: `show g/GROUP_NAME` **** * Shows the description, members and aggregated schedules for this group. **** // end::showgroup1[] [IMPORTANT] ==== include::UserGuide.adoc[tag=user-profile-full] ==== // tag::showgroup2[] Examples: . Let's say you want to organise a group meeting for a group named CS2103. Simply enter `show g/CS2103` in the command line as shown below + + .Command box image::showgroupcommand.png[] . Hit the kbd:[Enter] key and you should see the details of this group in a similar window below. + [[showgroupresult]] .Result after executing `show g/CS2103` image::showgroupresult.png[sgr,900,600] include::UserGuide.adoc[tag=navigationforshow] ==== Look at some members: `lookat` Suppose that all of your group members are extremely busy and the common free time is too short to do any productive work, you may use the `lookat` command to see if you can meet with some of your group members. You *must* be viewing a group's schedule in order for this command to work. Format: * `lookat [n/Name]...` The `lookat` command takes in any number of `n/Name` arguments and highlights the group members according to name. Example: Let's use the same schedule exactly like the one shown <<#showgroupresult, above>>. * Type `lookat n/Bobby n/Denise` if you are interested to inspect both Bobby's and Denise's schedules! You should see that both of these schedules become highlighted. .Zoom in of Bobby and Denise's schedule image::lookatgroupresult.png[lagr,800,500] ***** image:./icons/important.png[] *Empty blocks* represent the free time slots for the group members that you are looking at. The green blocks still represent the common free time slots for the entire group! ***** // end::showgroup2[] === Advanced Features // tag::showmod[] ==== Show Module: `showmod` Want to know more information about an NUS module? Use `showmod` to quickly open up the NUSMods page for a specific module on your browser! Format: `showmod m/MODULE_CODE` **** * image:./icons/warning.png[]: This command requires internet connection. **** Examples: * `showmod m/CS2103T` + Opens up https://nusmods.com/modules/CS2103T on your default browser. * `showmod m/CS2101` + Opens up https://nusmods.com/modules/CS2101 on your default browser. // end::showmod[] ==== Export: `export` Want to share a schedule with your friends? This command exports a visualisation representation of the schedule (timetable) of a group or person to a PNG file! + **** image:./icons/warning.png[] Take note when exporting a person's schedule, *sensitive information* are omitted. Only the person's schedule is exported. image:./icons/warning.png[] Take note that if you are exporting a group's schedule, the *entire* group's schedule will be exported. If you have used the `lookat` command, this command disregards it. **** Format: * Simply enter the `export` command to export the currently shown schedule in TimeBook! + //tag::select-command[] ==== Select Time Slot: `select` ____ Want to get more information about a particular time slot? Want to know where the venue of that time slot is? No worries! Simply select the time slot and TimeBook will tell you all about it! ____ When viewing a schedule on TimeBook, you can select a time slot to get more information out of it! The `select` command works when you are viewing a group's schedule, person's schedule or home page! The format for this command's use are detailed below! Format (group schedule): `select n/NAME [week/WEEK_NUMBER] i/ID` * Selects a time slot specified by `ID` that belongs to a person specified by `NAME`, on week `WEEK_NUMBER` Format (person schedule): `select [week/WEEK_NUMBER] i/ID` * Selects a time slot specified by `ID` on week `WEEK_NUMBER` that belongs to the current person shown in the schedule * If a name is specified, TimeBook will ignore it! Because we know you want to view the current person that is shown! Format (home): `select i/ID` * Selects a time slot specified by `ID` on your home page. The home page will not show the ID of the time slot, the `ID` is ordered with the earliest time slot as `ID:1` * If a person name or week is specified, TimeBook will ignore it! Because we know you want to view the time slots on your home page! Prefixes: * `n/`: specifies the name of a person ** A name must be alphanumeric * `week/` specifies the week of the schedule (optional) ** A week must be an interger between 1 and 4 inclusive ** If no week number is specified, TimeBook will choose the default week 1 * `i/`: specifies the ID number of the time slot ** An ID must be a positive number. When you execute the `select` command, it generates a pop up window that shows you the details of the selected time slot! We have also integrated this service with GoogleMaps and shows you the location of this time slot on the map! The figure below shows how a pop up window will look like! image::scheduler/selectpopup.png[width=100%] After you have viewed the time slot details, simply press the `ESC` key on your keyboard, and it will close the pop up! You will never have to touch your mouse! | image:./icons/important.png[] | When the location of the time slot is not a valid location in NUS, the location will not be shown on the map! The following shows some example usage! image::scheduler/select1.png[width=100%] When a group's schedule is shown, each members time slots are colour coded as shown above. Each time slot is also labeled with an ID for easy reference! Let us try to select Bobby's time slot 1. To select it, simply execute the following command! Example: * `select n/Bobby i/1` After executing that command, a pop up will be shown just like the one above! image::scheduler/select2.png[width=100%] When a person's schedule is shown, each events are colour coded as shown above. Each time slot is also labeled with an ID for easy reference! The name of the event is also shown! Let us try to select time slot 1. To select it, simply execute the following command! Example: * `select i/1` After executing that command, a pop up will be shown just like the one above! image::scheduler/select3.png[width=100%] When the home page is shown, you can select each time slot on the list! Do note that the first time slot on the list will have `ID:1` and the following time slots will follow with the next number. We chose to omit the number so you have a more cleaner home page! Simply execute the `select` command and specify the time slot you want to view like so: Example: * `select i/1` After executing that command, a pop up will be shown similar to the one above! //end::select-command[] //tag::Closest-Common-Location[] [[Closest-Common-Location]] === Closest Common Location TimeBook will also help you to decide where to meet for your project meetings by suggesting to you an optimal location for everyone. The optimal location is the closest location for everyone to meet in NUS based on their schedule. In time book we define the optimal location for everyone as the _closest common location_. *Steps* . Set up your group by: .. Adding your group members to your TimeBook with `addperson` command .. Adding your group to TimeBook with `addgroup` command .. Add your group members to your group with `addtogroup` command . Get the relevant information for your group schedule with `show g/[GROUP_NAME]` .. Identify the `ID` and `Week` of the time slot you want to get the closest common location for. . With the free time slot `id` and `week` get the details for the closest common location with `selectfreetime` command . Press `esc` button to close the popup *Constraints* Due to the lack of internet connectivity, TimeBook will only support locations that are in NUSMods and identifiable by Google Maps. The full list of supported locations is <>. *Definitions* . We define closest common location as the location that requires the least average distance to travel to and from different sources by car. . Locations that are not supported are voided and are not used for the calculations of the closest common location and average travelling distance. . Refer to the `Developer Guide` on how we computed the closest common location. ==== Select Free Time `selectfreetime` Select a free time slot to launch a popup window with all the relevant information to help you make decide on the venue to conduct your project meetings at. The image below is an example of the popup. Below is an example of a popup. [#img-SuccessfulPopup] .An example of a popup when `selectfreetime` is executed image::gmaps/SuccessfulPopup.png[SuccessfulPopup] command: `selectfreetime [week/WEEK_NUMBER] i/FREETIMESLOTID` Examples: * `selectfreetime i/3` * `selectfreetime week/2 i/3` _Description_ When the command is executed, a popup will appear that shows all the information of the closest common location for a particular free time slot in a group. _Prerequisite_ . You must be have group on TimeBook with members in it. . You must execute `show g/[GROUP NAME]` before executing `selectfreetime` command. _Parameters_ . `[WEEK_NUMBER]` - Description: The week(1-4) of the group schedule you want to select the free time slot from. If parameter is not stated, it will default to the first week(the default schedule when you execute `show g/GROUP_NAME`). - Type: `Integer` - Enum: `1`, `2`, `3`, `4` . `FREETIMESLOTID` - Description: ID of the free time slot in the <>. You can get this from the number in the free time slot box. You can only enter the `id` that is shown on the screen. - Type: `Integer` _Success Response_ If you follow the steps above, a popup will appear as seen in the Figure above. There are two main information that you will see in the popup when you execute the command. . The summary of the results that will be `displayed` on the top of the popup. .. *Your best location to meet up is:* The first choice location to meet(closest for everyone). .. *Everyone's locations:* List of locations that the group members will be at before the free time slot. .. *Out of all these locations, the valid locations are:* List of TimeBook supported locations that the group members will be at before the free time slot that. ... Subset of the *Everyone's locations:* list .. *Locations that cannot be found in NUS:* List of locations that the group members will be at before the free time slot but not supported by TimeBook. ... Subset of the *Everyone's locations:* list ... If all the locations are valid, this attribute will be empty as seen in the Figure above . The full details of the first, second and third closest common location will be shown at the bottom of the popup. .. First choice represents the first closest and so on and so forth. .. The average distance(m) to reach the various locations will be displayed below the respective choices. .. The picture of the location of the venue on Google Maps will be displayed below each choice. ... For locations that are not supported on Google Maps, a picture of the center of NUS will be displayed. _Failure Response_ - `Error` when all the source locations are not recognised by TimeBook, a popup will not appear. Feedback box will show: ``` We could not find a common location because all places cannot be found in NUS. The locations are: ``` - `Error` when all the group members are not in school before the free time slot, a popup will not appear. Feedback box will show: ``` We could not find a common location because: Everyone has not started their schedule yet. Feel free to meet up any time. ``` - `Error` when invalid free time slot `ID` entered. Feedback box will show: ``` Invalid time slot ID: 0. Please enter a valid id as shown in the GUI. ``` - `Error` when invalid `GROUP_NAME` entered. Feedback box will show: ``` Cannot recognise GROUP_NAME. Make sure you entered the correct value. ``` ==== Close popup `esc` After you are done with viewing the information on the popup press `esc` button on your keyboard to close the popup and and return to the main screen. Format: kbd:[esc] button on keyboard. // end::Closest-Common-Location[] === Upcoming schedule list. Unsure of what is your next event for the day? TimeBook's home page has a list that keeps track of your upcoming events for the day and would automatically tick off events that have past! Format: `home` === Saving the data TimeBook data are saved in the hard disk automatically after any command that changes the data. + There is no need to save manually. == FAQ [qanda] [[alice-notice]] How do I store my details and schedule?:: // tag::user-profile-full[] // tag::user-profile-brief[] When you first start using TimeBook, a default profile will be created for you! This default profile will have a default name: `User` // end::user-profile-brief[] + {nbsp} + To personalize TimeBook and make it yours, rename `User` by entering the command `edituser n/Your Name Here`. If you'd like to fill in more details, you can do so using the <>. // end::user-profile-full[] + {nbsp} + How do I transfer my data to another Computer?:: Install the app in the other computer and overwrite the empty data file it creates with the file that contains the data of your previous TimeBook folder. + {nbsp} + Why can I enter irrelevant arguments?:: We understand that users occasionally make error while typing and it is frustrating for the application to fail because of it. Thus for all commands that do not require any arguments(ie `help`, `home` and `exit`), TimeBook allows you to enter any value after the command word. For example `help 1` will execute `help` command eventhough `1` is irrelevant to the command. We hope with this feature you will have a seamless and pleasant experience with TimeBook. + {nbsp} + Help! I encountered an error!:: We understand that you may encounter a weird error message and are unsure of what it means so we prepared this section that describes the uncommon errors that you may see. [cols=""25h, ~""] |=== |Error message |What it means: | Invalid timing arguments | Ensure that the time you provide as argument follow the format. Example: 11 Nov 2019, 0800 to 0900 is represented as 11112019-0800-0900 | Clash in events | There is already a pre-existing event that is happening at that time slot. | Duplicate Mapping | This person is already in the group. | Cannot find closest location | The closest common location cannot be determined because everyone is not in NUS. | XXX does not exist | This person or group does not exist in TimeBook. Some names are case-sensitive. | No schedule to XXX | This error occurs when you use `scroll` and `togglenext` command when there is no schedule shown. | No group schedule is shown | You'll see this error when you are invoking the `look at` command when a group schedule is not displayed. | Internal Error. Please try again later | You'll see this error when our remote database cannot handle your requests. |=== {nbsp} + == Command Summary *Navigation* * *Return to Home page* : `home` * *Switch tabs* : `switch-tab` * *Viewing help* : `help` * *Exiting the program* : `exit` *Person Management* * *Edit your details* : `edituser` * *Add Person* `addperson n/NAME [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` + e.g. `addperson n/James Ho p/22224444 em/jamesho@example.com a/123, Clementi Rd, 1234665 r/Always helpful tag/friend tag/colleague` * *Edit Person* : `editperson ed/PERSON_NAME [n/NAME] [p/PHONE] [em/EMAIL] [a/ADDRESS] [r/REMARK] [tag/TAG]...` + e.g. `editperson ed/James Lee em/jameslee@example.com` * *Delete Person* : `deleteperson n/NAME` + e.g. `deleteperson n/Benedict` * *Show Person* : `show n/NAME` + e.g. `show n/James Jake` *Schedule Management* * *Add Module to Person's Schedule* : `addmod n/NAME m/MODULE_CODE class/CLASS_NUMBERS(comma-separated) [ay/ACADEMIC_YEAR] [s/SEMESTER]` + e.g. `addmod n/John m/CS2103T class/G01,T5 ay/2019/2020 s/1` * *Add Modules to Person's Schedule via NUSMods Link* : `addmods n/NAME l/NUSMODS_SHARE_LINK` + e.g. `addmods n/John l/https://nusmods.com/timetable/sem-1/share?CS2101=&CS2103T=LEC:G05&CS3230=LEC:1,TUT:08&CS3243=TUT:07,LEC:1&GEQ1000=TUT:D17` * *Show Module Classes Schedule* : `showmod m/MODULE_CODE [ay/ACADEMIC_YEAR] [s/SEMESTER]` + e.g. `showmod m/CS3230 ay/2019/2020 s/2` * *Add Event to Person's Schedule* : `addevent n/NAME e/EVENT_NAME t/DATETIME...` + e.g. `addevent n/John e/Math Lecture t/26092019-1300-1400` * *Delete Event* : `deleteevent [n/NAME] e/EVENT_NAME` + e.g. `deleteevent n/Bobby e/CS2105` * *Generate Schedule* : `schedule n/NAME...` + e.g. `schedule n/Bobby n/Charlie` *Group Management* * *Add Group* `addgroup g/GROUP_NAME [d/GROUP_DESCRIPTION] [role/USER_ROLE]` + e.g. `addgroup g/CS2103 d/A CS2103 project group role/Leader` * *Add Person to Group* : `addtogroup n/PERSON_NAME g/GROUP_NAME [role/ROLE]` + e.g. `addtogroup n/Denise g/CS3203 role/Manager` * *Edit Group* `editgroup ed/GROUP [g/GROUP_NAME] [d/GROUP_DESCRIPTION] [role/USER_ROLE]` + e.g. `editgroup ed/CS2103 g/CS3203 d/A CS3203 project group role/Member` * *Delete Group* : `deletegroup g/GROUP_NAME` + e.g. `deletegroup g/CS2103` * *Show Group Details and Schedule* : `show g/GROUP_NAME` + e.g. `show g/CS2030` *Advanced Features* * *Export Visual Representation* : `export-vr [n/NAME]… [g/GROUP_NAME]… o/SAVE_LOCATION` + e.g. `export-vr g/TimeBook o/timetable.jpg` * *Select Time slot* : `select n/NAME [week/WEEK_NUMBER] i/ID` + e.g. `select n/Bobby i/1` * *Closest Location* : `closestlocation l/LOCATIONA LOCATIONB ...` + e.g. `closestlocation l/LT16 LT15 AS5` * *Select Free Time Slot* : `selectfreetime [week/WEEK_NUMBER] i/FREETIMESLOTID` + e.g. `selectfreetime i/1` [[Supported-Locations]] == Supported Locations !=== 10+|Valid Locations| |AS4-0116|AS3-0214|AS3-0213|AS3-0303|AS3-0212|AS3-0302|AS1-0303|AS1-0302|AS5-0309|LT9 AS1-0304|AS6-0214|AS5-0205|AS2-0413|AS3-0215|LT12|AS7-0119|AS4-0118|LT11|AS1-0209| AS4-0109|LT14|AS6-0212|AS1-0203|AS1-0208|AS4-0601|AS5-0202|AS4-0206|AS7-0102|AS8-0402| UTSRC-SR5|UTSRC-SR2|UT-AUD1|ERC-SR9CAM|ERC-SR8|ERC-GLR|AS3-0306|ERC-SR10|UTSRC-SR3|TP-SR1| UTSRC-GLR|UTSRC-SR6|UTSRC-SR7|TP-GLR|AS6-0333|AS1-0211|AS6-0338|AS4-0119|AS1-0205|AS7-0106| AS3-0309|AS4-0604|AS1-0301|AS1-0213|AS4-0335|TP-SR8|UTSRC-LT51|AS8-0401|AS6-0215B|AS1-0207| AS7-0101|LT10|AS1-0201|NAK-AUD|ERC-SR11|UTSRC-SR1|UTSRC-LT52|AS4-0603|ERC-ALR|UTSRC-SR9| UTSRC-SR4|LT8|S16-0435|S16-0437|LT7A|LT28|E3-06-02|E3-06-03|S16-0304|AS2-0510| UTSRC-SR8|AS2-0509|AS3-0304|AS4-0117|AS2-0312|AS7-0117|AS8-0405|AS2-0311|AS5-0203|LT13| AS3-0308|AS2-0316|AS2-0313|AS2-0203|AS2-0204|AS2-ELAB|AS2-0302|AS1-0524|AS3-0307|AS4-0602| AS8-0646|AS1-0204|AS3-0305|AS3-0523|TP-SR2|AS7-0201|AS4-0208|CHPC|AS7-0201A|AS4-B107| AS4-B109|AS4-B110|AS1-0212|AS4-0115|AS1-0210|AS8-0647|AS3-0209|AS4-0519|AS4-0318|BIZ1-0301| BIZ1-0303|BIZ1-0302|BIZ1-0307|BIZ1-0202|BIZ1-0204|BIZ1-CMRI|BIZ1-0305|BIZ1-0205|BIZ1-0201|BIZ1-0304| BIZ1-0203|BIZ2-0413A|HSSMLCR|BIZ2-0509|BIZ1-SR6-1|BIZ2-0510|BIZ2-0413C|BIZ1-0206|BIZ2-B104|BIZ2-0301| BIZ2-0118|BIZ2-0114|LT17|LT16|BIZ2-0202|BIZ2-0224|BIZ2-0404|BIZ2-0420|BIZ2-0228|BIZ2-0117| BIZ1-SR6-4|LT19|LT18|BIZ2-0226|BIZ2-0227|BIZ2-0302|BIZ2-0413B|BIZ2-0303|BIZ2-0201|BIZ2-0229| I3-AUD|COM1-VCRM|SR_LT19|COM1-0206|LT15|COM1-0204|COM1-0201|COM1-0210|COM1-B103|COM1-0114| COM1-0208|COM2-0108|I3-0336|I3-0338|I3-0344|COM1-B112|COM1-0113|I3-0339|COM1-B108|COM1-B111| COM1-B110|AS6-0421|LT7|COM1-0209|UT-AUD2|AS6-0211|COM1-0203|COM1-0207|COM1-0212|COM1-B113| COM1-B102|COM1-0216|COM1-0217|AS6-0210|AS6-0208|AS3-0611|AS3-0610|COM1-0120|AS3-0620|S16-0436| LT26|COM1-B109|RMI-SR1|I3-0337|SDE2-ER1|SDE-ER5|UTSRC-LT53|UTSRC-LT50|SDE1-ISD-1|LAW_SR3| NHM-1M-03|UT-AUD3|AKIMAUD|UT22-07-02|SDE4-GISL1|SDE-ER4|SDE2-MEZZ|AKI5B|SDE2-ES1|SDE2-ES2| AKIMLA4|TP-SR3|WT-Lab|GBT-Lab|SDE-EXR-2|SDE4-EXR1-2|SDE4-EXR-2|SDE4-EXR-1|E2-03-02|E1-06-02| E1-06-06|E1-06-13|E5-03-22|E3-06-04|E5-03-21|E3-06-11|E3-06-01|E4-04-04|ENG-AUD|E2A-03-01| E2A-02-02|E2A-02-01|E2A-03-02|E2A-04-02|E2A-04-03|E3-06-08|E1-06-10|E3-06-12|E3-06-10|E3-06-13| E5-03-23|E1-06-16|E3-06-14|E1-06-15|E1-06-11|E1-06-12|E4-04-02|E2-0308PC5|E2-0309PC6|LT2| E4-02-06|EA-06-04|EA-02-11|EA-06-02|EA-06-05|EA-06-03|LT6|E3-06-05|E1-06-08|E5-03-20| E1-06-01|LT4|E1-06-07|E1-06-04|E1-06-05|E1-06-09|EW2-04-02|E1-06-03|E5-03-19|E3-06-07| E2-0307PC4|LT3|E5-03-24|E2-0306PC3|E3-06-09|LT1|E4-03-07|E4A-06-03|E3-06-15|E4-02-01| E4-04-03|E3-05-21|E3-03-01|EA-06-06|E1-0410PC2|E3A-05-03|E3A-05-04|E3A-05-07|E5-02-32|EA-04-21| EA-06-07|EA-04-22|EA-04-07|EA-04-06|E3-04-02E|E3-04-02L|E1A-01-06|EA-02-21|EA-04-04|E1-06-0506| E5-0320-21|E3-06-06|EW1-03-02|EW1-02-03|EW1-04-02|EW1-01-01|EW2-03-14|EW1-1M-03|EW1-1M-02|LAW_SR5-3| LAW_SR5-4|LAW_SR4-1|LAW_SR5-2|FED-01-02|LAW_SR5-1|LAW_ESR|LAW_SR4-2|LAW_SR4-3|LAW_SR5-5|LAW_CR3-5| TB-08-01R|LAW_SR4-4|LAW_CR3-4|LAW_LT|LAW_CR4-2|LAW_CR5|LAW_CR3-6|LAW_CR4-1|LAW_CR2-1|LAW_CR3-3| LAW_CR2-2|LAW_CR3-7|LT33|MD10-01-01|LT34|S14-0619|S16-0430|S16-0307|LT29|MD7_LAB8| LT20|MD7-02-03|MD4-02-03E|MD4_LAB9|S14-0620|MD1-03-01B|MD1-07-01A|LT21|LT32|S1A-0217| MD9-01-02|CELS-04-01|LT28-01-01|YSTCM-TR|YSTCM-RS|YSTCM-SR2|YSTCM-SR8|YSTCM-WS|YSTCM-OH|YSTCM-ER3| YSTCM-HALL|YSTCM-MLAB|YSTCM-SR4|YSTCM-SR7|YSTCM-ER2|YSTCM-ER6|YSTCM-ER1|YSTCM-SR1|YSTCM-SR5|YSTCM-RECS| YSTCM-SR3|YSTCM-SR6|YSTCM-ER4|S16-03-0506|S16-0598|S16-0309|S2-0414|S2-0415|S2-04LAB5|S1A-03LAB1| S1A-04LAB3|S2-03LAB7|S13-M-08|S13-M-09|S1A-03LAB2|LT31|S1A-04LAB4|S16-0431|S8-0314|S5-01PHYS| S5-0224|S5-0410|S8-0402|S7-0401|S14-0503|S5-01GEN|S17-0406|S17-0405|S17-0512|S17-0511| S17-0404|S17-0611|S17-0304|S17-0302|MD1-06-03M|MD1-05-01A|MD1-06-01A|S4-02LAB|MD1-05-03K|S16-0440| S4-04LAB|S12-0403|S11-0204|S11-0301|S12-0402A|S12-0402B|S12-0402C|S12-0402D|S11-0302A|S12-0401| S11-0401A|S13-0313|S12-0402|E4-07-08|S11-0302|S16-06118|S16-05102|S16-05101|LKY_SR3-5|LKY_SR3-1| LKY_SR2-1|LKY_EA_M|LKY_SR2-2|LKY_SR2-3|LKY_SR3-4|LKY_TB10SR|LKY_EE_CSU|LKY_SR3-3|CELS-01-08|CQT/SR0315| USP-TR1|USP-SR1|USP-SR2|USP-SR3|USP-TR2|UTSRC-PR1|TC-TR2|TC-SR6|TC-SR3|TC-SR4| TC-SR5|CAPT-SR5|CAPT-SR1-2|CAPT-SR3|CAPT-SR6|RC4-SR1-2|RC4-SR3|RC4-SR5|RC4-SR4|RVR_MPR1| RVR_MPR2|RVR-SRM04|RVR-SRM03|RVR-SRM02|RVR-SRM01|MD1-08-01E|MD1-0801AB|MD1-0903EF|MD1-09-01A|MD1-09-01B| MD1-08-03E|MD1-08-01B|Y-CR21|Y-CR19|Y-CR9|Y-GLRm1|Y-PracRm6|Y-CR13|Y-CR18|Y-CR22| Y-CR17|Y-KChanrai|Y-CR6|Y-LT1|Y-TCTLT|Y-CR8|Y-CR20|Y-CR2|Y-CR12|Y-CR5| Y-CR14|Y-CR4|Y-CR15|Y-GLRm2|Y-CR3|Y-PgRm1|Y-CR7|Y-ArtsStud|Y-PgRm2|Y-CompLab| Y-CR11|Y-PerfHall|Y-AChemLab|Y-OChemLab|Y-CR1|Y-CR23|Y-CR16|E3-0605-06|E2-03-03|E4A-04-08| E1-06-14|CELC-SR1A|CELC-TR6|BIZ2-0115|BIZ2-0116|BIZ2-0112|CAPT-SR4|RC4-SR6|TH-SR1|KEVII-MR2| RH-CONF-RM|KRH-SR3|SH-SR1|AS3-0314|AS3-0312|AS3-0208|AS3-0316|ISS/3-12|ISS/2-9|ISS/4-6| ISS/3-3|ISS/2-1|ISS/AUD|ISS/3-1|ISS/3-5|ISS/4-4|TP-SR7|TP-SR4|TP-SR5|TP-SR6| !=== ",16144,True,2610.0325053336787,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc //// = Qute Reference Guide include::./attributes.adoc[] :numbered: :sectnums: :sectnumlevels: 4 :toc: Qute is a templating engine designed specifically to meet the Quarkus needs. The usage of reflection is minimized to reduce the size of native images. The API combines both the imperative and the non-blocking reactive style of coding. In the development mode, all files located in the `src/main/resources/templates` folder are watched for changes and modifications are immediately visible in your application. Furthermore, Qute attempts to detect most of the template problems at build time and fail fast. In this guide, you will find an <>, the description of the <> and <> details. NOTE: Qute is primarily designed as a Quarkus extension. It is possible to use it as a ""standalone"" library too. However, in such case some of the features are not available. In general, any feature mentioned under the <> section is missing. You can find more information about the limitations and possibilities in the <> section. [[hello_world_example]] == Hello World Example In this example, we'd like to demonstrate the basic workflow when working with Qute templates. Let's start with a simple hello world example. We will always need some *template contents*: .hello.html [source,html] ----

    Hello {name}! <1> ---- <1> `{name}` is a value expression that is evaluated when the template is rendered. Then, we will need to parse the contents into a *template definition* Java object. A template definition is an instance of `io.quarkus.qute.Template`. If using Qute ""standalone"" you'll need to create an instance of `io.quarkus.qute.Engine` first. The `Engine` represents a central point for template management with dedicated configuration. Let's use the convenient builder: [source,java] ---- Engine engine = Engine.builder().addDefaults().build(); ---- TIP: In Quarkus, there is a preconfigured `Engine` available for injection - see <>. Once we have an `Engine` instance we could parse the template contents: [source,java] ---- Template helloTemplate = engine.parse(helloHtmlContent); ---- TIP: In Quarkus, you can simply inject the template definition. The template is automatically parsed and cached - see <>. Finally, we will create a *template instance*, set the data and render the output: [source,java] ---- // Renders

    Hello Jim!

    helloTemplate.data(""name"", ""Jim"").render(); <1> <2> ---- <1> `Template.data(String, Object)` is a convenient method that creates a template instance and sets the data in one step. <2> `TemplateInstance.render()` triggers a synchronous rendering, i.e. the current thread is blocked until the rendering is finished. However, there are also asynchronous ways to trigger the rendering and consume the results. For example there is the `TemplateInstance.renderAsync()` method that returns `CompletionStage` or `TemplateInstance.createMulti()` that returns Mutiny's `Multi`. So the workflow is simple: 1. Create template contents (`hello.html`), 2. Parse template definition (`io.quarkus.qute.Template`), 3. Create template instance (`io.quarkus.qute.TemplateInstance`), 4. Render output. TIP: The `Engine` is able to cache the definitions so that it's not necessary to parse the contents again and again. In Quarkus, the caching is done automatically. [[core_features]] == Core Features === Basic Building Blocks The dynamic parts of a template include comments, expressions, sections and unparsed character data. ==== Comments A comment starts with `{!` and ends with `!}`, e.g. `{! This is a comment !}`. It could be multi-line and may contain expressions and sections: `{! {#if true} !}`. Of course, the content of a comment is completely ignored. [[blocks_expressions]] ==== Expressions An <> outputs an evaluated value. It consists of one or more parts. A part may represent simple properties: `{foo}`, `{item.name}` or virtual methods: `{item.get(name)}`, `{name ?: 'John'}`. An expression may start with a namespace: `{inject:colors}`. [[blocks_sections]] ==== Sections A <> may contain text, expressions and nested sections: `{#if foo}{foo.name}{/if}`. The name in the closing tag is optional: `{#if active}ACTIVE!{/}`. It can be empty: `{#myTag image=true /}`. A section may declare nested section blocks: `{#if item.valid} Valid. {#else} Invalid. {/if}` and decide which block to render. ==== Unparsed Character Data It is used to mark the content that should be rendered but not parsed. It starts with `{|` and ends with `|}`: `{| |}`, and could be multi-line. NOTE: Previously, unparsed character data had to start with `{[` and end with `]}`. This syntax is still supported but we encourage users to switch to the new syntax to avoid some common collisions with constructs from other languages. [[identifiers]] === Identifiers and Tags Identifiers are used in expressions and section tags. A valid identifier is a sequence of non-whitespace characters. However, users are encouraged to only use valid Java identifiers in expressions. TIP: You can use bracket notation if you need to specify an identifier that contains a dot, e.g. `{map['my.key']}`. When parsing a template document the parser identifies all _tags_. A tag starts and ends with a curly bracket, e.g. `{foo}`. The content of a tag must start with: * a digit, or * an alphabet character, or * underscore, or * a built-in command: `#`, `!`, `@`, `/`. If it does not start with any of the above it is ignored by the parser. .Tag Examples [source,html] ---- {_foo.bar} <1> {! comment !}<2> { foo} <3> {{foo}} <4> {""foo"":true} <5> ---- <1> Parsed: an expression that starts with underscore. <2> Parsed: a comment <3> Ignored: starts with whitespace. <4> Ignored: starts with `{`. <5> Ignored: starts with `""`. TIP: It is also possible to use escape sequences `\\{` and `\\}` to insert delimiters in the text. In fact, an escape sequence is usually only needed for the start delimiter, ie. `\\\\{foo}` will be rendered as `{foo}` (no parsing/evaluation will happen). === Removing Standalone Lines From the Template By default, the parser removes standalone lines from the template output. A *standalone line* is a line that contains at least one section tag (e.g. `{#each}` and `{/each}`), parameter declaration (e.g. `{@org.acme.Foo foo}`) or comment but no expression and no non-whitespace character. In other words, a line that contains no section tag or a parameter declaration is *not* a standalone line. Likewise, a line that contains an _expression_ or a _non-whitespace character_ is *not* a standalone line. .Template Example [source,html] ----
      {#for item in items} <1>
    • {item.name} {#if item.active}{item.price}{/if}
    • <2> <3> {/for} <4>
    ---- <1> This is a standalone line and will be removed. <2> Not a standalone line - contains an expression and non-whitespace characters <3> Not a standalone line - contains no section tag/parameter declaration <4> This is a standalone line. .Default Output [source,html] ----
    • Foo 100
    ---- TIP: In Quarkus, the default behavior can be disabled by setting the property `quarkus.qute.remove-standalone-lines` to `false`. In this case, all whitespace characters from a standalone line will be printed to the output. .Output with `quarkus.qute.remove-standalone-lines=false` [source,html] ----
    • Foo 100
    ---- [[expressions]] === Expressions An expression outputs a value. It consists of one or more parts separated by dot (dot notation) or square brackets (bracket notation). In the `object.property` (dot notation) syntax, the `property` must be a <>. In the `object[property_name]` (bracket notation) syntax, the `property_name` has to be a non-null <> value. An expression could start with an optional namespace followed by a colon (`:`). A valid namespace consist of alphanumeric characters and underscores. .Expressions Example [source] ---- {name} <1> {item.name} <2> {item['name']} <3> {global:colors} <4> ---- <1> no namespace, one part: `name` <2> no namespace, two parts: `item`, `name` <3> equivalent to `{item.name}` but using the bracket notation <4> namespace `global`, one part: `colors` A part of an expression could be a _virtual method_ in which case the name can be followed by a list of comma-separated parameters in parentheses. A parameter of a virtual method can be either a nested expression or a <> value. We call it ""virtual"" because it does not have to be backed by a real Java method. .Virtual Methods Example [source] ---- {item.getLabels(1)} <1> {name or 'John'} <2> ---- <1> no namespace, two parts - `item`, `getLabels(1)`, the second part is a virtual method with name `getLabels` and params `1` <2> infix notation that can be used for virtual methods with single parameter, translated to `name.or('John')`; no namespace, two parts - `name`, `or('John')` [[literals]] ==== Supported Literals |=== |Literal |Examples |boolean |`true`, `false` |null |`null` |string |`'value'`, `""string""` |integer |`1`, `-5` |long |`1l`, `-5L` |double |`1D`, `-5d` |float |`1f`, `-5F` |=== ==== Resolution The first part of the expression is always resolved against the <>. If no result is found for the first part it's resolved against the parent context object (if available). For an expression that starts with a namespace the current context object is found using all the available ``NamespaceResolver``s. For an expression that does not start with a namespace the current context object is *derived from the position* of the tag. All other parts of an expression are resolved using all ``ValueResolver``s against the result of the previous resolution. For example, expression `{name}` has no namespace and single part - `name`. The ""name"" will be resolved using all available value resolvers against the current context object. However, the expression `{global:colors}` has the namespace `global` and single part - `colors`. First, all available ``NamespaceResolver``s will be used to find the current context object. And afterwards value resolvers will be used to resolve ""colors"" against the context object found. [TIP] ==== Data passed to the template instance are always accessible using the `data` namespace. This could be useful to access data for which the key is overridden: [source,html] ---- {item.name} <1>
      {#for item in item.getDerivedItems()} <2>
    • {item.name} <3> is derived from {data:item.name} <4>
    • {/for}
    ---- <1> `item` is passed to the template instance as a data object. <2> Iterate over the list of derived items. <3> `item` is an alias for the iterated element. <4> Use the `data` namespace to access the `item` data object. ==== [[current_context_object]] ==== Current Context If an expression does not specify a namespace the _current context object_ is derived from the position of the tag. By default, the current context object represents the data passed to the template instance. However, sections may change the current context object. A typical example is the `with` section that could be used to set the current context object in order to simplify the template structure: [source,html] ---- {#with item}

    {name}

    <1>

    {description}

    {/with} ---- <1> `name` is resolved against the `item`. Another built-in section that modifies the current context object is `let`/`set`: [source,html] ---- {#let myParent=order.item.parent myPrice=order.price} <1>

    {myParent.name}

    Price: {myPrice}

    {/let} ---- <1> The current context object inside the section is the map of resolved parameters. NOTE: The current context can be accessed via the implicit binding `this`. ==== Built-in Resolvers |=== |Name |Description |Examples |Elvis Operator |Outputs the default value if the previous part cannot be resolved or resolves to `null`. |`{person.name ?: 'John'}`, `{person.name or 'John'}`, `{person.name.or('John')}` |orEmpty |Outputs an empty list if the previous part cannot be resolved or resolves to `null`. |`{#for pet in pets.orEmpty}{pet.name}{/for}` |Ternary Operator |Shorthand for if-then-else statement. Unlike in <> nested operators are not supported. |`{item.isActive ? item.name : 'Inactive item'}` outputs the value of `item.name` if `item.isActive` resolves to `true`. |Logical AND Operator |Outputs `true` if both parts are not `falsy` as described in the <>. The parameter is only evaluated if needed. |`{person.isActive && person.hasStyle}` |Logical OR Operator |Outputs `true` if any of the parts is not `falsy` as described in the <>. The parameter is only evaluated if needed. |`{person.isActive \\|\\| person.hasStyle}` |=== TIP: The condition in a ternary operator evaluates to `true` if the value is not considered `falsy` as described in the <>. NOTE: In fact, the operators are implemented as ""virtual methods"" that consume one parameter and can be used with infix notation. For example `{person.name or 'John'}` is translated to `{person.name.or('John')}` and `{item.isActive ? item.name : 'Inactive item'}` is translated to `{item.isActive.ifTruthy(item.name).or('Inactive item')}` ==== Arrays You can iterate over elements of an array with the <>. Moreover, it's also possible to get the length of the specified array and access the elements directly via an index value. Additionaly, you can access the first/last `n` elements via the `take(n)/takeLast(n)` methods. .Array Examples [source,html] ----

    Array of length: {myArray.length}

    <1>
    • First: {myArray.0}
    • <2>
    • Second: {myArray[1]}
    • <3>
    • Third: {myArray.get(2)}
    • <4>
      {#for element in myArray}
    1. {element}
    2. {/for}
    First two elements: {#each myArray.take(2)}{it}{/each} <5> ---- <1> Outputs the length of the array. <2> Outputs the first element of the array. <3> Outputs the second element of the array using the bracket notation. <4> Outputs the third element of the array via the virtual method `get()`. <5> Outputs the first two elements of the array. ==== Character Escapes For HTML and XML templates the `'`, `""`, `<`, `>`, `&` characters are escaped by default if a template variant is set. NOTE: In Quarkus, a variant is set automatically for templates located in the `src/main/resources/templates`. By default, the `java.net.URLConnection#getFileNameMap()` is used to determine the content type of a template file. The additional map of suffixes to content types can be set via `quarkus.qute.content-types`. If you need to render the unescaped value: 1. Either use the `raw` or `safe` properties implemented as extension methods of the `java.lang.Object`, 2. Or wrap the `String` value in a `io.quarkus.qute.RawString`. [source,html] ----

    {title}

    <1> {paragraph.raw} <2> ---- <1> `title` that resolves to `Expressions & Escapes` will be rendered as `Expressions &amp; Escapes` <2> `paragraph` that resolves to `

    My text!

    ` will be rendered as `

    My text!

    ` ==== Virtual Methods A virtual method is a *part of an expression* that looks like a regular Java method invocation. It's called ""virtual"" because it does not have to match the actual method of a Java class. In fact, like normal properties a virtual method is also handled by a value resolver. The only difference is that for virtual methods a value resolver consumes parameters that are also expressions. .Virtual Method Example [source,html] ----

    {item.buildName(item.name,5)}

    <1> ---- <1> `buildName(item.name,5)` represents a virtual method with name `buildName` and two parameters: `item.name` and `5` . The virtual method could be evaluated by a value resolver generated for the following Java class: + [source,java] ---- class Item { String buildName(String name, int age) { return name + "":"" + age; } } ---- NOTE: Virtual methods are usually evaluated by value resolvers generated for <>, <> or classes used in <>. However, a custom value resolver that is not backed by any Java class/method can be registered as well. A virtual method with single parameter can be called using the infix notation: .Infix Notation Example [source,html] ----

    {item.price or 5}

    <1> ---- <1> `item.price or 5` is translated to `item.price.or(5)`. Virtual method parameters can be ""nested"" virtual method invocations. .Nested Virtual Method Example [source,html] ----

    {item.subtractPrice(item.calculateDiscount(10))}

    <1> ---- <1> `item.calculateDiscount(10)` is evaluated first and then passed as an argument to `item.subtractPrice()`. ==== Evaluation of `CompletionStage` and `Uni` Objects Objects that implement `java.util.concurrent.CompletionStage` and `io.smallrye.mutiny.Uni` are evaluated in a special way. If a part of an expression resolves to a `CompletionStage`, the resolution continues once this stage is completed and the next part of the expression (if any) is evaluated against the result of the completed stage. For example, if there is an expression `{foo.size}` and `foo` resolves to `CompletionStage>` then `size` is resolved against the completed result, i.e. `List`. If a part of an expression resolves to a `Uni`, a `CompletionStage` is first created from `Uni` using `Uni#subscribeAsCompletionStage()` and then evaluated as described above. ==== Missing Properties It can happen that an expression may not be evaluated at runtime. For example, if there is an expression `{person.age}` and there is no property `age` declared on the `Person` class. Qute outputs the special constant `NOT_FOUND` in this case by default. However, it's possible to change the default strategy via the `quarkus.qute.property-not-found-strategy` as described in the <>. NOTE: Similar errors are detected at build time if <> and <> are used. TIP: Alternatively, the _elvis operator_ can be used to output the default value in case the property cannot be resolved or resolves to `null`: `{person.age ?: 10}` would output `10`. And for the loop section, the `orEmpty` resolver can be used. See also <>. [[sections]] === Sections A section: * has a start tag ** starts with `#`, followed by the name of the section such as `{#if}` and `{#each}`, * may be empty ** tag ends with `/`, ie. `{#emptySection /}` * may contain other expression, sections, etc. ** the end tag starts with `/` and contains the name of the section (optional): `{#if foo}Foo!{/if}` or `{#if foo}Foo!{/}`, The start tag can also define parameters. The parameters have optional names. A section may contain several content *blocks*. The ""main"" block is always present. Additional/nested blocks also start with `#` and can have parameters too - `{#else if item.isActive}`. A section helper that defines the logic of a section can ""execute"" any of the blocks and evaluate the parameters. [source] ---- {#if item.name is 'sword'} It's a sword! {#else if item.name is 'shield'} It's a shield! {#else} Item is neither a sword nor a shield. {/if} ---- [[loop_section]] ==== Loop Section The loop section makes it possible to iterate over an instance of `Iterable`, `Iterator`, array, `Map` 's entry set, `Stream` and an `Integer`. It has two flavors. The first one is using the `each` name and `it` is an implicit alias for the iteration element. [source] ---- {#each items} {it.name} <1> {/each} ---- <1> `name` is resolved against the current iteration element. The other form is using the `for` name and can specify the alias used to reference the iteration element: [source] ---- {#for item in items} {item.name} {/for} ---- It's also possible to access the iteration metadata inside the loop: [source] ---- {#each items} {count}. {it.name} <1> {/each} ---- <1> `count` represents one-based index. TIP: The iteration metadata also include zero-based `index`, `hasNext`, `odd` and `even` properties. The `for` statement also works with integers, starting from 1. In the example below, considering that `total = 3`: [source] ---- {#for i in total} {i}: {/for} ---- And the output will be: [source] ---- 1:2:3: ---- A loop section may define the `{#else}` block that is executed when there are no items to iterate: [source] ---- {#for item in items} {item.name} {#else} No items. {/for} ---- [[if_section]] ==== If Section The `if` section represents a basic control flow section. The simplest possible version accepts a single parameter and renders the content if the condition is evaluated to `true`. A condition without an operator evaluates to `true` if the value is not considered `falsy`, i.e. if the value is not `null`, `false`, an empty collection, an empty map, an empty array, an empty string/char sequence or a number equal to zero. [source] ---- {#if item.active} This item is active. {/if} ---- You can also use the following operators in a condition: |=== |Operator |Aliases |Precedence (higher wins) |logical complement |`!` | 4 |greater than |`gt`, `>` | 3 |greater than or equal to |`ge`, `>=` | 3 |less than |`lt`, `<` | 3 |less than or equal to |`le`, `\\<=` | 3 |equals |`eq`, `==`, `is` | 2 |not equals |`ne`, `!=` | 2 |logical AND (short-circuiting) |`&&`, `and` | 1 |logical OR (short-circuiting) |`\\|\\|`, `or` | 1 |=== .A simple operator example [source] ---- {#if item.age > 10} This item is very old. {/if} ---- Multiple conditions are also supported. .Multiple conditions example [source] ---- {#if item.age > 10 && item.price > 500} This item is very old and expensive. {/if} ---- Precedence rules can be overridden by parentheses. .Parentheses example [source] ---- {#if (item.age > 10 || item.price > 500) && user.loggedIn} User must be logged in and item age must be > 10 or price must be > 500. {/if} ---- You can also add any number of `else` blocks: [source] ---- {#if item.age > 10} This item is very old. {#else if item.age > 5} This item is quite old. {#else if item.age > 2} This item is old. {#else} This item is not old at all! {/if} ---- [[when_section]] ==== When/Switch Section This section is similar to Java's `switch` or Kotlin's `when` constructs. It matches a _tested value_ against all blocks sequentially until a condition is satisfied. The first matching block is executed. All other blocks are ignored (this behavior differs to the Java `switch` where a `break` statement is necessary). .Example using the `when`/`is` name aliases [source] ---- {#when items.size} {#is 1} <1> There is exactly one item! {#is > 10} <2> There are more than 10 items! {#else} <3> There are 2 -10 items! {/when} ---- <1> If there is exactly one parameter it's tested for equality. <2> It's possible to use <> to specify the matching logic. Unlike in the <> nested operators are not supported. <3> `else` is block is executed if no other block matches the value. .Example using the `switch`/`case` name aliases [source] ---- {#switch person.name} {#case 'John'} <1> Hey John! {#case 'Mary'} Hey Mary! {/switch} ---- <1> `case` is an alias for `is`. A tested value that resolves to an enum is handled specifically. The parameters of an `is`/`case` block are not evaluated as expressions but compared with the result of `toString()` invocation upon the tested value. [source] ---- {#when machine.status} {#is ON} It's running. <1> {#is in OFF BROKEN} It's broken or OFF. <2> {/when} ---- <1> This block is executed if `machine.status.toString().equals(""ON"")`. <2> This block is executed if `machine.status.toString().equals(""OFF"")` or `machine.status.toString().equals(""BROKEN"")`. NOTE: An enum constant is validated if the tested value has a type information available and resolves to an enum type. The following operators are supported in `is`/`case` block conditions: [[when_operators]] |=== |Operator |Aliases |Example |not equal |`!=`, `not`, `ne` |`{#is not 10}`,`{#case != 10}` |greater than |`gt`, `>` |`{#case le 10}` |greater than or equal to |`ge`, `>=` |`{#is >= 10}` |less than |`lt`, `<` |`{#is < 10}` |less than or equal to |`le`, `\\<=` |`{#case le 10}` |in |`in` |`{#is in 'foo' 'bar' 'baz'}` |not in |`ni`,`!in` |`{#is !in 1 2 3}` |=== [[with_section]] ==== With Section This section can be used to set the current context object. This could be useful to simplify the template structure: [source,html] ---- {#with item.parent}

    {name}

    <1>

    {description}

    <2> {/with} ---- <1> The `name` will be resolved against the `item.parent`. <2> The `description` will be also resolved against the `item.parent`. This section might also come in handy when we'd like to avoid multiple expensive invocations: [source,html] ---- {#with item.callExpensiveLogicToGetTheValue(1,'foo',bazinga)} {#if this is ""fun""} <1>

    Yay!

    {#else}

    {this} is not fun at all!

    {/if} {/with} ---- <1> `this` is the result of `item.callExpensiveLogicToGetTheValue(1,'foo',bazinga)`. The method is only invoked once even though the result may be used in multiple expressions. ==== Let/Set Section This section allows you to define named local variables: [source,html] ---- {#let myParent=order.item.parent isActive=false age=10} <1>

    {myParent.name}

    Is active: {isActive} Age: {age} {/let} ---- <1> The local variable is initialized with an expression that can also represent a <>. The section tag is also registered under the `set` alias: [source,html] ---- {#set myParent=item.parent price=item.price}

    {myParent.name}

    Price: {price} {/set} ---- [[include_helper]] ==== Include Section This section can be used to include another template and possibly override some parts of the template (template inheritance). .Simple Example [source,html] ---- Simple Include {#include foo limit=10 /} <1><2> ---- <1> Include a template with id `foo`. The included template can reference data from the current context. <2> It's also possible to define optional parameters that can be used in the included template. Template inheritance makes it possible to reuse template layouts. .Template ""base"" [source,html] ---- {#insert title}Default Title{/} <1> {#insert}No body!{/} <2> ---- <1> `insert` sections are used to specify parts that could be overridden by a template that includes the given template. <2> An `insert` section may define the default content that is rendered if not overridden. If no name parameter is supplied then the main block of the relevant `{#include}` section is used. .Template ""detail"" [source,html] ---- {#include base} <1> {#title}My Title{/title} <2>

    <3> My body.
    {/include} ---- <1> `include` section is used to specify the extended template. <2> Nested blocks are used to specify the parts that should be overridden. <3> The content of the main block is used for an `{#insert}` section with no name parameter specified. NOTE: Section blocks can also define an optional end tag - `{/title}`. ==== Eval Section This section can be used to parse and evaluate a template dynamically. The behavior is very similar to the <> but: 1. The template content is passed directly, i.e. not obtained via an `io.quarkus.qute.TemplateLocator`, 2. It's not possible to override parts of the evaluated template. [source,html] ---- {#eval myData.template name='Mia' /} <1><2><3> ---- <1> The result of `myData.template` will be used as the template. The template is executed with the <>, i.e. can reference data from the template it's included into. <2> It's also possible to define optional parameters that can be used in the evaluated template. <3> The content of the section is always ignored. NOTE: The evaluated template is parsed and evaluated every time the section is executed. In other words, it's not possible to cache the parsed value to conserve resources and optimize the performance. [[user_tags]] ==== User-defined Tags User-defined tags can be used to include a template and optionally pass some parameters. Let's suppose we have a template called `itemDetail.html`: [source] ---- {#if showImage} <1> {it.image} <2> {nested-content} <3> {/if} ---- <1> `showImage` is a named parameter. <2> `it` is a special key that is replaced with the first unnamed param of the tag. <3> (optional) `nested-content` is a special key that will be replaced by the content of the tag. Now if we register this template under the name `itemDetail.html` and if we add a `UserTagSectionHelper` to the engine: [source,java] ---- Engine engine = Engine.builder() .addSectionHelper(new UserTagSectionHelper.Factory(""itemDetail"",""itemDetail.html"")) .build(); ---- NOTE: In Quarkus, all files from the `src/main/resources/templates/tags` are registered and monitored automatically! We can include the tag like this: [source,html] ----
      {#for item in items}
    • {#itemDetail item showImage=true} <1> = {item.name} <2> {/itemDetail}
    • {/for}
    ---- <1> `item` is resolved to an iteration element and can be referenced using the `it` key in the tag template. <2> Tag content injected using the `nested-content` key in the tag template. === Rendering Output `TemplateInstance` provides several ways to trigger the rendering and consume the result. The most straightforward approach is represented by `TemplateInstance.render()`. This method triggers a synchronous rendering, i.e. the current thread is blocked until the rendering is finished, and returns the output. By contrast, `TemplateInstance.renderAsync()` returns a `CompletionStage` which is completed when the rendering is finished. .`TemplateInstance.renderAsync()` Example [source,java] ---- template.data(foo).renderAsync().whenComplete((result, failure) -> { <1> if (failure == null) { // consume the output... } else { // process failure... } }; ---- <1> Register a callback that is executed once the rendering is finished. There are also two methods that return https://smallrye.io/smallrye-mutiny/[Mutiny] types. `TemplateInstance.createUni()` returns a new `Uni` object. If you call `createUni()` the template is not rendered right away. Instead, every time `Uni.subscribe()` is called a new rendering of the template is triggered. .`TemplateInstance.createUni()` Example [source,java] ---- template.data(foo).createUni().subscribe().with(System.out::println); ---- `TemplateInstance.createMulti()` returns a new `Multi` object. Each item represents a part/chunk of the rendered template. Again, `createMulti()` does not trigger rendering. Instead, every time a computation is triggered by a subscriber the template is rendered again. .`TemplateInstance.createMulti()` Example [source,java] ---- template.data(foo).createMulti().subscribe().with(buffer:append,buffer::flush); ---- NOTE: The template rendering is divided in two phases. During the first phase, which is asynchronous, all expressions in the template are resolved and a _result tree_ is built. In the second phase, which is synchronous, the result tree is _materialized_, i.e. one by one the result nodes emit chunks that are consumed/buffered by the specific consumer. === Engine Configuration [[value-resolvers]] ==== Value Resolvers Value resolvers are used when evaluating expressions. A custom `io.quarkus.qute.ValueResolver` can be registered programmatically via `EngineBuilder.addValueResolver()`. .`ValueResolver` Builder Example [source,java] ---- engineBuilder.addValueResolver(ValueResolver.builder() .appliesTo(ctx -> ctx.getBase() instanceof Long && ctx.getName().equals(""tenTimes"")) .resolveSync(ctx -> (Long) ctx.getBase() * 10) .build()); ---- [[template-locator]] ==== Template Locator Manual registration is sometimes handy but it's also possible to register a template locator using `EngineBuilder.addLocator(Function>)`. This locator is used whenever the `Engine.getTemplate()` method is called and the engine has no template for a given id stored in the cache. NOTE: In Quarkus, all templates from the `src/main/resources/templates` are located automatically. ==== Content Filters Content filters can be used to modify the template contents before parsing. .Content Filter Example [source,java] ---- engineBuilder.addParserHook(new ParserHook() { @Override public void beforeParsing(ParserHelper parserHelper) { parserHelper.addContentFilter(contents -> contents.replace(""${"", ""$\\\\{"")); <1> } }); ---- <1> Escape all occurences of `${`. ==== Strict Rendering The strict rendering enables the developers to catch insidious errors caused by typos and invalid expressions. If enabled then any expression that cannot be resolved, i.e. is evaluated to an instance of `io.quarkus.qute.Results.NotFound`, will always result in a `TemplateException` and the rendering is aborted. A `NotFound` value is considered an error because it basically means that no value resolver was able to resolve the expression correctly. NOTE: `null` is a valid value though. It is considered `falsy` as described in the <> and does not produce any output. Strict rendering is enabled by default. However, you can disable this functionality via `io.quarkus.qute.EngineBuilder.strictRendering(boolean)`. TIP: In Quarkus, a dedicated config property can be used instead: `quarkus.qute.strict-rendering`. If you really need to use an expression which can potentially lead to a ""not found"" error, you can use _default values_ and _safe expressions_ in order to suppress the error. A default value is used if the previous part of an expression cannot be resolved or resolves to `null`. You can use the elvis operator to output the default value: `{foo.bar ?: 'baz'}`, which is effectively the same as the following virtual method: `{foo.bar.or('baz')}`. A safe expression ends with the `??` suffix and results in `null` if the expression cannot be resolved. It can be very useful e.g. in `{#if}` sections: `{#if valueNotFound??}Only rendered if valueNotFound is truthy!{/if}`. In fact, `??` is just a shorthand notation for `.or(null)`, i.e. `{#if valueNotFound??}` becomes `{#if valueNotFound.or(null)}`. [[quarkus_integration]] == Quarkus Integration If you want to use Qute in your Quarkus application add the following dependency to your project: [source,xml] ---- io.quarkus quarkus-qute ---- In Quarkus, a preconfigured engine instance is provided and available for injection - a bean with scope `@ApplicationScoped`, bean type `io.quarkus.qute.Engine` and qualifier `@Default` is registered automatically. Moreover, all templates located in the `src/main/resources/templates` directory are validated and can be easily injected. [source,java] ---- import io.quarkus.qute.Engine; import io.quarkus.qute.Template; import io.quarkus.qute.Location; class MyBean { @Inject Template items; <1> @Location(""detail/items2_v1.html"") <2> Template items2; @Inject Engine engine; <3> } ---- <1> If there is no `Location` qualifier provided, the field name is used to locate the template. In this particular case, the container will attempt to locate a template with path `src/main/resources/templates/items.html`. <2> The `Location` qualifier instructs the container to inject a template from a path relative from `src/main/resources/templates`. In this case, the full path is `src/main/resources/templates/detail/items2_v1.html`. <3> Inject the configured `Engine` instance. It's also possible to contribute to the engine configuration via a CDI observer method. .`EngineBuilder` Observer Example [source,java] ---- import io.quarkus.qute.EngineBuilder; class MyBean { void configureEngine(@Observes EngineBuilder builder) { builder.addValueResolver(ValueResolver.builder() .appliesTo(ctx -> ctx.getBase() instanceof Long && ctx.getName().equals(""tenTimes"")) .resolveSync(ctx -> (Long) ec.getBase() * 10) .build()); } } ---- === Template Variants Sometimes it's useful to render a specific variant of the template based on the content negotiation. This can be done by setting a special attribute via `TemplateInstance.setAttribute()`: [source,java] ---- class MyService { @Inject Template items; <1> @Inject ItemManager manager; String renderItems() { return items.data(""items"",manager.findItems()).setAttribute(TemplateInstance.SELECTED_VARIANT, new Variant(Locale.getDefault(),""text/html"",""UTF-8"")).render(); } } ---- NOTE: When using `quarkus-resteasy-qute` the content negotiation is performed automatically. See <>. === Injecting Beans Directly In Templates A CDI bean annotated with `@Named` can be referenced in any template through the `inject` namespace: [source,html] ---- {inject:foo.price} <1> ---- <1> First, a bean with name `foo` is found and then used as the base object. All expressions using the `inject` namespace are validated during build. For the expression `inject:foo.price` the implementation class of the injected bean must either have the `price` property (e.g. a `getPrice()` method) or a matching <> must exist. NOTE: A `ValueResolver` is also generated for all beans annotated with `@Named` so that it's possible to access its properties without reflection. TIP: If your application serves link:http-reference[HTTP requests] you can also inject the current `io.vertx.core.http.HttpServerRequest` via the `inject` namespace, e.g. `{inject:vertxRequest.getParam('foo')}`. [[typesafe_expressions]] === Type-safe Expressions Template expressions can be optionally type-safe. Which means that an expression is validated against the existing Java types and template extension methods. If an invalid/incorrect expression is found then the build fails. For example, if there is an expression `item.name` where `item` maps to `org.acme.Item` then `Item` must have a property `name` or a matching template extension method must exist. An optional _parameter declaration_ is used to bind a Java type to expressions whose first part matches the parameter name. Parameter declarations are specified directly in a template. .Parameter Declaration Example [source,html] ---- {@org.acme.Foo foo} <1> Qute Hello

    {title}

    <2> Hello {foo.message.toLowerCase}! <3> <4> ---- <1> Parameter declaration - maps `foo` to `org.acme.Foo`. <2> Not validated - not matching a param declaration. <3> This expression is validated. `org.acme.Foo` must have a property `message` or a matching template extension method must exist. <4> Likewise, the Java type of the object resolved from `foo.message` must have a property `toLowerCase` or a matching template extension method must exist. IMPORTANT: A value resolver is automatically generated for all types used in parameter declarations so that it's possible to access its properties without reflection. TIP: Method parameters of <> are automatically turned into parameter declarations. Note that sections can override names that would otherwise match a parameter declaration: [source,html] ---- {@org.acme.Foo foo} Qute Hello

    {foo.message}

    <1> {#for foo in baz.foos}

    Hello {foo.message}!

    <2> {/for} ---- <1> Validated against `org.acme.Foo`. <2> Not validated - `foo` is overridden in the loop section. [[typesafe_templates]] === Type-safe Templates You can also define type-safe templates in your Java code. If using <>, you can rely on the following convention: - Organise your template files in the `/src/main/resources/templates` directory, by grouping them into one directory per resource class. So, if your `ItemResource` class references two templates `hello` and `goodbye`, place them at `/src/main/resources/templates/ItemResource/hello.txt` and `/src/main/resources/templates/ItemResource/goodbye.txt`. Grouping templates per resource class makes it easier to navigate to them. - In each of your resource class, declare a `@CheckedTemplate static class Template {}` class within your resource class. - Declare one `public static native TemplateInstance method();` per template file for your resource. - Use those static methods to build your template instances. .ItemResource.java [source,java] ---- package org.acme.quarkus.sample; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import io.quarkus.qute.TemplateInstance; import io.quarkus.qute.Template; import io.quarkus.qute.CheckedTemplate; @Path(""item"") public class ItemResource { @CheckedTemplate public static class Templates { public static native TemplateInstance item(Item item); <1> <2> } @GET @Path(""{id}"") @Produces(MediaType.TEXT_HTML) public TemplateInstance get(@PathParam(""id"") Integer id) { return Templates.item(service.findItem(id)); <3> } } ---- <1> Declare a method that gives us a `TemplateInstance` for `templates/ItemResource/item.html` and declare its `Item item` parameter so we can validate the template. <2> The `item` parameter is automatically turned into a <> and so all expressions that reference this name will be validated. <3> Make the `Item` object accessible in the template. TIP: By default, the templates defined in a class annotated with `@CheckedTemplate` can only contain type-safe expressions, i.e. expressions that can be validated at build time. You can use `@CheckedTemplate(requireTypeSafeExpressions = false)` to relax this requirement. You can also declare a top-level Java class annotated with `@CheckedTemplate`: .Top-level checked templates [source,java] ---- package org.acme.quarkus.sample; import io.quarkus.qute.TemplateInstance; import io.quarkus.qute.Template; import io.quarkus.qute.CheckedTemplate; @CheckedTemplate public class Templates { public static native TemplateInstance hello(String name); <1> } ---- <1> This declares a template with path `templates/hello.txt`. The `name` parameter is automatically turned into a <> and so all expressions that reference this name will be validated. Then declare one `public static native TemplateInstance method();` per template file. Use those static methods to build your template instances: .HelloResource.java [source,java] ---- package org.acme.quarkus.sample; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import io.quarkus.qute.TemplateInstance; @Path(""hello"") public class HelloResource { @GET @Produces(MediaType.TEXT_PLAIN) public TemplateInstance get(@QueryParam(""name"") String name) { return Templates.hello(name); } } ---- [[template_extension_methods]] === Template Extension Methods Extension methods can be used to extend the data classes with new functionality (to extend the set of accessible properties and methods) or to resolve expressions for a specific <>. For example, it is possible to add _computed properties_ and _virtual methods_. A value resolver is automatically generated for a method annotated with `@TemplateExtension`. If a class is annotated with `@TemplateExtension` then a value resolver is generated for every _non-private static method_ declared on the class. Method-level annotations override the behavior defined on the class. Methods that do not meet the following requirements are ignored. A template extension method: * must not be `private` * must be static, * must not return `void`. If there is no namespace defined the class of the first parameter that is not annotated with `@TemplateAttribute` is used to match the base object. Otherwise the namespace is used to match an expression. The method name is used to match the property name by default. However, it is possible to specify the matching name with `TemplateExtension#matchName()`. A special constant - `TemplateExtension#ANY` - may be used to specify that the extension method matches any name. It is also possible to match the name against a regular expression specified in `TemplateExtension#matchRegex()`. In both cases, an additional string method parameter must be used to pass the property name. If both `matchName()` and `matchRegex()` are set the regular expression is used for matching. .Extension Method Example [source,java] ---- package org.acme; class Item { public final BigDecimal price; public Item(BigDecimal price) { this.price = price; } } @TemplateExtension class MyExtensions { static BigDecimal discountedPrice(Item item) { <1> return item.getPrice().multiply(new BigDecimal(""0.9"")); } } ---- <1> This method matches an expression with base object of the type `Item.class` and the `discountedPrice` property name. This template extension method makes it possible to render the following template: [source,html] ---- {item.discountedPrice} <1> ---- <1> `item` is resolved to an instance of `org.acme.Item`. ==== Method Parameters An extension method may declare parameters. If no namespace is specified then the first parameter that is not annotated with `@TemplateAttribute` is used to pass the base object, i.e. `org.acme.Item` in the first example. If matching any name or using a regular expression then a string method parameter needs to be used to pass the property name. Parameters annotated with `@TemplateAttribute` are obtained via `TemplateInstance#getAttribute()`. All other parameters are resolved when rendering the template and passed to the extension method. .Multiple Parameters Example [source,java] ---- @TemplateExtension class BigDecimalExtensions { static BigDecimal scale(BigDecimal val, int scale, RoundingMode mode) { <1> return val.setScale(scale, mode); } } ---- <1> This method matches an expression with base object of the type `BigDecimal.class`, with the `scale` virtual method name and two virtual method parameters. [source,html] ---- {item.discountedPrice.scale(2,mode)} <1> ---- <1> `item.discountedPrice` is resolved to an instance of `BigDecimal`. [[namespace_extension_methods]] ==== Namespace Extension Methods If `TemplateExtension#namespace()` is specified then the extension method is used to resolve expressions with the given <>. Template extension methods that share the same namespace are grouped in one resolver ordered by `TemplateExtension#priority()`. The first matching extension method is used to resolve an expression. .Namespace Extension Method Example [source,java] ---- @TemplateExtension(namespace = ""str"") public static class StringExtensions { static String format(String fmt, Object... args) { return String.format(fmt, args); } static String reverse(String val) { return new StringBuilder(val).reverse().toString(); } } ---- These extension methods can be used as follows. [source,html] ---- {str:format('%s %s!','Hello', 'world')} <1> {str:reverse('hello')} <2> ---- <1> The output is `Hello world!` <2> The output is `olleh` [[built-in-template-extension]] ==== Built-in Template Extensions Quarkus provides a set of built-in extension methods. ===== Maps * `keys` or `keySet`: Returns a Set view of the keys contained in a map ** `{#for key in map.keySet}` * `values`: Returns a Collection view of the values contained in a map ** `{#for value in map.values}` * `size`: Returns the number of key-value mappings in a map ** `{map.size}` * `isEmpty`: Returns true if a map contains no key-value mappings ** `{#if map.isEmpty}` * `get(key)`: Returns the value to which the specified key is mapped ** `{map.get('foo')}` TIP: A map value can be also accessed directly: `{map.myKey}`. Use the bracket notation for keys that are not legal identifiers: `{map['my key']}`. ===== Collections * `get(index)`: Returns the element at the specified position in a list ** `{list.get(0)}` * `reversed`: Returns a reversed iterator over a list ** `{#for r in recordsList.reversed}` * `take`: Returns the first `n` elements from the given list; throws an `IndexOutOfBoundsException` if `n` is out of range ** `{#for r in recordsList.take(3)}` * `takeLast`: Returns the last `n` elements from the given list; throws an `IndexOutOfBoundsException` if `n` is out of range ** `{#for r in recordsList.takeLast(3)}` TIP: A list element can be accessed directly: `{list.10}` or `{list[10]}`. ===== Numbers * `mod`: Modulo operation ** `{#if counter.mod(5) == 0}` ==== Strings * `fmt` or `format`: format the string instance via `java.lang.String.format()` ** `{myStr.fmt(""arg1"",""arg2"")}` ** `{myStr.format(locale,arg1)}` * `str:fmt` or `str:format`: format the supplied string value via `java.lang.String.format()` ** `{str:format(""Hello %s!"",name)}` ** `{str:fmt(locale,'%tA',now)}` ===== Config * `config:` or `config:[]`: Returns the config value for the given property name ** `{config:foo}` or `{config:['property.with.dot.in.name']}` * `config:property(name)`: Returns the config value for the given property name; the name can be obtained dynamically by an expression ** `{config:property('quarkus.foo')}` ** `{config:property(foo.getPropertyName())}` * `config:boolean(name)`: Returns the config value for the given property name as a boolean; the name can be obtained dynamically by an expression ** `{config:boolean('quarkus.foo.boolean') ?: 'Not Found'}` ** `{config:boolean(foo.getPropertyName()) ?: 'property is false'}` * `config:integer(name)`: Returns the config value for the given property name as an integer; the name can be obtained dynamically by an expression ** `{config:integer('quarkus.foo')}` ** `{config:integer(foo.getPropertyName())}` ===== Time * `format(pattern)`: Formats temporal objects from the `java.time` package ** `{dateTime.format('d MMM uuuu')}` * `format(pattern,locale)`: Formats temporal objects from the `java.time` package ** `{dateTime.format('d MMM uuuu',myLocale)}` * `format(pattern,locale,timeZone)`: Formats temporal objects from the `java.time` package ** `{dateTime.format('d MMM uuuu',myLocale,myTimeZoneId)}` * `time:format(dateTime,pattern)`: Formats temporal objects from the `java.time` package, `java.util.Date`, `java.util.Calendar` and `java.lang.Number` ** `{time:format(myDate,'d MMM uuuu')}` * `time:format(dateTime,pattern,locale)`: Formats temporal objects from the `java.time` package, `java.util.Date`, `java.util.Calendar` and `java.lang.Number` ** `{time:format(myDate,'d MMM uuuu', myLocale)}` * `time:format(dateTime,pattern,locale,timeZone)`: Formats temporal objects from the `java.time` package, `java.util.Date`, `java.util.Calendar` and `java.lang.Number` ** `{time:format(myDate,'d MMM uuuu',myTimeZoneId)}` [[template_data]] === @TemplateData A value resolver is automatically generated for a type annotated with `@TemplateData`. This allows Quarkus to avoid using reflection to access the data at runtime. NOTE: Non-public members, constructors, static initializers, static, synthetic and void methods are always ignored. [source,java] ---- package org.acme; @TemplateData class Item { public final BigDecimal price; public Item(BigDecimal price) { this.price = price; } public BigDecimal getDiscountedPrice() { return price.multiply(new BigDecimal(""0.9"")); } } ---- Any instance of `Item` can be used directly in the template: [source,html] ---- {#each items} <1> {it.price} / {it.discountedPrice} {/each} ---- <1> `items` is resolved to a list of `org.acme.Item` instances. Furthermore, `@TemplateData.properties()` and `@TemplateData.ignore()` can be used to fine-tune the generated resolver. Finally, it is also possible to specify the ""target"" of the annotation - this could be useful for third-party classes not controlled by the application: [source,java] ---- @TemplateData(target = BigDecimal.class) @TemplateData class Item { public final BigDecimal price; public Item(BigDecimal price) { this.price = price; } } ---- [source,html] ---- {#each items} <1> {it.price.setScale(2, rounding)} <1> {/each} ---- <1> The generated value resolver knows how to invoke the `BigDecimal.setScale()` method. [[native_executables]] === Native Executables In the JVM mode a reflection-based value resolver may be used to access properties and call methods of the model classes. But this does not work for <> out of the box. As a result, you may encounter template exceptions like `Property ""name"" not found on the base object ""org.acme.Foo"" in expression {foo.name} in template hello.html` even if the `Foo` class declares a relevant getter method. There are several ways to solve this problem: * Make use of <> or <> ** In this case, an optimized value resolver is generated automatically and used at rutime ** This is the preferred solution * Annotate the model class with <> - a specialized value resolver is generated and used at rutime * Annotate the model class with `@io.quarkus.runtime.annotations.RegisterForReflection` to make the reflection-based value resolver work [[resteasy_integration]] === RESTEasy Integration If you want to use Qute in your JAX-RS application, then depending on which JAX-RS stack you are using, you'll need to register the proper extension first. If you are using the traditional `quakus-resteasy` extension, then in your `pom.xml` file, add: [source,xml] ---- io.quarkus quarkus-resteasy-qute ---- If instead you are using RESTEasy Reactive via the `quarkus-resteasy-reactive` extension, then in your `pom.xml` file, add: [source,xml] ---- io.quarkus quarkus-resteasy-reactive-qute ---- Both of these extensions register a special `ContainerResponseFilter` implementation which enables resource methods to return a `TemplateInstance`, thus freeing users of having to take care of all necessary internal steps. The end result is that a using Qute within a JAX-RS resource may look as simple as: .HelloResource.java [source,java] ---- package org.acme.quarkus.sample; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import io.quarkus.qute.TemplateInstance; import io.quarkus.qute.Template; @Path(""hello"") public class HelloResource { @Inject Template hello; <1> @GET @Produces(MediaType.TEXT_PLAIN) public TemplateInstance get(@QueryParam(""name"") String name) { return hello.data(""name"", name); <2> <3> } } ---- <1> If there is no `@Location` qualifier provided, the field name is used to locate the template. In this particular case, we're injecting a template with path `templates/hello.txt`. <2> `Template.data()` returns a new template instance that can be customized before the actual rendering is triggered. In this case, we put the name value under the key `name`. The data map is accessible during rendering. <3> Note that we don't trigger the rendering - this is done automatically by a special `ContainerResponseFilter` implementation. TIP: Users are encouraged to use <> that help to organize the templates for a specific JAX-RS resource and enable <> automatically. The content negotiation is performed automatically. The resulting output depends on the `Accept` header received from the client. [source,java] ---- @Path(""/detail"") class DetailResource { @Inject Template item; <1> @GET @Produces({ MediaType.TEXT_HTML, MediaType.TEXT_PLAIN }) public TemplateInstance item() { return item.data(""myItem"", new Item(""Alpha"", 1000)); <2> } } ---- <1> Inject a variant template with base path derived from the injected field - `src/main/resources/templates/item`. <2> For `text/plain` the `src/main/resources/templates/item.txt` template is used. For `text/html` the `META-INF/resources/templates/item.html` template is used. The `RestTemplate` util class can be used to obtain a template instance from a body of a JAX-RS resource method: .RestTemplate Example [source,java] ---- @Path(""/detail"") class DetailResource { @GET @Produces({ MediaType.TEXT_HTML, MediaType.TEXT_PLAIN }) public TemplateInstance item() { return RestTemplate.data(""myItem"", new Item(""Alpha"", 1000)); <1> } } ---- <1> The name of the template is derived from the resource class and method name; `DetailResource/item` in this particular case. WARNING: Unlike with `@Inject` the templates obtained via `RestTemplate` are not validated, i.e. the build does not fail if a template does not exist. === Development Mode In the development mode, all files located in `src/main/resources/templates` are watched for changes and modifications are immediately visible. [[type-safe-message-bundles]] === Type-safe Message Bundles ==== Basic Concepts The basic idea is that every message is potentially a very simple template. In order to prevent type errors a message is defined as an annotated method of a *message bundle interface*. Quarkus generates the *message bundle implementation* at build time. Subsequently, the bundles can be used at runtime: 1. Directly in your code via `io.quarkus.qute.i18n.MessageBundles#get()`; e.g. `MessageBundles.get(AppMessages.class).hello_name(""Lucie"")` 2. Injected in your beans via `@Inject`; e.g. `@Inject AppMessages` 3. Referenced in the templates via the message bundle namespace: + [source,html] ---- {msg:hello_name('Lucie')} <1> <2> <3> {msg:message(myKey,'Lu')} <4> ---- <1> `msg` is the default namespace. <2> `hello_name` is the message key. <3> `Lucie` is the parameter of the message bundle interface method. <4> It is also possible to obtain a localized message for a key resolved at runtime using a reserved key `message`. The validation is skipped in this case though. .Message Bundle Interface Example [source,java] ---- import io.quarkus.qute.i18n.Message; import io.quarkus.qute.i18n.MessageBundle; @MessageBundle <1> public interface AppMessages { @Message(""Hello {name}!"") <2> String hello_name(String name); <3> } ---- <1> Denotes a message bundle interface. The bundle name is defaulted to `msg` and is used as a namespace in templates expressions, e.g. `{msg:hello_name}`. <2> Each method must be annotated with `@Message`. The value is a qute template. <3> The method parameters can be used in the template. ==== Bundle Name and Message Keys Keys are used directly in templates. The bundle name is used as a namespace in template expressions. The `@MessageBundle` can be used to define the default strategy used to generate message keys from method names. However, the `@Message` can override this strategy and even define a custom key. By default, the annotated element's name is used as-is. Other possibilities are: 1. De-camel-cased and hyphenated; e.g. `helloName()` -> `hello-name` 2. De-camel-cased and parts separated by underscores; e.g. `helloName()` -> `hello_name`. ==== Validation * All message bundle templates are validated: ** All expressions without a namespace must map to a parameter; e.g. `Hello {foo}` -> the method must have a param of name `foo` ** All expressions are validated against the types of the parameters; e.g. `Hello {foo.bar}` where the parameter `foo` is of type `org.acme.Foo` -> `org.acme.Foo` must have a property of name `bar` + NOTE: A warning message is logged for each _unused_ parameter. * Expressions that reference a message bundle method, such as `{msg:hello(item.name)}`, are validated too. ==== Localization The default locale of the Java Virtual Machine used to *build the application* is used for the `@MessageBundle` interface by default. However, the `io.quarkus.qute.i18n.MessageBundle#locale()` can be used to specify a custom locale. Additionally, there are two ways to define a localized bundle: 1. Create an interface that extends the default interface that is annotated with `@Localized` 2. Create an UTF-8 encoded file located in `src/main/resources/messages`; e.g. `msg_de.properties`. TIP: A localized interface is the preferred solution mainly due to the possibility of easy refactoring. .Localized Interface Example [source,java] ---- import io.quarkus.qute.i18n.Localized; import io.quarkus.qute.i18n.Message; @Localized(""de"") <1> public interface GermanAppMessages extends AppMessages { @Override @Message(""Hallo {name}!"") <2> String hello_name(String name); } ---- <1> The value is the locale tag string (IETF). <2> The value is the localized template. Message bundle files must be encoded in UTF-8. The file name consists of the relevant bundle name (e.g. `msg`) and underscore followed by the locate tag (IETF). The file format is very simple: each line represents either a key/value pair with the equals sign used as a separator or a comment (line starts with `#`). Blank lines are ignored. Keys are _mapped to method names_ from the corresponding message bundle interface. Values represent the templates normally defined by `io.quarkus.qute.i18n.Message#value()`. A value may be spread out across several adjacent normal lines. In such case, the line terminator must be escaped with a backslash character `\\`. The behavior is very similar to the behavior of the `java.util.Properties.load(Reader)` method. .Localized File Example - `msg_de.properties` [source,properties] ---- # This comment is ignored hello_name=Hallo {name}! <1> <2> ---- <1> Each line in a localized file represents a key/value pair. The key must correspond to a method declared on the message bundle interface. The value is the message template. <2> Keys and values are separated by the equals sign. NOTE: We use the `.properties` suffix in our example because most IDEs and text editors support syntax highlighting of `.properties` files. But in fact, the suffix could be anything - it is just ignored. TIP: An example properties file is generated into the target directory for each message bundle interface automatically. For example, by default if no name is specified for `@MessageBundle` the file `target/qute-i18n-examples/msg.properties` is generated when the application is build via `mvn clean package`. You can use this file as a base for a specific locale. Just rename the file - e.g. `msg_fr.properties`, change the message templates and move it in the `src/main/resources/messages` directory. .Value Spread Out Across Several Adjacent Lines [source,properties] ---- hello=Hello \\ {name} and \\ good morning! ---- Note that the line terminator is escaped with a backslash character `\\` and white space at the start of the following line is ignored. I.e. `{msg:hello('Edgar')}` would be rendered as `Hello Edgar and good morning!`. Once we have the localized bundles defined we need a way to _select_ the correct bundle. If you use a message bundle expression in a template you'll have to specify the `locale` attribute of a template instance. .`locale` Attribute Example [source,java] ---- @Singleton public class MyBean { @Inject Template hello; String render() { return hello.instance().setAttribute(""locale"", Locale.forLanguageTag(""cs"")).render(); <1> } } ---- <1> You can set a `Locale` instance or a locale tag string (IETF). NOTE: When using <> the `locale` attribute is derived from the the `Accept-Language` header if not set by a user. The `@Localized` qualifier can be used to inject a localized message bundle interface. .Injected Localized Message Bundle Example [source,java] ---- @Singleton public class MyBean { @Localized(""cs"") <1> AppMessages msg; String render() { return msg.hello_name(""Jachym""); } } ---- <1> The annotation value is a locale tag string (IETF). === Configuration Reference include::{generated-dir}/config/quarkus-qute.adoc[leveloffset=+1, opts=optional] [[standalone]] == Qute Used as a Standalone Library Qute is primarily designed as a Quarkus extension. However. it is possible to use it as a ""standalone"" library. In this case, some features are not available and some additional configuration is needed. Engine:: First of all, no managed `Engine` instance is available out of the box. You'll need to configure a new instance via `Engine.builder()`. Templates:: * By default, no <> are registered, i.e. `Engine.getTemplate(String)` will not work. * You can register a custom template locator or parse a template manually and put the reulst in the cache via `Engine.putTemplate(String, Template)`. Value resolvers:: * No <> are generated automatically. ** <> will not work. ** <> annotations are ignored. * It's recommended to register a `ReflectionValueResolver` instance via `Engine.addValueResolver(new ReflectionValueResolver())` so that Qute can access object properties and call public methods. + NOTE: Keep in mind that reflection may not work correctly in some restricted environments or may require additional configuration, e.g. registration in case of a GraalVM native image. * A custom value resolver can be easily built via `ValueResolver.builder()` Type-safety:: * <> are not validated. * <> are not supported. Injection:: It is not possible to inject a `Template` instance and vice versa - a template cannot inject a `@Named` CDI bean via the `inject:` namespace.",16320,True,2893.578390970625,median "package DDLS.data { import DDLS.data.math.DDLSGeom2D; import DDLS.data.math.DDLSMatrix2D; import DDLS.data.math.DDLSPoint2D; import DDLS.iterators.IteratorFromVertexToIncomingEdges; import DDLS.iterators.IteratorFromVertexToOutgoingEdges; import flash.utils.Dictionary; public class DDLSMesh { private static var INC:int = 0; private var _id:int; private var _width:Number; private var _height:Number; private var _clipping:Boolean; private var _vertices:Vector.; private var _edges:Vector.; private var _faces:Vector.; private var _constraintShapes:Vector.; private var _objects:Vector.; // keep references of center vertex and bounding edges when split, useful to restore edges as Delaunay private var __centerVertex:DDLSVertex; private var __edgesToCheck:Vector.; public function DDLSMesh(width:Number, height:Number) { _id = INC; INC++; _width = width; _height = height; _clipping = true; _vertices = new Vector.(); _edges = new Vector.(); _faces = new Vector.(); _constraintShapes = new Vector.(); _objects = new Vector.(); __edgesToCheck = new Vector.(); } public function get height():Number { return _height; } public function get width():Number { return _width; } public function get clipping():Boolean { return _clipping; } public function set clipping(value:Boolean):void { _clipping = value; } public function get id():int { return _id; } public function dispose():void { while ( _vertices.length > 0 ) _vertices.pop().dispose(); _vertices = null; while ( _edges.length > 0 ) _edges.pop().dispose(); _edges = null; while ( _faces.length > 0 ) _faces.pop().dispose(); _faces = null; while ( _constraintShapes.length > 0 ) _constraintShapes.pop().dispose(); _constraintShapes = null; while ( _objects.length > 0 ) _objects.pop().dispose(); _objects = null; __edgesToCheck = null; __centerVertex = null; } public function get __vertices():Vector. { return _vertices; } public function get __edges():Vector. { return _edges; } public function get __faces():Vector. { return _faces; } public function get __constraintShapes():Vector. { return _constraintShapes; } public function buildFromRecord(rec:String):void { var positions:Array = rec.split(';'); for (var i:int = 0; i < positions.length; i+=4) { insertConstraintSegment(Number(positions[i]), Number(positions[i+1]), Number(positions[i+2]), Number(positions[i+3])); } } public function insertObject(object:DDLSObject):void { if (object.constraintShape) deleteObject(object); var shape:DDLSConstraintShape = new DDLSConstraintShape(); var segment:DDLSConstraintSegment; var coordinates:Vector. = object.coordinates; var m:DDLSMatrix2D = object.matrix; object.updateMatrixFromValues(); var x1:Number; var y1:Number; var x2:Number; var y2:Number; var transfx1:Number; var transfy1:Number; var transfx2:Number; var transfy2:Number; for (var i:int=0 ; i):DDLSConstraintShape { var shape:DDLSConstraintShape = new DDLSConstraintShape(); var segment:DDLSConstraintSegment; for (var i:int=0 ; i _width && x2 > _width) || (x1 < 0 && x2 < 0) || (y1 > _height && y2 > _height) || (y1 < 0 && y2 < 0) ) { return null; } else { var nx:Number = x2 - x1; var ny:Number = y2 - y1; var tmin:Number = Number.NEGATIVE_INFINITY; var tmax:Number = Number.POSITIVE_INFINITY; if (nx != 0.0) { var tx1:Number = (0 - x1)/nx; var tx2:Number = (_width - x1)/nx; tmin = Math.max(tmin, Math.min(tx1, tx2)); tmax = Math.min(tmax, Math.max(tx1, tx2)); } if (ny != 0.0) { var ty1:Number = (0 - y1)/ny; var ty2:Number = (_height - y1)/ny; tmin = Math.max(tmin, Math.min(ty1, ty2)); tmax = Math.min(tmax, Math.max(ty1, ty2)); } if (tmax >= tmin) { if (tmax < 1) { //Clip end point newX2 = nx*tmax + x1; newY2 = ny*tmax + y1; } if (tmin > 0) { //Clip start point newX1 = nx*tmin + x1; newY1 = ny*tmin + y1; } } else return null; } // we check the vertices insertions var vertexDown:DDLSVertex = insertVertex(newX1, newY1); if (! vertexDown) return null; var vertexUp:DDLSVertex = insertVertex(newX2, newY2); if (! vertexUp) return null; if (vertexDown == vertexUp) return null; //trace(""vertices"", vertexDown.id, vertexUp.id) // useful var iterVertexToOutEdges:IteratorFromVertexToOutgoingEdges = new IteratorFromVertexToOutgoingEdges(); var currVertex:DDLSVertex; var currEdge:DDLSEdge; var i:int; // the new constraint segment var segment:DDLSConstraintSegment = new DDLSConstraintSegment(); var tempEdgeDownUp:DDLSEdge = new DDLSEdge(); var tempSdgeUpDown:DDLSEdge = new DDLSEdge(); tempEdgeDownUp.setDatas(vertexDown, tempSdgeUpDown, null, null, true, true); tempSdgeUpDown.setDatas(vertexUp, tempEdgeDownUp, null, null, true, true); var intersectedEdges:Vector. = new Vector.(); var leftBoundingEdges:Vector. = new Vector.(); var rightBoundingEdges:Vector. = new Vector.(); var currObjet:Object; var pIntersect:DDLSPoint2D = new DDLSPoint2D(); var edgeLeft:DDLSEdge; var newEdgeDownUp:DDLSEdge; var newEdgeUpDown:DDLSEdge; var done:Boolean; currVertex = vertexDown; currObjet = currVertex; while ( true ) { done = false; if ( (currVertex = currObjet as DDLSVertex) ) { //trace(""case vertex""); iterVertexToOutEdges.fromVertex = currVertex; while ( currEdge = iterVertexToOutEdges.next() ) { // if we meet directly the end vertex if ( currEdge.destinationVertex == vertexUp ) { //trace(""we met the end vertex""); if ( ! currEdge.isConstrained ) { currEdge.isConstrained = true; currEdge.oppositeEdge.isConstrained = true; } currEdge.addFromConstraintSegment(segment); currEdge.oppositeEdge.fromConstraintSegments = currEdge.fromConstraintSegments; vertexDown.addFromConstraintSegment(segment); vertexUp.addFromConstraintSegment(segment); segment.addEdge(currEdge); return segment; } // if we meet a vertex if ( DDLSGeom2D.distanceSquaredVertexToEdge(currEdge.destinationVertex, tempEdgeDownUp) <= DDLSConstants.EPSILON_SQUARED ) { //trace(""we met a vertex""); if ( ! currEdge.isConstrained ) { //trace(""edge is not constrained""); currEdge.isConstrained = true; currEdge.oppositeEdge.isConstrained = true; } currEdge.addFromConstraintSegment(segment); currEdge.oppositeEdge.fromConstraintSegments = currEdge.fromConstraintSegments; vertexDown.addFromConstraintSegment(segment); segment.addEdge(currEdge); vertexDown = currEdge.destinationVertex; tempEdgeDownUp.originVertex = vertexDown; currObjet = vertexDown; done = true; break; } } if (done) continue; iterVertexToOutEdges.fromVertex = currVertex; while ( currEdge = iterVertexToOutEdges.next() ) { currEdge = currEdge.nextLeftEdge; if ( DDLSGeom2D.intersections2edges(currEdge, tempEdgeDownUp, pIntersect) ) { //trace(""edge intersection""); if ( currEdge.isConstrained ) { //trace(""edge is constrained""); vertexDown = splitEdge(currEdge, pIntersect.x, pIntersect.y); iterVertexToOutEdges.fromVertex = currVertex; while ( currEdge = iterVertexToOutEdges.next() ) { if (currEdge.destinationVertex == vertexDown) { currEdge.isConstrained = true; currEdge.oppositeEdge.isConstrained = true; currEdge.addFromConstraintSegment(segment); currEdge.oppositeEdge.fromConstraintSegments = currEdge.fromConstraintSegments; segment.addEdge(currEdge); break; } } currVertex.addFromConstraintSegment(segment); tempEdgeDownUp.originVertex = vertexDown; currObjet = vertexDown; } else { //trace(""edge is not constrained""); intersectedEdges.push(currEdge); leftBoundingEdges.unshift(currEdge.nextLeftEdge); rightBoundingEdges.push(currEdge.prevLeftEdge); currEdge = currEdge.oppositeEdge; // we keep the edge from left to right currObjet = currEdge; } break; } } } else if ( (currEdge = currObjet as DDLSEdge) ) { //trace(""case edge""); edgeLeft = currEdge.nextLeftEdge; if ( edgeLeft.destinationVertex == vertexUp ) { //trace(""end point reached""); leftBoundingEdges.unshift(edgeLeft.nextLeftEdge); rightBoundingEdges.push(edgeLeft); newEdgeDownUp = new DDLSEdge(); newEdgeUpDown = new DDLSEdge(); newEdgeDownUp.setDatas(vertexDown, newEdgeUpDown, null, null, true, true); newEdgeUpDown.setDatas(vertexUp, newEdgeDownUp, null, null, true, true); leftBoundingEdges.push(newEdgeDownUp); rightBoundingEdges.push(newEdgeUpDown); insertNewConstrainedEdge(segment, newEdgeDownUp, intersectedEdges, leftBoundingEdges, rightBoundingEdges); return segment; } else if ( DDLSGeom2D.distanceSquaredVertexToEdge( edgeLeft.destinationVertex, tempEdgeDownUp) <= DDLSConstants.EPSILON_SQUARED ) { //trace(""we met a vertex""); leftBoundingEdges.unshift(edgeLeft.nextLeftEdge); rightBoundingEdges.push(edgeLeft); newEdgeDownUp = new DDLSEdge(); newEdgeUpDown = new DDLSEdge(); newEdgeDownUp.setDatas(vertexDown, newEdgeUpDown, null, null, true, true); newEdgeUpDown.setDatas(edgeLeft.destinationVertex, newEdgeDownUp, null, null, true, true); leftBoundingEdges.push(newEdgeDownUp); rightBoundingEdges.push(newEdgeUpDown); insertNewConstrainedEdge(segment, newEdgeDownUp, intersectedEdges, leftBoundingEdges, rightBoundingEdges); intersectedEdges.splice(0, intersectedEdges.length); leftBoundingEdges.splice(0, leftBoundingEdges.length); rightBoundingEdges.splice(0, rightBoundingEdges.length); vertexDown = edgeLeft.destinationVertex; tempEdgeDownUp.originVertex = vertexDown; currObjet = vertexDown; } else { if ( DDLSGeom2D.intersections2edges(edgeLeft, tempEdgeDownUp, pIntersect) ) { //trace(""1st left edge intersected""); if (edgeLeft.isConstrained) { //trace(""edge is constrained""); currVertex = splitEdge(edgeLeft, pIntersect.x, pIntersect.y); iterVertexToOutEdges.fromVertex = currVertex; while ( currEdge = iterVertexToOutEdges.next() ) { if (currEdge.destinationVertex == leftBoundingEdges[0].originVertex) { leftBoundingEdges.unshift(currEdge); } if (currEdge.destinationVertex == rightBoundingEdges[rightBoundingEdges.length-1].destinationVertex) { rightBoundingEdges.push(currEdge.oppositeEdge); } } newEdgeDownUp = new DDLSEdge(); newEdgeUpDown = new DDLSEdge(); newEdgeDownUp.setDatas(vertexDown, newEdgeUpDown, null, null, true, true); newEdgeUpDown.setDatas(currVertex, newEdgeDownUp, null, null, true, true); leftBoundingEdges.push(newEdgeDownUp); rightBoundingEdges.push(newEdgeUpDown); insertNewConstrainedEdge(segment, newEdgeDownUp, intersectedEdges, leftBoundingEdges, rightBoundingEdges); intersectedEdges.splice(0, intersectedEdges.length); leftBoundingEdges.splice(0, leftBoundingEdges.length); rightBoundingEdges.splice(0, rightBoundingEdges.length); vertexDown = currVertex; tempEdgeDownUp.originVertex = vertexDown; currObjet = vertexDown; } else { //trace(""edge is not constrained""); intersectedEdges.push(edgeLeft); leftBoundingEdges.unshift(edgeLeft.nextLeftEdge); currEdge = edgeLeft.oppositeEdge; // we keep the edge from left to right currObjet = currEdge; } } else { //trace(""2nd left edge intersected""); edgeLeft = edgeLeft.nextLeftEdge; DDLSGeom2D.intersections2edges(edgeLeft, tempEdgeDownUp, pIntersect); if (edgeLeft.isConstrained) { //trace(""edge is constrained""); currVertex = splitEdge(edgeLeft, pIntersect.x, pIntersect.y); iterVertexToOutEdges.fromVertex = currVertex; while ( currEdge = iterVertexToOutEdges.next() ) { if (currEdge.destinationVertex == leftBoundingEdges[0].originVertex) { leftBoundingEdges.unshift(currEdge); } if (currEdge.destinationVertex == rightBoundingEdges[rightBoundingEdges.length-1].destinationVertex) { rightBoundingEdges.push(currEdge.oppositeEdge); } } newEdgeDownUp = new DDLSEdge(); newEdgeUpDown = new DDLSEdge(); newEdgeDownUp.setDatas(vertexDown, newEdgeUpDown, null, null, true, true); newEdgeUpDown.setDatas(currVertex, newEdgeDownUp, null, null, true, true); leftBoundingEdges.push(newEdgeDownUp); rightBoundingEdges.push(newEdgeUpDown); insertNewConstrainedEdge(segment, newEdgeDownUp, intersectedEdges, leftBoundingEdges, rightBoundingEdges); intersectedEdges.splice(0, intersectedEdges.length); leftBoundingEdges.splice(0, leftBoundingEdges.length); rightBoundingEdges.splice(0, rightBoundingEdges.length); vertexDown = currVertex; tempEdgeDownUp.originVertex = vertexDown; currObjet = vertexDown; } else { //trace(""edge is not constrained""); intersectedEdges.push(edgeLeft); rightBoundingEdges.push(edgeLeft.prevLeftEdge); currEdge = edgeLeft.oppositeEdge; // we keep the edge from left to right currObjet = currEdge; } } } } } return segment; } private function insertNewConstrainedEdge(fromSegment:DDLSConstraintSegment, edgeDownUp:DDLSEdge, intersectedEdges:Vector., leftBoundingEdges:Vector., rightBoundingEdges:Vector.):void { //trace(""insertNewConstrainedEdge""); _edges.push(edgeDownUp); _edges.push(edgeDownUp.oppositeEdge); edgeDownUp.addFromConstraintSegment(fromSegment); edgeDownUp.oppositeEdge.fromConstraintSegments = edgeDownUp.fromConstraintSegments; fromSegment.addEdge(edgeDownUp); edgeDownUp.originVertex.addFromConstraintSegment(fromSegment); edgeDownUp.destinationVertex.addFromConstraintSegment(fromSegment); untriangulate(intersectedEdges); triangulate(leftBoundingEdges, true); triangulate(rightBoundingEdges, true); } public function deleteConstraintSegment(segment:DDLSConstraintSegment):void { //trace(""deleteConstraintSegment id"", segment.id); var i:int; var vertexToDelete:Vector. = new Vector.(); var edge:DDLSEdge; var vertex:DDLSVertex; var fromConstraintSegment:Vector.; for (i=0 ; i _width || y > _height) return null; __edgesToCheck.splice(0, __edgesToCheck.length); var inObject:Object = DDLSGeom2D.locatePosition(x, y, this); var inVertex:DDLSVertex; var inEdge:DDLSEdge; var inFace:DDLSFace; var newVertex:DDLSVertex; if ((inVertex = inObject as DDLSVertex)) { //trace(""inVertex"", inVertex.id); newVertex = inVertex; } else if ((inEdge = inObject as DDLSEdge)) { //trace(""inEdge"", inEdge); newVertex = splitEdge(inEdge, x, y); } else if ((inFace = inObject as DDLSFace)) { //trace(""inFace""); newVertex = splitFace(inFace, x, y); } restoreAsDelaunay(); return newVertex; } public function flipEdge(edge:DDLSEdge):DDLSEdge { // retrieve and create useful objets var eBot_Top:DDLSEdge = edge; var eTop_Bot:DDLSEdge = edge.oppositeEdge; var eLeft_Right:DDLSEdge = new DDLSEdge(); var eRight_Left:DDLSEdge = new DDLSEdge(); var eTop_Left:DDLSEdge = eBot_Top.nextLeftEdge; var eLeft_Bot:DDLSEdge = eTop_Left.nextLeftEdge; var eBot_Right:DDLSEdge = eTop_Bot.nextLeftEdge; var eRight_Top:DDLSEdge = eBot_Right.nextLeftEdge; var vBot:DDLSVertex = eBot_Top.originVertex; var vTop:DDLSVertex = eTop_Bot.originVertex; var vLeft:DDLSVertex = eLeft_Bot.originVertex; var vRight:DDLSVertex = eRight_Top.originVertex; var fLeft:DDLSFace = eBot_Top.leftFace; var fRight:DDLSFace = eTop_Bot.leftFace; var fBot:DDLSFace = new DDLSFace(); var fTop:DDLSFace = new DDLSFace(); // add the new edges _edges.push(eLeft_Right); _edges.push(eRight_Left); // add the new faces _faces.push( fTop ); _faces.push( fBot ); // set vertex, edge and face references for the new LEFT_RIGHT and RIGHT-LEFT edges eLeft_Right.setDatas(vLeft, eRight_Left, eRight_Top, fTop, edge.isReal, edge.isConstrained); eRight_Left.setDatas(vRight, eLeft_Right, eLeft_Bot, fBot, edge.isReal, edge.isConstrained); // set edge references for the new TOP and BOTTOM faces fTop.setDatas(eLeft_Right); fBot.setDatas(eRight_Left); // check the edge references of TOP and BOTTOM vertices if ( vTop.edge == eTop_Bot ) vTop.setDatas(eTop_Left); if ( vBot.edge == eBot_Top ) vBot.setDatas(eBot_Right); // set the new edge and face references for the 4 bouding edges eTop_Left.nextLeftEdge = eLeft_Right; eTop_Left.leftFace = fTop; eLeft_Bot.nextLeftEdge = eBot_Right; eLeft_Bot.leftFace = fBot; eBot_Right.nextLeftEdge = eRight_Left; eBot_Right.leftFace = fBot; eRight_Top.nextLeftEdge = eTop_Left; eRight_Top.leftFace = fTop; // remove the old TOP-BOTTOM and BOTTOM-TOP edges eBot_Top.dispose(); eTop_Bot.dispose(); _edges.splice(_edges.indexOf(eBot_Top), 1); _edges.splice(_edges.indexOf(eTop_Bot), 1); // remove the old LEFT and RIGHT faces fLeft.dispose(); fRight.dispose(); _faces.splice(_faces.indexOf(fLeft), 1); _faces.splice(_faces.indexOf(fRight), 1); return eRight_Left; } public function splitEdge(edge:DDLSEdge, x:Number, y:Number):DDLSVertex { // empty old references __edgesToCheck.splice(0, __edgesToCheck.length); // retrieve useful objets var eLeft_Right:DDLSEdge = edge; var eRight_Left:DDLSEdge = eLeft_Right.oppositeEdge; var eRight_Top:DDLSEdge = eLeft_Right.nextLeftEdge; var eTop_Left:DDLSEdge = eRight_Top.nextLeftEdge; var eLeft_Bot:DDLSEdge = eRight_Left.nextLeftEdge; var eBot_Right:DDLSEdge = eLeft_Bot.nextLeftEdge; var vTop:DDLSVertex = eTop_Left.originVertex; var vLeft:DDLSVertex = eLeft_Right.originVertex; var vBot:DDLSVertex = eBot_Right.originVertex; var vRight:DDLSVertex = eRight_Left.originVertex; var fTop:DDLSFace = eLeft_Right.leftFace; var fBot:DDLSFace = eRight_Left.leftFace; // check distance from the position to edge end points if ( (vLeft.pos.x - x)*(vLeft.pos.x - x) + (vLeft.pos.y - y)*(vLeft.pos.y - y) <= DDLSConstants.EPSILON_SQUARED ) return vLeft; if ( (vRight.pos.x - x)*(vRight.pos.x - x) + (vRight.pos.y - y)*(vRight.pos.y - y) <= DDLSConstants.EPSILON_SQUARED ) return vRight; // create new objects var vCenter:DDLSVertex = new DDLSVertex(); var eTop_Center:DDLSEdge = new DDLSEdge(); var eCenter_Top:DDLSEdge = new DDLSEdge(); var eBot_Center:DDLSEdge = new DDLSEdge(); var eCenter_Bot:DDLSEdge = new DDLSEdge(); var eLeft_Center:DDLSEdge = new DDLSEdge(); var eCenter_Left:DDLSEdge = new DDLSEdge(); var eRight_Center:DDLSEdge = new DDLSEdge(); var eCenter_Right:DDLSEdge = new DDLSEdge(); var fTopLeft:DDLSFace = new DDLSFace(); var fBotLeft:DDLSFace = new DDLSFace(); var fBotRight:DDLSFace = new DDLSFace(); var fTopRight:DDLSFace = new DDLSFace(); // add the new vertex _vertices.push(vCenter); // add the new edges _edges.push(eCenter_Top); _edges.push(eTop_Center); _edges.push(eCenter_Left); _edges.push(eLeft_Center); _edges.push(eCenter_Bot); _edges.push(eBot_Center); _edges.push(eCenter_Right); _edges.push(eRight_Center); // add the new faces _faces.push(fTopRight); _faces.push(fBotRight); _faces.push(fBotLeft); _faces.push(fTopLeft); // set pos and edge reference for the new CENTER vertex vCenter.setDatas( fTop.isReal ? eCenter_Top : eCenter_Bot); vCenter.pos.x = x; vCenter.pos.y = y; DDLSGeom2D.projectOrthogonaly(vCenter.pos, eLeft_Right); // set the new vertex, edge and face references for the new 8 center crossing edges eCenter_Top.setDatas(vCenter, eTop_Center, eTop_Left, fTopLeft, fTop.isReal); eTop_Center.setDatas(vTop, eCenter_Top, eCenter_Right, fTopRight, fTop.isReal); eCenter_Left.setDatas(vCenter, eLeft_Center, eLeft_Bot, fBotLeft, edge.isReal, edge.isConstrained); eLeft_Center.setDatas(vLeft, eCenter_Left, eCenter_Top, fTopLeft, edge.isReal, edge.isConstrained); eCenter_Bot.setDatas(vCenter, eBot_Center, eBot_Right, fBotRight, fBot.isReal); eBot_Center.setDatas(vBot, eCenter_Bot, eCenter_Left, fBotLeft, fBot.isReal); eCenter_Right.setDatas(vCenter, eRight_Center, eRight_Top, fTopRight, edge.isReal, edge.isConstrained); eRight_Center.setDatas(vRight, eCenter_Right, eCenter_Bot, fBotRight, edge.isReal, edge.isConstrained); // set the new edge references for the new 4 faces fTopLeft.setDatas(eCenter_Top, fTop.isReal); fBotLeft.setDatas(eCenter_Left, fBot.isReal); fBotRight.setDatas(eCenter_Bot, fBot.isReal); fTopRight.setDatas(eCenter_Right, fTop.isReal); // check the edge references of LEFT and RIGHT vertices if ( vLeft.edge == eLeft_Right ) vLeft.setDatas(eLeft_Center); if ( vRight.edge == eRight_Left ) vRight.setDatas(eRight_Center); // set the new edge and face references for the 4 bounding edges eTop_Left.nextLeftEdge = eLeft_Center; eTop_Left.leftFace = fTopLeft; eLeft_Bot.nextLeftEdge = eBot_Center; eLeft_Bot.leftFace = fBotLeft; eBot_Right.nextLeftEdge = eRight_Center; eBot_Right.leftFace = fBotRight; eRight_Top.nextLeftEdge = eTop_Center; eRight_Top.leftFace = fTopRight; // if the edge was constrained, we must: // - add the segments the edge is from to the 2 new // - update the segments the edge is from by deleting the old edge and inserting the 2 new // - add the segments the edge is from to the new vertex if (eLeft_Right.isConstrained) { var fromSegments:Vector. = eLeft_Right.fromConstraintSegments; eLeft_Center.fromConstraintSegments = fromSegments.slice(0); eCenter_Left.fromConstraintSegments = eLeft_Center.fromConstraintSegments; eCenter_Right.fromConstraintSegments = fromSegments.slice(0); eRight_Center.fromConstraintSegments = eCenter_Right.fromConstraintSegments; var edges:Vector.; var index:int; for (var i:int=0 ; i = new Vector.(); freeOfConstraint = vertex.fromConstraintSegments.length == 0; //trace("" -> freeOfConstraint"", freeOfConstraint); var bound:Vector. = new Vector.(); if (freeOfConstraint) { while ( edge = iterEdges.next() ) { outgoingEdges.push(edge); bound.push( edge.nextLeftEdge ); } } else { // we check if the vertex is an end point of a constraint segment var edges:Vector.; for (i=0 ; i is end point of a constraint segment""); return false; } } // we check the count of adjacent constrained edges var count:int = 0; while ( edge = iterEdges.next() ) { outgoingEdges.push(edge); if (edge.isConstrained) { count++; if (count > 2) { //trace("" -> count of adjacent constrained edges"", count); return false; } } } // if not disqualified, then we can process //trace(""process vertex deletion""); var boundA:Vector. = new Vector.(); var boundB:Vector. = new Vector.(); var constrainedEdgeA:DDLSEdge; var constrainedEdgeB:DDLSEdge; var edgeA:DDLSEdge = new DDLSEdge(); var edgeB:DDLSEdge = new DDLSEdge(); var realA:Boolean; var realB:Boolean; _edges.push(edgeA); _edges.push(edgeB); for (i=0; i < outgoingEdges.length; i++) { edge = outgoingEdges[i]; if (edge.isConstrained) { if (!constrainedEdgeA) { edgeB.setDatas(edge.destinationVertex, edgeA, null, null, true, true); boundA.push(edgeA, edge.nextLeftEdge); boundB.push(edgeB); constrainedEdgeA = edge; } else if (!constrainedEdgeB) { edgeA.setDatas(edge.destinationVertex, edgeB, null, null, true, true); boundB.push(edge.nextLeftEdge); constrainedEdgeB = edge; } } else { if (!constrainedEdgeA) boundB.push(edge.nextLeftEdge); else if (!constrainedEdgeB) boundA.push(edge.nextLeftEdge); else boundB.push(edge.nextLeftEdge); } } // keep infos about reality realA = constrainedEdgeA.leftFace.isReal; realB = constrainedEdgeB.leftFace.isReal; // we update the segments infos edgeA.fromConstraintSegments = constrainedEdgeA.fromConstraintSegments.slice(0); edgeB.fromConstraintSegments = edgeA.fromConstraintSegments; var index:int; for (i=0 ; i):void { // we clean useless faces and adjacent vertices var i:int; var verticesCleaned:Dictionary = new Dictionary(); var currEdge:DDLSEdge; var outEdge:DDLSEdge; for ( i=0 ; i, isReal:Boolean ):void { if (bound.length < 2) { trace(""BREAK ! the hole has less than 2 edges""); return; } // if the hole is a 2 edges polygon, we have a big problem else if (bound.length == 2) { //throw new Error(""BREAK ! the hole has only 2 edges! "" + "" - edge0: "" + bound[0].originVertex.id + "" -> "" + bound[0].destinationVertex.id + "" - edge1: "" + bound[1].originVertex.id + "" -> "" + bound[1].destinationVertex.id); trace(""BREAK ! the hole has only 2 edges""); trace("" - edge0:"", bound[0].originVertex.id, ""->"", bound[0].destinationVertex.id); trace("" - edge1:"", bound[1].originVertex.id, ""->"", bound[1].destinationVertex.id); return; } // if the hole is a 3 edges polygon: else if ( bound.length == 3 ) { /*trace(""the hole is a 3 edges polygon""); trace("" - edge0:"", bound[0].originVertex.id, ""->"", bound[0].destinationVertex.id); trace("" - edge1:"", bound[1].originVertex.id, ""->"", bound[1].destinationVertex.id); trace("" - edge2:"", bound[2].originVertex.id, ""->"", bound[2].destinationVertex.id);*/ var f:DDLSFace = new DDLSFace(); f.setDatas(bound[0], isReal); _faces.push(f); bound[0].leftFace = f; bound[1].leftFace = f; bound[2].leftFace = f; bound[0].nextLeftEdge = bound[1]; bound[1].nextLeftEdge = bound[2]; bound[2].nextLeftEdge = bound[0]; } else // if more than 3 edges, we process recursively: { //trace(""the hole has"", bound.length, ""edges""); for (i=0 ; i"", bound[i].destinationVertex.id); } var baseEdge:DDLSEdge = bound[0]; var vertexA:DDLSVertex = baseEdge.originVertex; var vertexB:DDLSVertex = baseEdge.destinationVertex; var vertexC:DDLSVertex; var vertexCheck:DDLSVertex; var circumcenter:DDLSPoint2D = new DDLSPoint2D(); var radiusSquared:Number; var distanceSquared:Number; var isDelaunay:Boolean; var index:int; var i:int; for (i=2 ; i; var boundM:Vector.; var boundB:Vector.; if (index < (bound.length-1)) { edgeA = new DDLSEdge(); edgeAopp = new DDLSEdge(); _edges.push(edgeA, edgeAopp); edgeA.setDatas(vertexA, edgeAopp, null, null, isReal, false); edgeAopp.setDatas(bound[index].originVertex, edgeA, null, null, isReal, false); boundA = bound.slice(index); boundA.push(edgeA); triangulate(boundA, isReal); } if ( index > 2 ) { edgeB = new DDLSEdge(); edgeBopp = new DDLSEdge(); _edges.push(edgeB, edgeBopp); edgeB.setDatas(bound[1].originVertex, edgeBopp, null, null, isReal, false); edgeBopp.setDatas(bound[index].originVertex, edgeB, null, null, isReal, false); boundB = bound.slice(1, index); boundB.push(edgeBopp); triangulate(boundB, isReal); } boundM = new Vector.(); if (index == 2) boundM.push(baseEdge, bound[1], edgeAopp); else if (index == (bound.length-1)) boundM.push(baseEdge, edgeB, bound[index]); else boundM.push(baseEdge, edgeB, edgeAopp ); triangulate(boundM, isReal); } } public function debug():void { var i:int; for (i = 0; i < __vertices.length; i++) { trace(""-- vertex"", _vertices[i].id); trace("" edge"", _vertices[i].edge.id, "" - "", _vertices[i].edge); trace("" edge isReal:"", _vertices[i].edge.isReal); } for (i = 0; i < _edges.length; i++) { trace(""-- edge"", _edges[i]); trace("" isReal"", _edges[i].id, "" - "", _edges[i].isReal); trace("" nextLeftEdge"", _edges[i].nextLeftEdge); trace("" oppositeEdge"", _edges[i].oppositeEdge); } } } }",12470,False,2247.9064593016205,median "[.configuration-legend] icon:lock[title=Fixed at build time] Configuration property fixed at build time - All other configuration properties are overridable at runtime [.configuration-reference, cols=""80,.^10,.^10""] |=== h|[[quarkus-oidc-oidc-tenant-config_configuration]]link:#quarkus-oidc-oidc-tenant-config_configuration[Configuration property] h|Type h|Default a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.auth-server-url]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.auth-server-url[quarkus.oidc.auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, `https://host:port/auth`. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: `https://host:port/auth/realms/++{++realm++}++` where `++{++realm++}++` has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.discovery-enabled]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.discovery-enabled[quarkus.oidc.discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the 'token-path' property must be configured. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token-path[quarkus.oidc.token-path]` [.description] -- Relative path of the OIDC token endpoint which issues access and refresh tokens using either 'client_credentials' or 'password' grants --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.client-id]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.client-id[quarkus.oidc.client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.connection-delay]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.connection-delay[quarkus.oidc.connection-delay]` [.description] -- The maximum amount of time connecting to the currently unavailable OIDC server will be attempted for. The number of times the connection request will be repeated is calculated by dividing the value of this property by 2. For example, setting it to `20S` will allow for requesting the connection up to 10 times with a 2 seconds delay between the retries. Note this property is only effective when the initial OIDC connection is created, for example, when requesting a well-known OIDC configuration. Use the 'connection-retry-count' property to support trying to re-establish an already available connection which may have been dropped. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.connection-retry-count]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.connection-retry-count[quarkus.oidc.connection-retry-count]` [.description] -- The number of times an attempt to re-establish an already available connection will be repeated for. Note this property is different to the `connection-delay` property which is only effective during the initial OIDC connection creation. This property is used to try to recover the existing connection which may have been temporarily lost. For example, if a request to the OIDC token endpoint fails due to a connection exception then the request will be retried for a number of times configured by this property. --|int |`3` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.connection-timeout]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.connection-timeout[quarkus.oidc.connection-timeout]` [.description] -- The amount of time after which the current OIDC connection request will time out. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10S` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.secret]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.secret[quarkus.oidc.credentials.secret]` [.description] -- Client secret which is used for a `client_secret_basic` authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.client-secret.value]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.client-secret.value[quarkus.oidc.credentials.client-secret.value]` [.description] -- The client secret --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.client-secret.method]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.client-secret.method[quarkus.oidc.credentials.client-secret.method]` [.description] -- Authentication method. --|`basic`, `post` | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.secret]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.secret[quarkus.oidc.credentials.jwt.secret]` [.description] -- If provided, indicates that JWT is signed using a secret key --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-file]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-file[quarkus.oidc.credentials.jwt.key-file]` [.description] -- If provided, indicates that JWT is signed using a private key in PEM or JWK format --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-store-file]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-store-file[quarkus.oidc.credentials.jwt.key-store-file]` [.description] -- If provided, indicates that JWT is signed using a private key from a key store --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-store-password]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-store-password[quarkus.oidc.credentials.jwt.key-store-password]` [.description] -- A parameter to specify the password of the key store file. If not given, the default (""password"") is used. --|string |`password` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-id]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-id[quarkus.oidc.credentials.jwt.key-id]` [.description] -- The private key id/alias --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-password]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.key-password[quarkus.oidc.credentials.jwt.key-password]` [.description] -- The private key password --|string |`password` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.lifespan]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.credentials.jwt.lifespan[quarkus.oidc.credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.proxy.host]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.proxy.host[quarkus.oidc.proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.proxy.port]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.proxy.port[quarkus.oidc.proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.proxy.username]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.proxy.username[quarkus.oidc.proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.proxy.password]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.proxy.password[quarkus.oidc.proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.tls.verification]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.tls.verification[quarkus.oidc.tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. --|`required`, `none` | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.tenant-id]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.tenant-id[quarkus.oidc.tenant-id]` [.description] -- A unique tenant identifier. It must be set by `TenantConfigResolver` providers which resolve the tenant configuration dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.tenant-enabled]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.tenant-enabled[quarkus.oidc.tenant-enabled]` [.description] -- If this tenant configuration is enabled. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.application-type]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.application-type[quarkus.oidc.application-type]` [.description] -- The application type, which can be one of the following values from enum `ApplicationType`. --|`web-app`, `service`, `hybrid` |`service` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authorization-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authorization-path[quarkus.oidc.authorization-path]` [.description] -- Relative path of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.user-info-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.user-info-path[quarkus.oidc.user-info-path]` [.description] -- Relative path of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.introspection-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.introspection-path[quarkus.oidc.introspection-path]` [.description] -- Relative path of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.jwks-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.jwks-path[quarkus.oidc.jwks-path]` [.description] -- Relative path of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.end-session-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.end-session-path[quarkus.oidc.end-session-path]` [.description] -- Relative path of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.public-key]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.public-key[quarkus.oidc.public-key]` [.description] -- Public key for the local JWT token verification. OIDC server connection will not be created when this property is set. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.roles.role-claim-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.roles.role-claim-path[quarkus.oidc.roles.role-claim-path]` [.description] -- Path to the claim containing an array of groups. It starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: ""realm/groups"". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in a different claim. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.roles.role-claim-separator]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.roles.role-claim-separator[quarkus.oidc.roles.role-claim-separator]` [.description] -- Separator for splitting a string which may contain multiple group values. It will only be used if the ""role-claim-path"" property points to a custom claim whose value is a string. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.roles.source]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.roles.source[quarkus.oidc.roles.source]` [.description] -- Source of the principal roles. --|`idtoken`, `accesstoken`, `userinfo` | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.issuer]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.issuer[quarkus.oidc.token.issuer]` [.description] -- Expected issuer 'iss' claim value. Note this property overrides the `issuer` property which may be set in OpenId Connect provider's well-known configuration. If the `iss` claim value varies depending on the host/IP address or tenant id of the provider then you may skip the issuer verification by setting this property to 'any' but it should be done only when other options (such as configuring the provider to use the fixed `iss` claim value) are not possible. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.audience]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.audience[quarkus.oidc.token.audience]` [.description] -- Expected audience 'aud' claim value which may be a string or an array of strings. --|list of string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.token-type]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.token-type[quarkus.oidc.token.token-type]` [.description] -- Expected token type --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.lifespan-grace]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.lifespan-grace[quarkus.oidc.token.lifespan-grace]` [.description] -- Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds. --|int | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.principal-claim]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.principal-claim[quarkus.oidc.token.principal-claim]` [.description] -- Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and `sub` claims are checked. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.refresh-expired]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.refresh-expired[quarkus.oidc.token.refresh-expired]` [.description] -- Refresh expired ID tokens. If this property is enabled then a refresh token request will be performed if the ID token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the `authentication.session-age-extension` property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type `ApplicationType++#++WEB_APP`++}++. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.refresh-token-time-skew]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.refresh-token-time-skew[quarkus.oidc.token.refresh-token-time-skew]` [.description] -- Refresh token time skew in seconds. If this property is enabled then the configured number of seconds is added to the current time when checking whether the access token should be refreshed. If the sum is greater than this access token's expiration time then a refresh is going to happen. This property will be ignored if the 'refresh-expired' property is not enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.forced-jwk-refresh-interval]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.forced-jwk-refresh-interval[quarkus.oidc.token.forced-jwk-refresh-interval]` [.description] -- Forced JWK set refresh interval in minutes. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10M` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.header]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.header[quarkus.oidc.token.header]` [.description] -- Custom HTTP header that contains a bearer token. This option is valid only when the application is of type `ApplicationType++#++SERVICE`++}++. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.allow-jwt-introspection]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.allow-jwt-introspection[quarkus.oidc.token.allow-jwt-introspection]` [.description] -- Allow the remote introspection of JWT tokens when no matching JWK key is available. Note this property is set to 'true' by default for backward-compatibility reasons and will be set to `false` instead in one of the next releases. Also note this property will be ignored if JWK endpoint URI is not available and introspecting the tokens is the only verification option. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.allow-opaque-token-introspection]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token.allow-opaque-token-introspection[quarkus.oidc.token.allow-opaque-token-introspection]` [.description] -- Allow the remote introspection of the opaque tokens. Set this property to 'false' if only JWT tokens are expected. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.logout.path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.logout.path[quarkus.oidc.logout.path]` [.description] -- The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.logout.post-logout-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.logout.post-logout-path[quarkus.oidc.logout.post-logout-path]` [.description] -- Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.redirect-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.redirect-path[quarkus.oidc.authentication.redirect-path]` [.description] -- Relative path for calculating a ""redirect_uri"" query parameter. It has to start from a forward slash and will be appended to the request URI's host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated if 'restorePathAfterRedirect' is set to 'true'. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.restore-path-after-redirect]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.restore-path-after-redirect[quarkus.oidc.authentication.restore-path-after-redirect]` [.description] -- If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. Note if `redirectPath` property is not set the the original request URI will be restored even if this property is disabled. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.remove-redirect-parameters]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.remove-redirect-parameters[quarkus.oidc.authentication.remove-redirect-parameters]` [.description] -- Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.verify-access-token]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.verify-access-token[quarkus.oidc.authentication.verify-access-token]` [.description] -- Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if `quarkus.oidc.roles.source` property is set to `accesstoken` which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.force-redirect-https-scheme]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.force-redirect-https-scheme[quarkus.oidc.authentication.force-redirect-https-scheme]` [.description] -- Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout `post_logout_redirect_uri` and the local redirect requests. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.scopes]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.scopes[quarkus.oidc.authentication.scopes]` [.description] -- List of scopes --|list of string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.cookie-force-secure]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.cookie-force-secure[quarkus.oidc.authentication.cookie-force-secure]` [.description] -- If enabled the state, session and post logout cookies will have their 'secure' parameter set to 'true' when HTTP is used. It may be necessary when running behind an SSL terminating reverse proxy. The cookies will always be secure if HTTPS is used even if this property is set to false. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.cookie-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.cookie-path[quarkus.oidc.authentication.cookie-path]` [.description] -- Cookie path parameter value which, if set, will be used to set a path parameter for the session, state and post logout cookies. The `cookie-path-header` property, if set, will be checked first. --|string |`/` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.cookie-path-header]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.cookie-path-header[quarkus.oidc.authentication.cookie-path-header]` [.description] -- Cookie path header parameter value which, if set, identifies the incoming HTTP header whose value will be used to set a path parameter for the session, state and post logout cookies. If the header is missing then the `cookie-path` property will be checked. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.cookie-domain]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.cookie-domain[quarkus.oidc.authentication.cookie-domain]` [.description] -- Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.user-info-required]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.user-info-required[quarkus.oidc.authentication.user-info-required]` [.description] -- If this property is set to 'true' then an OIDC UserInfo endpoint will be called --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.session-age-extension]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.session-age-extension[quarkus.oidc.authentication.session-age-extension]` [.description] -- Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the `token.refresh-expired` property has not been enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`5M` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.java-script-auto-redirect]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.java-script-auto-redirect[quarkus.oidc.authentication.java-script-auto-redirect]` [.description] -- If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since it automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to `false` then a status code of '499' will be returned to allow the client to handle the redirect manually --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token-state-manager.strategy]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token-state-manager.strategy[quarkus.oidc.token-state-manager.strategy]` [.description] -- Default TokenStateManager strategy. --|`keep-all-tokens`, `id-token`, `id-refresh-tokens` |`keep-all-tokens` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.token-state-manager.split-tokens]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.token-state-manager.split-tokens[quarkus.oidc.token-state-manager.split-tokens]` [.description] -- Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.extra-params-extra-params]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.authentication.extra-params-extra-params[quarkus.oidc.authentication.extra-params]` [.description] -- Additional properties which will be added as the query parameters to the authentication redirect URI. --|`Map` | h|[[quarkus-oidc-oidc-tenant-config_quarkus.oidc.named-tenants-additional-named-tenants]]link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.named-tenants-additional-named-tenants[Additional named tenants] h|Type h|Default a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.auth-server-url]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.auth-server-url[quarkus.oidc.""tenant"".auth-server-url]` [.description] -- The base URL of the OpenID Connect (OIDC) server, for example, `https://host:port/auth`. OIDC discovery endpoint will be called by default by appending a '.well-known/openid-configuration' path to this URL. Note if you work with Keycloak OIDC server, make sure the base URL is in the following format: `https://host:port/auth/realms/++{++realm++}++` where `++{++realm++}++` has to be replaced by the name of the Keycloak realm. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.discovery-enabled]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.discovery-enabled[quarkus.oidc.""tenant"".discovery-enabled]` [.description] -- Enables OIDC discovery. If the discovery is disabled then the 'token-path' property must be configured. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token-path[quarkus.oidc.""tenant"".token-path]` [.description] -- Relative path of the OIDC token endpoint which issues access and refresh tokens using either 'client_credentials' or 'password' grants --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.client-id]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.client-id[quarkus.oidc.""tenant"".client-id]` [.description] -- The client-id of the application. Each application has a client-id that is used to identify the application --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.connection-delay]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.connection-delay[quarkus.oidc.""tenant"".connection-delay]` [.description] -- The maximum amount of time connecting to the currently unavailable OIDC server will be attempted for. The number of times the connection request will be repeated is calculated by dividing the value of this property by 2. For example, setting it to `20S` will allow for requesting the connection up to 10 times with a 2 seconds delay between the retries. Note this property is only effective when the initial OIDC connection is created, for example, when requesting a well-known OIDC configuration. Use the 'connection-retry-count' property to support trying to re-establish an already available connection which may have been dropped. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.connection-retry-count]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.connection-retry-count[quarkus.oidc.""tenant"".connection-retry-count]` [.description] -- The number of times an attempt to re-establish an already available connection will be repeated for. Note this property is different to the `connection-delay` property which is only effective during the initial OIDC connection creation. This property is used to try to recover the existing connection which may have been temporarily lost. For example, if a request to the OIDC token endpoint fails due to a connection exception then the request will be retried for a number of times configured by this property. --|int |`3` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.connection-timeout]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.connection-timeout[quarkus.oidc.""tenant"".connection-timeout]` [.description] -- The amount of time after which the current OIDC connection request will time out. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10S` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.secret]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.secret[quarkus.oidc.""tenant"".credentials.secret]` [.description] -- Client secret which is used for a `client_secret_basic` authentication method. Note that a 'client-secret.value' can be used instead but both properties are mutually exclusive. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.client-secret.value]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.client-secret.value[quarkus.oidc.""tenant"".credentials.client-secret.value]` [.description] -- The client secret --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.client-secret.method]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.client-secret.method[quarkus.oidc.""tenant"".credentials.client-secret.method]` [.description] -- Authentication method. --|`basic`, `post` | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.secret]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.secret[quarkus.oidc.""tenant"".credentials.jwt.secret]` [.description] -- If provided, indicates that JWT is signed using a secret key --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-file]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-file[quarkus.oidc.""tenant"".credentials.jwt.key-file]` [.description] -- If provided, indicates that JWT is signed using a private key in PEM or JWK format --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-store-file]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-store-file[quarkus.oidc.""tenant"".credentials.jwt.key-store-file]` [.description] -- If provided, indicates that JWT is signed using a private key from a key store --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-store-password]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-store-password[quarkus.oidc.""tenant"".credentials.jwt.key-store-password]` [.description] -- A parameter to specify the password of the key store file. If not given, the default (""password"") is used. --|string |`password` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-id]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-id[quarkus.oidc.""tenant"".credentials.jwt.key-id]` [.description] -- The private key id/alias --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-password]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.key-password[quarkus.oidc.""tenant"".credentials.jwt.key-password]` [.description] -- The private key password --|string |`password` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.lifespan]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.credentials.jwt.lifespan[quarkus.oidc.""tenant"".credentials.jwt.lifespan]` [.description] -- JWT life-span in seconds. It will be added to the time it was issued at to calculate the expiration time. --|int |`10` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.proxy.host]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.proxy.host[quarkus.oidc.""tenant"".proxy.host]` [.description] -- The host (name or IP address) of the Proxy. Note: If OIDC adapter needs to use a Proxy to talk with OIDC server (Provider), then at least the ""host"" config item must be configured to enable the usage of a Proxy. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.proxy.port]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.proxy.port[quarkus.oidc.""tenant"".proxy.port]` [.description] -- The port number of the Proxy. Default value is 80. --|int |`80` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.proxy.username]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.proxy.username[quarkus.oidc.""tenant"".proxy.username]` [.description] -- The username, if Proxy needs authentication. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.proxy.password]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.proxy.password[quarkus.oidc.""tenant"".proxy.password]` [.description] -- The password, if Proxy needs authentication. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.tls.verification]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.tls.verification[quarkus.oidc.""tenant"".tls.verification]` [.description] -- Certificate validation and hostname verification, which can be one of the following values from enum `Verification`. Default is required. --|`required`, `none` | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.tenant-id]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.tenant-id[quarkus.oidc.""tenant"".tenant-id]` [.description] -- A unique tenant identifier. It must be set by `TenantConfigResolver` providers which resolve the tenant configuration dynamically and is optional in all other cases. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.tenant-enabled]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.tenant-enabled[quarkus.oidc.""tenant"".tenant-enabled]` [.description] -- If this tenant configuration is enabled. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.application-type]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.application-type[quarkus.oidc.""tenant"".application-type]` [.description] -- The application type, which can be one of the following values from enum `ApplicationType`. --|`web-app`, `service`, `hybrid` |`service` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authorization-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authorization-path[quarkus.oidc.""tenant"".authorization-path]` [.description] -- Relative path of the OIDC authorization endpoint which authenticates the users. This property must be set for the 'web-app' applications if OIDC discovery is disabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.user-info-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.user-info-path[quarkus.oidc.""tenant"".user-info-path]` [.description] -- Relative path of the OIDC userinfo endpoint. This property must only be set for the 'web-app' applications if OIDC discovery is disabled and 'authentication.user-info-required' property is enabled. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.introspection-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.introspection-path[quarkus.oidc.""tenant"".introspection-path]` [.description] -- Relative path of the OIDC RFC7662 introspection endpoint which can introspect both opaque and JWT tokens. This property must be set if OIDC discovery is disabled and 1) the opaque bearer access tokens have to be verified or 2) JWT tokens have to be verified while the cached JWK verification set with no matching JWK is being refreshed. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.jwks-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.jwks-path[quarkus.oidc.""tenant"".jwks-path]` [.description] -- Relative path of the OIDC JWKS endpoint which returns a JSON Web Key Verification Set. This property should be set if OIDC discovery is disabled and the local JWT verification is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.end-session-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.end-session-path[quarkus.oidc.""tenant"".end-session-path]` [.description] -- Relative path of the OIDC end_session_endpoint. This property must be set if OIDC discovery is disabled and RP Initiated Logout support for the 'web-app' applications is required. This property will be ignored if the discovery is enabled. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.public-key]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.public-key[quarkus.oidc.""tenant"".public-key]` [.description] -- Public key for the local JWT token verification. OIDC server connection will not be created when this property is set. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.roles.role-claim-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.roles.role-claim-path[quarkus.oidc.""tenant"".roles.role-claim-path]` [.description] -- Path to the claim containing an array of groups. It starts from the top level JWT JSON object and can contain multiple segments where each segment represents a JSON object name only, example: ""realm/groups"". Use double quotes with the namespace qualified claim names. This property can be used if a token has no 'groups' claim but has the groups set in a different claim. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.roles.role-claim-separator]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.roles.role-claim-separator[quarkus.oidc.""tenant"".roles.role-claim-separator]` [.description] -- Separator for splitting a string which may contain multiple group values. It will only be used if the ""role-claim-path"" property points to a custom claim whose value is a string. A single space will be used by default because the standard 'scope' claim may contain a space separated sequence. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.roles.source]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.roles.source[quarkus.oidc.""tenant"".roles.source]` [.description] -- Source of the principal roles. --|`idtoken`, `accesstoken`, `userinfo` | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.issuer]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.issuer[quarkus.oidc.""tenant"".token.issuer]` [.description] -- Expected issuer 'iss' claim value. Note this property overrides the `issuer` property which may be set in OpenId Connect provider's well-known configuration. If the `iss` claim value varies depending on the host/IP address or tenant id of the provider then you may skip the issuer verification by setting this property to 'any' but it should be done only when other options (such as configuring the provider to use the fixed `iss` claim value) are not possible. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.audience]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.audience[quarkus.oidc.""tenant"".token.audience]` [.description] -- Expected audience 'aud' claim value which may be a string or an array of strings. --|list of string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.token-type]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.token-type[quarkus.oidc.""tenant"".token.token-type]` [.description] -- Expected token type --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.lifespan-grace]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.lifespan-grace[quarkus.oidc.""tenant"".token.lifespan-grace]` [.description] -- Life span grace period in seconds. When checking token expiry, current time is allowed to be later than token expiration time by at most the configured number of seconds. When checking token issuance, current time is allowed to be sooner than token issue time by at most the configured number of seconds. --|int | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.principal-claim]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.principal-claim[quarkus.oidc.""tenant"".token.principal-claim]` [.description] -- Name of the claim which contains a principal name. By default, the 'upn', 'preferred_username' and `sub` claims are checked. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.refresh-expired]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.refresh-expired[quarkus.oidc.""tenant"".token.refresh-expired]` [.description] -- Refresh expired ID tokens. If this property is enabled then a refresh token request will be performed if the ID token has expired and, if successful, the local session will be updated with the new set of tokens. Otherwise, the local session will be invalidated and the user redirected to the OpenID Provider to re-authenticate. In this case the user may not be challenged again if the OIDC provider session is still active. For this option be effective the `authentication.session-age-extension` property should also be set to a non-zero value since the refresh token is currently kept in the user session. This option is valid only when the application is of type `ApplicationType++#++WEB_APP`++}++. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.refresh-token-time-skew]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.refresh-token-time-skew[quarkus.oidc.""tenant"".token.refresh-token-time-skew]` [.description] -- Refresh token time skew in seconds. If this property is enabled then the configured number of seconds is added to the current time when checking whether the access token should be refreshed. If the sum is greater than this access token's expiration time then a refresh is going to happen. This property will be ignored if the 'refresh-expired' property is not enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.forced-jwk-refresh-interval]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.forced-jwk-refresh-interval[quarkus.oidc.""tenant"".token.forced-jwk-refresh-interval]` [.description] -- Forced JWK set refresh interval in minutes. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`10M` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.header]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.header[quarkus.oidc.""tenant"".token.header]` [.description] -- Custom HTTP header that contains a bearer token. This option is valid only when the application is of type `ApplicationType++#++SERVICE`++}++. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.allow-jwt-introspection]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.allow-jwt-introspection[quarkus.oidc.""tenant"".token.allow-jwt-introspection]` [.description] -- Allow the remote introspection of JWT tokens when no matching JWK key is available. Note this property is set to 'true' by default for backward-compatibility reasons and will be set to `false` instead in one of the next releases. Also note this property will be ignored if JWK endpoint URI is not available and introspecting the tokens is the only verification option. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.allow-opaque-token-introspection]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token.allow-opaque-token-introspection[quarkus.oidc.""tenant"".token.allow-opaque-token-introspection]` [.description] -- Allow the remote introspection of the opaque tokens. Set this property to 'false' if only JWT tokens are expected. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.logout.path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.logout.path[quarkus.oidc.""tenant"".logout.path]` [.description] -- The relative path of the logout endpoint at the application. If provided, the application is able to initiate the logout through this endpoint in conformance with the OpenID Connect RP-Initiated Logout specification. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.logout.post-logout-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.logout.post-logout-path[quarkus.oidc.""tenant"".logout.post-logout-path]` [.description] -- Relative path of the application endpoint where the user should be redirected to after logging out from the OpenID Connect Provider. This endpoint URI must be properly registered at the OpenID Connect Provider as a valid redirect URI. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.redirect-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.redirect-path[quarkus.oidc.""tenant"".authentication.redirect-path]` [.description] -- Relative path for calculating a ""redirect_uri"" query parameter. It has to start from a forward slash and will be appended to the request URI's host and port. For example, if the current request URI is 'https://localhost:8080/service' then a 'redirect_uri' parameter will be set to 'https://localhost:8080/' if this property is set to '/' and be the same as the request URI if this property has not been configured. Note the original request URI will be restored after the user has authenticated if 'restorePathAfterRedirect' is set to 'true'. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.restore-path-after-redirect]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.restore-path-after-redirect[quarkus.oidc.""tenant"".authentication.restore-path-after-redirect]` [.description] -- If this property is set to 'true' then the original request URI which was used before the authentication will be restored after the user has been redirected back to the application. Note if `redirectPath` property is not set the the original request URI will be restored even if this property is disabled. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.remove-redirect-parameters]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.remove-redirect-parameters[quarkus.oidc.""tenant"".authentication.remove-redirect-parameters]` [.description] -- Remove the query parameters such as 'code' and 'state' set by the OIDC server on the redirect URI after the user has authenticated by redirecting a user to the same URI but without the query parameters. --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.verify-access-token]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.verify-access-token[quarkus.oidc.""tenant"".authentication.verify-access-token]` [.description] -- Both ID and access tokens are fetched from the OIDC provider as part of the authorization code flow. ID token is always verified on every user request as the primary token which is used to represent the principal and extract the roles. Access token is not verified by default since it is meant to be propagated to the downstream services. The verification of the access token should be enabled if it is injected as a JWT token. Access tokens obtained as part of the code flow will always be verified if `quarkus.oidc.roles.source` property is set to `accesstoken` which means the authorization decision will be based on the roles extracted from the access token. Bearer access tokens are always verified. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.force-redirect-https-scheme]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.force-redirect-https-scheme[quarkus.oidc.""tenant"".authentication.force-redirect-https-scheme]` [.description] -- Force 'https' as the 'redirect_uri' parameter scheme when running behind an SSL terminating reverse proxy. This property, if enabled, will also affect the logout `post_logout_redirect_uri` and the local redirect requests. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.scopes]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.scopes[quarkus.oidc.""tenant"".authentication.scopes]` [.description] -- List of scopes --|list of string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.extra-params-extra-params]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.extra-params-extra-params[quarkus.oidc.""tenant"".authentication.extra-params]` [.description] -- Additional properties which will be added as the query parameters to the authentication redirect URI. --|`Map` | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.cookie-force-secure]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.cookie-force-secure[quarkus.oidc.""tenant"".authentication.cookie-force-secure]` [.description] -- If enabled the state, session and post logout cookies will have their 'secure' parameter set to 'true' when HTTP is used. It may be necessary when running behind an SSL terminating reverse proxy. The cookies will always be secure if HTTPS is used even if this property is set to false. --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.cookie-path]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.cookie-path[quarkus.oidc.""tenant"".authentication.cookie-path]` [.description] -- Cookie path parameter value which, if set, will be used to set a path parameter for the session, state and post logout cookies. The `cookie-path-header` property, if set, will be checked first. --|string |`/` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.cookie-path-header]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.cookie-path-header[quarkus.oidc.""tenant"".authentication.cookie-path-header]` [.description] -- Cookie path header parameter value which, if set, identifies the incoming HTTP header whose value will be used to set a path parameter for the session, state and post logout cookies. If the header is missing then the `cookie-path` property will be checked. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.cookie-domain]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.cookie-domain[quarkus.oidc.""tenant"".authentication.cookie-domain]` [.description] -- Cookie domain parameter value which, if set, will be used for the session, state and post logout cookies. --|string | a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.user-info-required]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.user-info-required[quarkus.oidc.""tenant"".authentication.user-info-required]` [.description] -- If this property is set to 'true' then an OIDC UserInfo endpoint will be called --|boolean |`false` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.session-age-extension]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.session-age-extension[quarkus.oidc.""tenant"".authentication.session-age-extension]` [.description] -- Session age extension in minutes. The user session age property is set to the value of the ID token life-span by default and the user will be redirected to the OIDC provider to re-authenticate once the session has expired. If this property is set to a non-zero value then the expired ID token can be refreshed before the session has expired. This property will be ignored if the `token.refresh-expired` property has not been enabled. --|link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html[Duration] link:#duration-note-anchor[icon:question-circle[], title=More information about the Duration format] |`5M` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.java-script-auto-redirect]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.authentication.java-script-auto-redirect[quarkus.oidc.""tenant"".authentication.java-script-auto-redirect]` [.description] -- If this property is set to 'true' then a normal 302 redirect response will be returned if the request was initiated via JavaScript API such as XMLHttpRequest or Fetch and the current user needs to be (re)authenticated which may not be desirable for Single Page Applications since it automatically following the redirect may not work given that OIDC authorization endpoints typically do not support CORS. If this property is set to `false` then a status code of '499' will be returned to allow the client to handle the redirect manually --|boolean |`true` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token-state-manager.strategy]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token-state-manager.strategy[quarkus.oidc.""tenant"".token-state-manager.strategy]` [.description] -- Default TokenStateManager strategy. --|`keep-all-tokens`, `id-token`, `id-refresh-tokens` |`keep-all-tokens` a| [[quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token-state-manager.split-tokens]]`link:#quarkus-oidc-oidc-tenant-config_quarkus.oidc.-tenant-.token-state-manager.split-tokens[quarkus.oidc.""tenant"".token-state-manager.split-tokens]` [.description] -- Default TokenStateManager keeps all tokens (ID, access and refresh) returned in the authorization code grant response in a single session cookie by default. Enable this property to minimize a session cookie size --|boolean |`false` |=== ifndef::no-duration-note[] [NOTE] [[duration-note-anchor]] .About the Duration format ==== The format for durations uses the standard `java.time.Duration` format. You can learn more about it in the link:https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-[Duration#parse() javadoc]. You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, `PT` is implicitly prepended to the value to obtain a standard `java.time.Duration` format. ==== endif::no-duration-note[] ",16307,True,4727.173447814891,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.containers { /* import flash.display.DisplayObject; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.Point; import mx.containers.dividedBoxClasses.BoxDivider; import mx.core.EdgeMetrics; import mx.core.IFlexDisplayObject; import mx.core.IFlexModuleFactory; import mx.core.IInvalidating; */ import mx.containers.beads.BoxLayout; import mx.containers.beads.DividedBoxLayout; import mx.core.IUIComponent; import mx.core.UIComponent; /* import mx.core.mx_internal; import mx.events.ChildExistenceChangedEvent; import mx.events.DividerEvent; import mx.managers.CursorManager; import mx.managers.CursorManagerPriority; import mx.styles.IStyleManager2; import mx.styles.StyleManager; use namespace mx_internal; */ //-------------------------------------- // Events //-------------------------------------- /** * Dispatched multiple times as the user drags any divider. * * The dividerDrag event is dispatched * after the dividerPress event * and before the dividerRelease event. * * @eventType mx.events.DividerEvent.DIVIDER_DRAG * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Event(name=""dividerDrag"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user presses any divider in this container. * * The dividerPress event is dispatched * before any dividerDrag events are dispatched. * * @eventType mx.events.DividerEvent.DIVIDER_PRESS * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ //[Event(name=""dividerPress"", type=""mx.events.DividerEvent"")] /** * Dispatched when the user releases a divider. * * The dividerRelease event is dispatched * after the dividerDrag events, * but before the container's children are resized. * The divider's x and y properties are not updated until * after this event is triggered. As a result, a call to * hDividerBox.getDividerAt(0).x will return * the value of the original x position of the first divider. If you want the * position of the divider after the move, you can access it when the * DividerBox's updateComplete event has been triggered. * * @eventType mx.events.DividerEvent.DIVIDER_RELEASE * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ [Event(name=""dividerRelease"", type=""mx.events.DividerEvent"")] /** * A DividedBox container measures and lays out its children * horizontally or vertically in exactly the same way as a * Box container, but it inserts * draggable dividers in the gaps between the children. * Users can drag any divider to resize the children on each side. * *

    The DividedBox class is the base class for the more commonly used * HDividedBox and VDividedBox classes.

    * *

    The direction property of a DividedBox container, inherited * from Box container, determines whether it has horizontal * or vertical layout.

    * *

    A DividedBox, HDividedBox, or VDividedBox container has the following default sizing characteristics:

    * * * * * * * * * * * * * * * * * *
    CharacteristicDescription
    Default sizeVertical DividedBox Height is large enough to hold all of its children at the default or explicit * heights of the children, plus any vertical gap between the children, plus the top and bottom padding of the * container. The width is the default or explicit width of the widest child, plus the left and right padding of * the container. *
    Horizontal DividedBox Width is large enough to hold all of its children at the * default or explicit widths of the children, plus any horizontal gap between the children, plus the left and * right padding of the container. Height is the default or explicit height of the tallest child * plus the top and bottom padding of the container.
    Default padding0 pixels for the top, bottom, left, and right values.
    Default gap10 pixels for the horizontal and vertical gaps.
    * * @mxml * *

    The <mx:DividedBox> tag inherits all of the tag * attributes of its superclass, and adds the following tag attributes:

    * *
     *  <mx:DividedBox
     *    Properties
     *    liveDragging=""false|true""
     *    resizeToContent=""false|true""
     *  
     *    Styles
     *    dividerAffordance=""6""
     *    dividerAlpha=""0.75""
     *    dividerColor=""0x6F7777""
     *    dividerSkin=""'mx.skins.BoxDividerSkin' symbol in Assets.swf""
     *    dividerThickness=""3""
     *    horizontalDividerCursor=""'mx.skins.cursor.HBoxDivider' symbol in Assets.swf""
     *    verticalDividerCursor=""'mx.skins.cursor.VBoxDivider' symbol in Assets.swf""
     * 
     *    Events
     *    dividerPress=""No default""
     *    dividerDrag=""No default""
     *    dividerRelease=""No default""
     *    >
     *      ...
     *      child tags
     *      ...
     *  </mx:DividedBox>
     *  
    * * @see mx.containers.HDividedBox * @see mx.containers.VDividedBox * * @includeExample examples/DividedBoxExample.mxml * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class DividedBox extends Box { //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * @private */ private static const PROXY_DIVIDER_INDEX:int = 999; //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function DividedBox() { super(); // addEventListener(ChildExistenceChangedEvent.CHILD_ADD, childAddHandler); // addEventListener(ChildExistenceChangedEvent.CHILD_REMOVE, // childRemoveHandler); } override protected function createLayout():void { _layout = new DividedBoxLayout(); } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- /** * @private * Container for holding divider objects. */ private var dividerLayer:UIComponent = null; /** * @private */ //mx_internal var activeDivider:BoxDivider; /** * @private */ private var activeDividerIndex:int = -1; /** * @private */ private var activeDividerStartPosition:Number; /** * @private */ private var dragStartPosition:Number; /** * @private */ private var dragDelta:Number; /** * @private */ private var oldChildSizes:Array /* of ChildSizeInfo */; /** * @private */ private var minDelta:Number; /** * @private */ private var maxDelta:Number; /** * @private * Only allow a single divider to move at a time. */ private var dontCoalesceDividers:Boolean; /** * @private */ //private var cursorID:int = CursorManager.NO_CURSOR; /** * @private * We'll measure ourselves once and then store the results here * for the lifetime of the DividedBox. */ private var dbMinWidth:Number; private var dbMinHeight:Number; private var dbPreferredWidth:Number; private var dbPreferredHeight:Number; /** * @private */ private var layoutStyleChanged:Boolean = false; /** * @private */ private var _resizeToContent:Boolean = false; /** * @private * Number of children with their includeInLayout set to true. The rest of * the children don't count. */ private var numLayoutChildren:int = 0; //-------------------------------------------------------------------------- // // Overridden Properties // //-------------------------------------------------------------------------- /** * @private */ // override public function set moduleFactory(moduleFactory:IFlexModuleFactory):void // { // super.moduleFactory = moduleFactory; // // styleManager.registerSizeInvalidatingStyle(""dividerAffordance""); // styleManager.registerSizeInvalidatingStyle(""dividerThickness""); // } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // direction //---------------------------------- /** * @private */ override public function set direction(value:String):void { if (super.direction != value) { super.direction = value; // Need to invalidate all our dividers // if (dividerLayer) // { // for (var i:int = 0; i < dividerLayer.numChildren; i++) // getDividerAt(i).invalidateDisplayList(); // } } } //---------------------------------- // dividerClass //---------------------------------- /** * The class for the divider between the children. * * @default mx.containers.dividedBoxClasses.BoxDivider * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // protected var dividerClass:Class = BoxDivider; //---------------------------------- // liveDragging //---------------------------------- // [Inspectable(category=""General"")] /** * If true, the children adjacent to a divider * are continuously resized while the user drags it. * If false, they are not resized * until the user releases the divider. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public var liveDragging:Boolean = false; //---------------------------------- // numDividers //---------------------------------- /** * The number of dividers. * The count is always numChildren - 1. * * @return The number of dividers. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get numDividers():int { // if (dividerLayer) // if (!liveDragging && activeDivider) // return dividerLayer.numChildren-1; // else // return dividerLayer.numChildren; // else // return 0; trace(""numDividers not implemented""); return 0; } //---------------------------------- // resizeToContent //---------------------------------- /** * If true, the DividedBox automatically resizes to the size * of its children. * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function get resizeToContent():Boolean { return _resizeToContent; } /** * @private */ public function set resizeToContent(value:Boolean):void { if (value != _resizeToContent) { _resizeToContent = value; if (value) invalidateSize(); } } //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private * Override of the measure method of Box. * *

    This function is almost identical to the Box version except * that more extensive testing of the min, max * boundary conditions is performed. This is because the DividedBox allows * default values to be less than the min value of a control.

    */ // override protected function measure():void // { // super.measure(); // // // We only measure ourselves once, since as we change the // // size of children, they in turn change the preferred sizes // // // // We need to copy the cached values into the measured fields // // again to handle the case where scaleX or scaleY is not 1.0. // // When the ViewStack is zoomed, code in UIComponent.measureSizes // // scales the measuredWidth/Height values every time that // // measureSizes is called. (Bug 100749) // if (!isNaN(dbPreferredWidth) && !_resizeToContent && !layoutStyleChanged) // { // measuredMinWidth = dbMinWidth; // measuredMinHeight = dbMinHeight; // measuredWidth = dbPreferredWidth; // measuredHeight = dbPreferredHeight; // return; // } // // layoutStyleChanged = false; // // var isVertical:Boolean = this.isVertical(); // var minWidth:Number = 0; // var minHeight:Number = 0; // var preferredWidth:Number = 0; // var preferredHeight:Number = 0; // // var n:int = numChildren; // for (var i:int = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // var prefW:Number = child.getExplicitOrMeasuredWidth(); // var prefH:Number = child.getExplicitOrMeasuredHeight(); // // var minW:Number = child.minWidth; // var minH:Number = child.minHeight; // // var wFlex:Boolean = !isNaN(child.percentWidth); // var hFlex:Boolean = !isNaN(child.percentHeight); // // // Make sure we take the lowest of the low, since pref < min. // var smallestMinW:Number = Math.min(prefW, minW); // var smallestMinH:Number = Math.min(prefH, minH); // // if (isVertical) // { // minWidth = Math.max(wFlex ? minW : prefW, minWidth); // preferredWidth = Math.max(prefW, preferredWidth); // minHeight += hFlex ? smallestMinH : prefH; // preferredHeight += prefH; // } // else // { // minWidth += wFlex ? smallestMinW : prefW; // preferredWidth += prefW; // minHeight = Math.max(hFlex ? minH : prefH, minHeight); // preferredHeight = Math.max(prefH, preferredHeight); // } // } // // var wPadding:Number = layoutObject.widthPadding(numLayoutChildren); // var hPadding:Number = layoutObject.heightPadding(numLayoutChildren); // // measuredMinWidth = dbMinWidth = minWidth + wPadding; // measuredMinHeight = dbMinHeight = minHeight + hPadding; // measuredWidth = dbPreferredWidth = preferredWidth + wPadding; // measuredHeight = dbPreferredHeight = preferredHeight + hPadding; // } /** * @private */ // override protected function updateDisplayList(unscaledWidth:Number, // unscaledHeight:Number):void // { // var n:int; // var i:int; // // // This method gets called while dragging a divider, // // but we don't want to do anything then. // if (!liveDragging && activeDivider) // { // n = numChildren; // for (i = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // // Clear out measured min/max // // so super.layout() doesn't use them. // child.measuredMinWidth = 0; // child.measuredMinHeight = 0; // } // return; // } // // // Before we allow layout, let's clear out any measured min // // values of our children so that they don't restrict us. // // We only honour explicitly set mins/maxs. // // We also try to remove any excess space, but tweaking // // the % values on the flexible components. // preLayoutAdjustment(); // // // Let Box lay out the children. // super.updateDisplayList(unscaledWidth, unscaledHeight); // // postLayoutAdjustment(); // // // Lay out the dividers. // if (!dividerLayer) // return; // // var vm:EdgeMetrics = viewMetrics; // // dividerLayer.x = vm.left; // dividerLayer.y = vm.top; // // var prevChild:IUIComponent = null; // var dividerIndex:int = 0; // n = numChildren; // for (i = 0; i < n; i++) // { // child = UIComponent(getChildAt(i)); // if (child.includeInLayout) // { // if (prevChild) // { // layoutDivider(dividerIndex, unscaledWidth, unscaledHeight, prevChild, child); // dividerIndex++; // } // prevChild = child; // } // } // } /** * @private */ // override protected function scrollChildren():void // { // super.scrollChildren(); // // // Scroll divider layer. // if (contentPane && dividerLayer) // dividerLayer.scrollRect = contentPane.scrollRect; // } //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * Returns a reference to the specified BoxDivider object * in this DividedBox container or null if it doesn't exist. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @return A BoxDivider object. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public function getDividerAt(i:int):BoxDivider // { // if (dividerLayer) { // // Check whether this is a valid divider index. // if (i < 0 || i >= dividerLayer.numChildren) // return null; // else // return BoxDivider(dividerLayer.getChildAt(i)); // } // else { // return null; // } // } /** * Move a specific divider a given number of pixels. * * @param i Zero-based index of a divider, counting from * the left for a horizontal DividedBox, * or from the top for a vertical DividedBox. * * @param amt The number of pixels to move the divider. * A negative number can be specified in order to move * a divider up or left. The divider movement is * constrained in the same manner as if a user * had moved it. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ // public function moveDivider(i:int, amt:Number):void // { // // Check whether this is a valid divider index. // if (i < 0 || i >= numDividers) // return; // // // Make sure the user is not currently dragging. // if (activeDividerIndex >= 0) // return; // // // We have to first hit the children if we haven't // // yet done so since the first movement . // // // Mimic a divider moving. // activeDividerIndex = i; // // // Store away child sizes, // // then determine the limits on our movement. // cacheChildSizes(); // computeMinAndMaxDelta(); // dragDelta = limitDelta(amt); // // // Now update the children sizes accordingly. // adjustChildSizes(); // // invalidateSize(); // invalidateDisplayList(); // // // Reset the divider tracking stuff. // resetDividerTracking(); // } /** * @private */ // private function createDivider(i:int):BoxDivider // { // // Create separate layer for holding divider objects. // if (!dividerLayer) // { // dividerLayer = UIComponent(rawChildren.addChild(new UIComponent())); // } // // var divider:BoxDivider = BoxDivider(new dividerClass()); // dividerLayer.addChild(divider); // // // if we are creating the active divider bring the divider layer // // to the top most so that users can see the divider line over // // the other children // if (i == PROXY_DIVIDER_INDEX) // { // rawChildren.setChildIndex(dividerLayer, // rawChildren.numChildren-1); // } // // // Tell BoxDivider to use DividedBox's styles, // // unless we are sliding the divider; in that case, // // use the styles of the divider we are sliding. // var basedOn:IFlexDisplayObject = (i == PROXY_DIVIDER_INDEX) ? // getDividerAt(activeDividerIndex) : // this; // // divider.styleName = basedOn; // // divider.owner = this; // // return divider; // } /** * @private */ private function layoutDivider(i:int, unscaledWidth:Number, unscaledHeight:Number, prevChild:IUIComponent, nextChild:IUIComponent):void { // The mouse-over thickness of the divider is normally determined // by the dividerAffordance style, and the visible thickness is // normally determined by the dividerThickness style, assuming that // the relationship thickness <= affordance <= gap applies. But if // one of the other five orderings applies, here is a table of what // happens: // // divider divider horizontalGap/ dividerWidth/ visible width/ // Thickness Affordance verticalGap dividerHeight visible height // // 4 6 8 6 4 // 4 8 6 6 4 // 6 4 8 6 6 // 6 8 4 4 4 // 8 4 6 6 6 // 8 6 4 4 4 // var divider:BoxDivider = BoxDivider(getDividerAt(i)); // // var vm:EdgeMetrics = viewMetrics; // // var verticalGap:Number = getStyle(""verticalGap""); // var horizontalGap:Number = getStyle(""horizontalGap""); // // var thickness:Number = divider.getStyle(""dividerThickness""); // var affordance:Number = divider.getStyle(""dividerAffordance""); // // if (isVertical()) // { // var dividerHeight:Number = affordance; // // dividerHeight is the mouse-over height, // // not necessarily the visible height. // // // The specified affordance should be greater than the thickness. // // But if it isn't, use the thickness instead to determine the // // divider height. // if (dividerHeight < thickness) // dividerHeight = thickness; // // // Don't let the divider overlap the children. // if (dividerHeight > verticalGap) // dividerHeight = verticalGap; // // divider.setActualSize(unscaledWidth - vm.left - vm.right, dividerHeight); // // divider.move(vm.left, // Math.round((prevChild.y + prevChild.height + // nextChild.y - dividerHeight) / 2)); // } // else // { // var dividerWidth:Number = affordance; // // dividerWidth is the mouse-over width, // // not necessarily the visible width. // // // The specified affordance should be greater than the thickness. // // But if it isn't, use the thickness instead to determine the // // divider width. // if (dividerWidth < thickness) // dividerWidth = thickness; // // // Don't let the divider overlap the children. // if (dividerWidth > horizontalGap) // dividerWidth = horizontalGap; // // divider.setActualSize(dividerWidth, unscaledHeight - vm.top - vm.bottom); // // divider.move(Math.round((prevChild.x + prevChild.width + // nextChild.x - dividerWidth) / 2), // vm.top); // } // // divider.invalidateDisplayList(); } /** * @private */ // mx_internal function changeCursor(divider:BoxDivider):void // { // if (cursorID == CursorManager.NO_CURSOR) // { // // If a cursor skin has been set for the specified BoxDivider, // // use it. Otherwise, use the cursor skin for the DividedBox. // var cursorClass:Class = isVertical() ? // getStyle(""verticalDividerCursor"") as Class : // getStyle(""horizontalDividerCursor"") as Class; // // cursorID = cursorManager.setCursor(cursorClass, // CursorManagerPriority.HIGH, 0, 0); // } // } /** * @private */ // mx_internal function restoreCursor():void // { // if (cursorID != CursorManager.NO_CURSOR) // { // cursorManager.removeCursor(cursorID); // cursorID = CursorManager.NO_CURSOR; // } // } /** * @private */ // mx_internal function getDividerIndex(divider:BoxDivider):int // { // var n:int = numChildren; // for (var i:int = 0; i < n - 1; i++) // { // if (getDividerAt(i) == divider) // return i; // } // return -1; // } /** * @private */ // private function getMousePosition(event:MouseEvent):Number // { // var point:Point = new Point(event.stageX, event.stageY); // point = globalToLocal(point); // return isVertical() ? point.y : point.x; // } /** * @private */ // mx_internal function startDividerDrag(divider:BoxDivider, // trigger:MouseEvent):void // { // // Make sure the user is not currently dragging. // if (activeDividerIndex >= 0) // return; // // activeDividerIndex = getDividerIndex(divider); // // var event:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_PRESS); // event.dividerIndex = activeDividerIndex; // dispatchEvent(event); // // if (liveDragging) // activeDivider = divider; // else // { // activeDivider = createDivider(PROXY_DIVIDER_INDEX); // activeDivider.visible = false; // activeDivider.state = DividerState.DOWN; // activeDivider.setActualSize(divider.width, divider.height); // activeDivider.move(divider.x, divider.y); // activeDivider.visible = true; // divider.state = DividerState.UP; // } // // if (isVertical()) // activeDividerStartPosition = activeDivider.y; // else // activeDividerStartPosition = activeDivider.x; // // dragStartPosition = getMousePosition(trigger); // dragDelta = 0; // // cacheChildSizes(); // adjustChildSizes(); // // computeMinAndMaxDelta(); // // systemManager.getSandboxRoot().addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); // systemManager.deployMouseShields(true); // } /** * @private * Store away some important information about * each child for us to use while we move the divider. */ // private function cacheSizes():void // { // oldChildSizes = []; // empty array // // var vertical:Boolean = isVertical(); // // var smallest:Number = Number.MAX_VALUE; // use a big number // // var n:int = numChildren; // for (var i:int = 0; i < n; i++) // { // var child:IUIComponent = getLayoutChildAt(i); // if (!child.includeInLayout) // continue; // // var sz:Number = vertical ? child.height : child.width; // // var mx:Number = vertical ? child.maxHeight : child.maxWidth; // // var umn:Number = vertical ? // child.explicitMinHeight : // child.explicitMinWidth; // avoid measured values // // // A NaN min means 0. // var mn:Number = (isNaN(umn)) ? 0 : umn; // // // Compute these for later use. // var dMin:Number = Math.max(0, sz - mn); // var dMax:Number = Math.max(0, mx - sz); // // if (sz > 0 && sz < smallest) // smallest = sz; // // oldChildSizes.push(new ChildSizeInfo(sz, mn, mx, dMin, dMax)); // } // // // Remember the smallest child size we saw. // oldChildSizes.push(new ChildSizeInfo((smallest == Number.MAX_VALUE) ? 1 : smallest)); // } /** * @private */ // private function cacheChildSizes():void // { // oldChildSizes = []; // clear or store // // cacheSizes(); // } /** * @private */ // private function mouseMoveHandler(event:MouseEvent):void // { // dragDelta = limitDelta(getMousePosition(event) - dragStartPosition); // // var dividerEvent:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_DRAG); // dividerEvent.dividerIndex = activeDividerIndex; // dividerEvent.delta = dragDelta; // dispatchEvent(dividerEvent); // // if (liveDragging) // { // adjustChildSizes(); // // invalidateDisplayList(); // // updateDisplayList(unscaledWidth, unscaledHeight); // } // else // { // if (isVertical()) // activeDivider.move(0, activeDividerStartPosition + dragDelta); // else // activeDivider.move(activeDividerStartPosition + dragDelta, 0); // } // } /** * @private * * @param trigger May be null if the event is not a MouseEvent but * a mouse event from another sandbox. */ // mx_internal function stopDividerDrag(divider:BoxDivider, // trigger:MouseEvent):void // { // if (trigger) // dragDelta = limitDelta(getMousePosition(trigger) - dragStartPosition); // // var event:DividerEvent = // new DividerEvent(DividerEvent.DIVIDER_RELEASE); // event.dividerIndex = activeDividerIndex; // event.delta = dragDelta; // dispatchEvent(event); // // if (!liveDragging) // { // if (dragDelta == 0) // getDividerAt(activeDividerIndex).state = DividerState.OVER; // // if (activeDivider) // dividerLayer.removeChild(activeDivider); // activeDivider = null; // // adjustChildSizes(); // // invalidateSize(); // invalidateDisplayList(); // } // // resetDividerTracking(); // systemManager.getSandboxRoot().removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler, true); // systemManager.deployMouseShields(false); // } /** * @private */ // private function resetDividerTracking():void // { // activeDivider = null; // activeDividerIndex = -1; // activeDividerStartPosition = NaN; // dragStartPosition = NaN; // dragDelta = NaN; // oldChildSizes = null; // minDelta = NaN; // maxDelta = NaN; // } /** * @private * Determine the maximum amount of movement that * a divider, i, can move both up and down. * * We base this calculation on the amount of * travel that each divider supports, assuming * that as one divider reaches its limits, the next * divider will move. In this way dividers will * cascade. */ // private function computeAllowableMovement(at:int):void // { // // We break the computation into two loops, // // so that we can calc min and max travel // // independently as one would move the divider // // either up or down. // var deltaMinAbove:Number = 0; // var deltaMaxAbove:Number = 0; // var deltaMinBelow:Number = 0; // var deltaMaxBelow:Number = 0; // // var n:int = numLayoutChildren; // var i:int; // var child:ChildSizeInfo; // // if (at < 0) // return; // // for (i = at; i >= 0; i--) // { // child = ChildSizeInfo(oldChildSizes[i]); // // deltaMinAbove += (dontCoalesceDividers && deltaMinAbove) ? // 0 : child.deltaMin; // // deltaMaxAbove += (dontCoalesceDividers && deltaMaxAbove) ? // 0 : child.deltaMax; // } // // for (i = at + 1; i < n; i++) // { // child = ChildSizeInfo(oldChildSizes[i]); // // deltaMinBelow += (dontCoalesceDividers && deltaMinBelow) ? // 0 : child.deltaMin; // // deltaMaxBelow += (dontCoalesceDividers && deltaMaxBelow) ? // 0 : child.deltaMax; // } // // // Now the maximum movement we can have if // // the divider is moved up is equal to the // // smaller of how much we can shrink all // // components above our divider or the // // maximum of how much the components below // // our divider can grow. Similarly for the // // divider moving in the opposite direction. // var deltaUp:Number = Math.min(deltaMinAbove, deltaMaxBelow); // var deltaDn:Number = Math.min(deltaMinBelow, deltaMaxAbove); // // // deltaUp needs to be in -ve in order for our // // update logic to work // minDelta = -deltaUp; // maxDelta = deltaDn; // } /** * @private */ // private function computeMinAndMaxDelta():void // { // computeAllowableMovement(activeDividerIndex); // } /** * @private */ // private function limitDelta(delta:Number):Number // { // if (delta < minDelta) // delta = minDelta; // else if (delta > maxDelta) // delta = maxDelta; // // // Make sure it is not fractional, // // otherwise we lose pixels. (Bug 87339) // delta = Math.round(delta); // return delta; // } /** * @private * We distribute the delta space in the same * fashion that we calculated it. That is we * start at the divider and give out space * until we hit a limit on the component or * we run out of space to distribute. * We need to do this in both directions since * in one direction we are shrinking and * in the other we are growing. */ // private function distributeDelta():void // { // // if there is no movement of divider we need not // // do any child resizing. // if (!dragDelta) // return; // // var vertical:Boolean = isVertical(); // var n:int = numLayoutChildren; // var k:int = activeDividerIndex; // var smallest:Number = oldChildSizes[n].size - // Math.abs(dragDelta); // smallest possible child size // // if (smallest <= 0 || isNaN(smallest)) // smallest = 1; // // var i:int; // var size:ChildSizeInfo; // var move:Number; // var newSize:Number; // var child:IUIComponent; // var childSize:Number; // // // Find the index of the child before the active divider // var activeDividerChildIndex:int = -1; // var dividerIndex:int = -1; // while (dividerIndex < activeDividerIndex) // { // if (UIComponent(getChildAt(++activeDividerChildIndex)).includeInLayout) // ++dividerIndex; // } // // // Distribute space starting from the center and // // moving upwards. // var curChildIndex:int = activeDividerChildIndex; // var amt:Number = dragDelta; // for (i = k; i >= 0; i--) // { // // If dragDelta -ve => shrink upper components // // otherwise grow them. // size = ChildSizeInfo(oldChildSizes[i]); // move = (amt < 0) ? // -Math.min(-amt, size.deltaMin) : // Math.min(amt, size.deltaMax); // // // Adjust the component and reduce the remaining delta // newSize = size.size + move; // amt -= move; // // // Find the previous child included in the layout // do // { // child = IUIComponent(getChildAt(curChildIndex--)); // } // while (!child.includeInLayout); // // // Adjust the child size. // childSize = (newSize / smallest) * 100; // // if (vertical) // child.percentHeight = childSize; // else // child.percentWidth = childSize; // // // Force a re-measure. // if (child is IInvalidating) // IInvalidating(child).invalidateSize(); // } // // // assert(amt == 0) // // // Now do the same distribution but moving downwards. // curChildIndex = activeDividerChildIndex + 1; // amt = dragDelta; // for (i = k + 1; i < n; i++) // { // // If dragDelta -ve => grow lower components // // otherwise shrink them. // size = ChildSizeInfo(oldChildSizes[i]); // move = (amt < 0) ? // Math.min(-amt, size.deltaMax) : // -Math.min(amt, size.deltaMin); // // // Adjust the component and reduce the remaining delta. // newSize = size.size + move; // amt += move; // // // Find the next child included in the layout // do // { // child = IUIComponent(getChildAt(curChildIndex++)); // } // while (!child.includeInLayout); // // childSize = (newSize / smallest) * 100; // // if (vertical) // child.percentHeight = childSize; // else // child.percentWidth = childSize; // // // Force a re-measure. // if (child is IInvalidating) // IInvalidating(child).invalidateSize(); // } // } /** * @private * For 1.5 we normalize all children to the smallest one * So that we can remove n-1 children and still guarantee * one child can consume 100%. * Also we support the concept of fixed sized children, * which allows us to have one or more children be rigid * in the DividedBox in this case, the dividers above * and below the fixed component move in unison. */ // private function adjustChildSizes():void // { // distributeDelta(); // } /** * @private * Algorithm employed pre-layout to ensure that * we don't leave any dangling space and to ensure * that only explicit min/max values are honored. * * We first compute the sum of %'s across all * children to ensure that we have at least 100%. * If so, we are done. If not, then we attempt * to attach the remaining amount to the last * component, if not, then we distribute the * percentages evenly across all % components. * */ // private function preLayoutAdjustment():void // { // // Calculate the total % // var vertical:Boolean = isVertical(); // // var totalPerc:Number = 0; // var percCount:Number = 0; // // var n:int = numChildren; // var i:int; // var child:IUIComponent; // var perc:Number; // // for (i = 0; i < n; i++) // { // child = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // // Clear out measured min/max // // so super.layout() doesn't use them. // child.measuredMinWidth = 0; // child.measuredMinHeight = 0; // // perc = vertical ? child.percentHeight : child.percentWidth; // // if (!isNaN(perc)) // { // totalPerc += perc; // percCount++; // } // } // // // during preLayoutAdjustment, we make some changes to the children's // // widths and heights. We keep track of the original values in postLayoutChanges // // so we can later go back and reset them so another layout pass is working // // with the correct values rather than these modified values. // postLayoutChanges = []; // var changeObject:Object; // // // No flexible children, so we make the last one 100%. // if (totalPerc == 0 && percCount == 0) // { // // Everyone is fixed and we can give 100% to the last // // included in layout one without concern. // for (i = n-1; i >= 0; i--) // { // child = UIComponent(getChildAt(i)); // if (child.includeInLayout) // { // // create a changeObject to keep track of the original values // // that this child had for width and height // changeObject = {child: child}; // if (vertical) // { // // we know there's no percentHeight originally // if (child.explicitHeight) // changeObject.explicitHeight = child.explicitHeight; // else // changeObject.percentHeight = NaN; // // child.percentHeight = 100; // } // else // { // // we know there's no percentWidth originally // if (child.explicitWidth) // changeObject.explicitWidth = child.explicitWidth; // else if (child.percentWidth) // changeObject.percentWidth = NaN; // // child.percentWidth = 100; // } // postLayoutChanges.push(changeObject); // break; // } // } // } // else if (totalPerc < 100) // { // // We have some %s but they don't total to 100, so lets // // distribute the delta across all of them and in the // // meantime normalize all %s to unscaledHeight/Width. // // The normalization takes care of the case where any one // // of the components hits a min/max limit on their size, // // which could result in the others filling less than 100%. // var delta:Number = Math.ceil((100 - totalPerc) / percCount); // for (i = 0; i < n; i++) // { // child = getLayoutChildAt(i); // // if (!child.includeInLayout) // continue; // // changeObject = {child: child}; // // if (vertical) // { // perc = child.percentHeight; // if (!isNaN(perc)) // { // changeObject.percentHeight = child.percentHeight; // postLayoutChanges.push(changeObject); // // child.percentHeight = (perc + delta) * unscaledHeight; // } // } // else // { // perc = child.percentWidth; // if (!isNaN(perc)) // { // changeObject.percentWidth = child.percentWidth; // postLayoutChanges.push(changeObject); // // child.percentWidth = (perc + delta) * unscaledWidth; // } // } // } // } // // // OK after all this magic we still can't guarantee that the space is // // entirely filled. For example, all percent components hit their max // // values. In this case, the layout will include empty space at the end, // // and once the divider is touched, the non-percent based components // // will be converted into percent based ones and fill the remaining // // space. It seems to me that this scenario is highly unlikely. // // Thus I've choosen the route of stretching the percent based // // components and not touching the explicitly sized or default // // sized ones. // // // // Another option would be to stretch the default sized components // // either in addition to the percent based ones or instead of. // // This seemed a little odd to me as the user never indicated // // that these components are to be stretched initially, so in the end // // I choose to tweak the components that the user has indicated // // as being stretchable. // } /** * @private * During preLayoutAdjustment, we make some changes to the children's * widths and heights. We keep track of the original values in postLayoutChanges * so we can later go back and reset them so another layout pass is working * with the correct values rather than these modified values. */ // private var postLayoutChanges:Array; /** * @private * Post layout work. In preLayoutAdjustment() * sometimes we set a child's percentWidth/percentHeight. * postLayoutAdjustment() will reset the child's width or height * back to what it was. */ // private function postLayoutAdjustment():void // { // // each object has a child property and may have a set of width/height // // properties that it would like to be set // var len:int = postLayoutChanges.length; // for (var i:int = 0; i < len; i++) // { // var changeObject:Object = postLayoutChanges[i]; // // if (changeObject.percentWidth !== undefined) // changeObject.child.percentWidth = changeObject.percentWidth; // // if (changeObject.percentHeight !== undefined) // changeObject.child.percentHeight = changeObject.percentHeight; // // if (changeObject.explicitWidth !== undefined) // changeObject.child.explicitWidth = changeObject.explicitWidth; // // if (changeObject.explicitHeight !== undefined) // changeObject.child.explicitHeight = changeObject.explicitHeight; // } // postLayoutChanges = null; // } //-------------------------------------------------------------------------- // // Event handlers // //-------------------------------------------------------------------------- /** * @private */ // private function childAddHandler(event:ChildExistenceChangedEvent):void // { // var child:DisplayObject = event.relatedObject; // // child.addEventListener(""includeInLayoutChanged"", // child_includeInLayoutChangedHandler); // // if (!IUIComponent(child).includeInLayout) // return; // // numLayoutChildren++; // // if (numLayoutChildren > 1) // createDivider(numLayoutChildren - 2); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // } /** * @private */ // private function childRemoveHandler(event:ChildExistenceChangedEvent):void // { // var child:DisplayObject = event.relatedObject; // // child.removeEventListener(""includeInLayoutChanged"", // child_includeInLayoutChangedHandler); // // if (!IUIComponent(child).includeInLayout) // return; // // numLayoutChildren--; // // if (numLayoutChildren > 0) // dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // invalidateSize(); // } /** * @private * When a child's includeInLayout changes, we either remove or add a * divider. */ // private function child_includeInLayoutChangedHandler(event:Event):void // { // var child:UIComponent = UIComponent(event.target); // // if (child.includeInLayout && ++numLayoutChildren > 1) // createDivider(numLayoutChildren - 2); // // else if (!child.includeInLayout && --numLayoutChildren > 0) // dividerLayer.removeChild(getDividerAt(numLayoutChildren - 1)); // // // Clear the cached values so that we do another // // measurement pass. // dbMinWidth = NaN; // dbMinHeight = NaN; // dbPreferredWidth = NaN; // dbPreferredHeight = NaN; // invalidateSize(); // } } } //////////////////////////////////////////////////////////////////////////////// // // Helper class: ChildSizeInfo // //////////////////////////////////////////////////////////////////////////////// /** * @private */ //class ChildSizeInfo //{ // //-------------------------------------------------------------------------- // // // // Constructor // // // //-------------------------------------------------------------------------- // // /** // * @private // */ // public function ChildSizeInfo(size:Number, // min:Number = 0, max:Number = 0, // deltaMin:Number = 0, deltaMax:Number = 0) // { // super(); // // this.size = size; // this.min = min; // this.max = max; // this.deltaMin = deltaMin; // this.deltaMax = deltaMax; // } // // //-------------------------------------------------------------------------- // // // // Properties // // // //-------------------------------------------------------------------------- // // //---------------------------------- // // deltaMin // //---------------------------------- // // /** // * @private // */ // public var deltaMin:Number; // // //---------------------------------- // // deltaMax // //---------------------------------- // // /** // * @private // */ // public var deltaMax:Number; // // //---------------------------------- // // min // //---------------------------------- // // /** // * @private // */ // public var min:Number; // // //---------------------------------- // // max // //---------------------------------- // // /** // * @private // */ // public var max:Number; // // //---------------------------------- // // size // //---------------------------------- // // /** // * @private // */ // public var size:Number; //} ",12396,False,2350.5641418932464,median "//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the ""License""); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ""AS IS"" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package mx.controls.advancedDataGridClasses { /* import flash.display.DisplayObject; import flash.events.Event; */ import mx.controls.AdvancedDataGrid; import mx.controls.TextInput; import mx.controls.dataGridClasses.DataGridColumn; import mx.core.ClassFactory; import mx.core.IFactory; import mx.core.mx_internal; import mx.utils.StringUtil; import org.apache.royale.core.UIBase; import org.apache.royale.events.Event; use namespace mx_internal; //-------------------------------------- // Styles //-------------------------------------- //include ""../../styles/metadata/TextStyles.as""; /** * The background color of the column. * The default value is undefined, which means it uses the value of the * backgroundColor style of the associated AdvancedDataGrid control. * The default value for the AdvancedDataGrid control is 0xFFFFFF. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ [Style(name=""backgroundColor"", type=""uint"", format=""Color"", inherit=""no"")] /** * The name of a CSS style declaration for controlling other aspects of * the appearance of the column headers. * The default value is undefined, which means it uses the value of the * headerStyleName style of the associated AdvancedDataGrid control. * The default value for the AdvancedDataGrid control is * "".advancedDataGridStyles"". * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ [Style(name=""headerStyleName"", type=""String"", inherit=""no"")] /** * The number of pixels between the container's left border and its content * area. * There is no default value for this style. * An item renderer's setting of the paddingLeft property * is used to determine the default. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //[Style(name=""paddingLeft"", type=""Number"", format=""Length"", inherit=""no"")] /** * The number of pixels between the container's right border and its content * area. * There is no default value for this style. * An item renderer's setting of the paddingRight property * is used to determine the default. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //[Style(name=""paddingRight"", type=""Number"", format=""Length"", inherit=""no"")] /** * The AdvancedDataGridColumn class describes a column in an AdvancedDataGrid control. * There is one AdvancedDataGridColumn per displayable column, even if a column * is hidden or off-screen. * The data provider items of an AdvancedDataGrid control * can contain properties that are not displayed, * and therefore, do not need an AdvancedDataGridColumn. * An AdvancedDataGridColumn allows specification of the color and font of the text * in a column; specification of what kind of component displays the data for the column; * specification of whether the column is editable, sortable, or resizeable; * and specification of the text for the column header. * *

    Notes:

      *
    • An AdvancedDataGridColumn only holds information about a column; * it is not the parent of the item renderers in the column.
    • *
    • If you specify an AdvancedDataGridColumn class without a dataField * property, you must specify a sortCompareFunction * property. Otherwise, sort operations may cause run-time errors.
    *

    * * @mxml * *

    You use the <mx.AdvancedDataGridcolumn> tag to configure a column * of a AdvancedDataGrid control. * You specify the <mx.AdvancedDataGridcolumn> tag as a child * of the columns property in MXML. * The <mx.AdvancedDataGridcolumn> tag inherits all of the * tag attributes of its superclass, and adds the following tag attributes:

    * *
     *  <mx:AdvancedDataGridColumn
     *  Properties 
     *    dataField=""No default""
     *    dataTipField=""No default""
     *    dataTipFunction=""No default""
     *    editable=""true|false""
     *    editorDataField=""text""
     *    editorHeightOffset=""0""
     *    editorUsesEnterKey=""false|true""
     *    editorWidthOffset=""0""
     *    editorXOffset=""0""
     *    editorYOffset=""0""
     *    formatter=""null""
     *    headerRenderer=""AdvancedDataGridHeaderRenderer""
     *    headerText=""No default""
     *    headerWordWrap=""undefined""
     *    imeMode=""null""
     *    itemEditor=""TextInput""
     *    itemRenderer=""AdvancedDataGridItemRenderer""
     *    labelFunction=""No default""
     *    minWidth=""20""
     *    rendererIsEditor=""false|true""
     *    resizable=""true|false""
     *    showDataTips=""false|true""
     *    sortable=""true|false""
     *    sortCompareFunction=""No default""
     *    sortDescending=""false|true""
     *    styleFunction=""No default""
     *    visible=""true|false""
     *    width=""100""
     *    wordWrap=""false|true""
     * 
     *  Styles
     *    backgroundColor=""0xFFFFFF""
     *    color=""No default.""
     *    disabledColor=""0xAAB3B3""
     *    fontAntiAliasType=""advanced""
     *    fontFamily=""No default""
     *    fontGridFitType=""pixel""
     *    fontSharpness=""0""
     *    fontSize=""No default""
     *    fontStyle=""normal|italic""
     *    fontThickness=""0""
     *    fontWeight=""normal|bold""
     *    headerStyleName=""No default""
     *    kerning=""false|true""
     *    letterSpacing=""0""
     *    paddingLeft=""0""
     *    paddingRight=""0""
     *    textAlign=""right|center|left""
     *    textDecoration=""none|underline""
     *    textIndent=""0""
     *  />
     *  
    * * @see mx.controls.AdvancedDataGrid * * @see mx.styles.CSSStyleDeclaration * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 * @royalesuppresspublicvarwarning */ public class AdvancedDataGridColumn extends DataGridColumn {//extends CSSStyleDeclaration implements IIMESupport //include ""../../core/Version.as""; //-------------------------------------------------------------------------- // // Class variables // //-------------------------------------------------------------------------- //---------------------------------- // embeddedFontRegistry //---------------------------------- // private static var noEmbeddedFonts:Boolean; /** * @private * Storage for the embeddedFontRegistry property. * This gets initialized on first access, * not at static initialization time, in order to ensure * that the Singleton registry has already been initialized. */ // private static var _embeddedFontRegistry:IEmbeddedFontRegistry; /** * @private * A reference to the embedded font registry. * Single registry in the system. * Used to look up the moduleFactory of a font. */ /* private static function get embeddedFontRegistry():IEmbeddedFontRegistry { if (!_embeddedFontRegistry && !noEmbeddedFonts) { try { _embeddedFontRegistry = IEmbeddedFontRegistry( Singleton.getInstance(""mx.core::IEmbeddedFontRegistry"")); } catch (e:Error) { noEmbeddedFonts = true; } } return _embeddedFontRegistry; } */ private static var _defaultItemEditorFactory:IFactory; mx_internal static function get defaultItemEditorFactory():IFactory { if (!_defaultItemEditorFactory) _defaultItemEditorFactory = new ClassFactory(TextInput); return _defaultItemEditorFactory; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. * * @param columnName The name of the field in the data provider * associated with the column, and the text for the header cell of this * column. This is equivalent to setting the dataField * and headerText properties. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public function AdvancedDataGridColumn(columnName:String = null) { super(columnName); /* if (columnName) { dataField = columnName; headerText = columnName; } */ } //-------------------------------------------------------------------------- // // Variables // //-------------------------------------------------------------------------- // mx_internal var list:UIBase; //BaseEx; /** * @private */ // mx_internal var explicitWidth:Number; /** * @private * Holds the last recorded value of the module factory used to create the font. */ // private var oldEmbeddedFontContext:IFlexModuleFactory = null; /** * @private * * true if font properties do not need to be set. */ // private var fontPropertiesSet:Boolean = false; /** * @private * True if createInFontContext has been called. */ // private var hasFontContextBeenSaved:Boolean = false; // preferred width is the number we should use when measuring // regular width will be changed if we shrink columns to fit. // mx_internal var preferredWidth:Number = 100; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- // ------------------------------------------------ // fontWeight // ------------------------------------------------ public function get fontWeight():String { return ""normal""; } public function set fontWeight(value:String):void { } // ------------------------------------------------ // fontSize // ------------------------------------------------ public function get fontSize():Number { return 11; } public function set fontSize(value:Number):void { } // ------------------------------------------------ // color // ------------------------------------------------ public function get color():uint { return 0x0B333C; } public function set color(value:uint):void { } //---------------------------------- // sortDescending //---------------------------------- /** * Indicates whether the column sort is * in ascending order, false, * or descending order, true. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ // public var sortDescending:Boolean = false; //---------------------------------- // dataTipField //---------------------------------- /** * @private * Storage for the dataTipField property. */ /* private var _dataTipField:String; [Bindable(""dataTipFieldChanged"")] [Inspectable(category=""Advanced"", defaultValue=""label"")] */ /** * The name of the field in the data provider to display as the data tip. * By default, the AdvancedDataGrid control looks for a property named * label on each data provider item and displays it. * However, if the data provider does not contain a label * property, you can set the dataTipField property to * specify a different property. * For example, you could set the value to ""FullName"" when a user views a * set of people's names included from a database. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function get dataTipField():String { return _dataTipField; } */ /** * @private */ /* public function set dataTipField(value:String):void { _dataTipField = value; if (owner) { owner.invalidateList(); } dispatchEvent(new Event(""dataTipChanged"")); } */ //---------------------------------- // dataTipFunction //---------------------------------- /** * @private * Storage for the dataTipFunction property. */ /* private var _dataTipFunction:Function; [Bindable(""dataTipFunctionChanged"")] [Inspectable(category=""Advanced"")] */ /** * Specifies a callback function to run on each item of the data provider * to determine its data tip. * This property is used by the itemToDataTip() method. * *

    By default, the control looks for a property named label * on each data provider item and displays it as its dataTip. * However, some data providers do not have a label property * or another property that you can use for displaying data * in the rows. * For example, you might have a data provider that contains a lastName * and firstName fields, but you want to display full names as the dataTip. * You can specify a function to the dataTipFunction property * that returns a single String containing the value of both fields. You * can also use the dataTipFunction property for handling * formatting and localization.

    * *

    The function must take a single Object parameter, and return a String. * For the header cell of a column, the Object parameter is of type AdvancedDataGridColumn. * For table cells, the Object parameter contains the data provider element for the cell.

    * *

    Shown below is an example implementation of the function. * For the header cell, return ""Column Name"". * For the table cells, return the name property of the Object:

    *
         *  private function tipFunc(value:Object):String
         *  {
         *      if (value is AdvancedDataGridColumn)
         *          return ""Column Name"";
         *                 
         *      // Use the 'name' property of the data provider element.
         *      return ""Name: "" + value[""name""];
         *  }
    * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function get dataTipFunction():Function { return _dataTipFunction; } */ /** * @private */ /* public function set dataTipFunction(value:Function):void { _dataTipFunction = value; if (owner) { owner.invalidateList(); } dispatchEvent(new Event(""labelFunctionChanged"")); } */ //---------------------------------- // draggable //---------------------------------- // [Inspectable(category=""General"")] /** * A flag that indicates whether the user is allowed to drag * the column to a new position * If true, the user can drag the * the column headers to a new position * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //public var draggable:Boolean = true; //---------------------------------- // editable //---------------------------------- //[Inspectable(category=""General"")] /** * A flag that indicates whether the items in the column are editable. * If true, and the AdvancedDataGrid's editable * property is also true, the items in a column are * editable and can be individually edited * by clicking an item or by navigating to the item with the * Tab and Arrow keys. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ //public var editable:Boolean = true; //---------------------------------- // itemEditor //---------------------------------- [Inspectable(category=""General"")] /** * A class factory for the instances of the item editor to use for the * column, when it is editable. * *

    The default value is the mx.controls.TextInput control.

    * * @see mx.controls.TextInput * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var itemEditor:IFactory = defaultItemEditorFactory; //---------------------------------- // editorDataField //---------------------------------- [Inspectable(category=""General"")] /** * The name of the property of the item editor that contains the new * data for the list item. * For example, the default itemEditor is * TextInput, so the default value of the editorDataField * property is ""text"", which specifies the * text property of the TextInput control. * * @default ""text"" * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorDataField:String = ""text""; //---------------------------------- // editorHeightOffset //---------------------------------- [Inspectable(category=""General"", defaultValue=""0"")] /** * The height of the item editor, in pixels, relative to the size of the * item renderer. This property can be used to make the editor overlap * the item renderer by a few pixels to compensate for a border around the * editor. * Note that changing these values while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorHeightOffset:Number = 0; //---------------------------------- // editorWidthOffset //---------------------------------- //[Inspectable(category=""General"", defaultValue=""0"")] /** * The width of the item editor, in pixels, relative to the size of the * item renderer. This property can be used to make the editor overlap * the item renderer by a few pixels to compensate for a border around the * editor. * Note that changing these values while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorWidthOffset:Number = 0; //---------------------------------- // editorXOffset //---------------------------------- // [Inspectable(category=""General"", defaultValue=""0"")] /** * The x location of the upper-left corner of the item editor, * in pixels, relative to the upper-left corner of the item. * This property can be used to make the editor overlap * the item renderer by a few pixels to compensate for a border around the * editor. * Note that changing these values while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorXOffset:Number = 0; //---------------------------------- // editorYOffset //---------------------------------- //[Inspectable(category=""General"", defaultValue=""0"")] /** * The y location of the upper-left corner of the item editor, * in pixels, relative to the upper-left corner of the item. * This property can be used to make the editor overlap * the item renderer by a few pixels to compensate for a border around the * editor. * Note that changing these values while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorYOffset:Number = 0; //---------------------------------- // editorUsesEnterKey //---------------------------------- //[Inspectable(category=""General"", defaultValue=""false"")] /** * A flag that indicates whether the item editor uses Enter key. * If true the item editor uses the Enter key and the * AdvancedDataGrid will not look for the Enter key and move the editor in * response. * Note that changing this value while the editor is displayed * will have no effect on the current editor, but will affect the next * item renderer that opens an editor. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public var editorUsesEnterKey:Boolean = false; //---------------------------------- // headerRenderer //---------------------------------- /** * @private * Storage for the headerRenderer property. */ private var _headerRenderer:IFactory; [Bindable(""headerRendererChanged"")] [Inspectable(category=""Other"")] /** * The class factory for item renderer instances that display the * column header for the column. * You can specify a drop-in item renderer, * an inline item renderer, or a custom item renderer component as the * value of this property. * *

    The default item renderer is the AdvancedDataGridItemRenderer class, * which displays the item data as text.

    * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ override public function get headerRenderer():IFactory { return _headerRenderer; } /** * @private */ override public function set headerRenderer(value:IFactory):void { _headerRenderer = value; // rebuild the headers /* if (owner) { owner.invalidateList(); owner.columnRendererChanged(this); } dispatchEvent(new Event(""headerRendererChanged"")); */ } //---------------------------------- // headerWordWrap //---------------------------------- /** * @private * Storage for the headerWordWrap property. */ private var _headerWordWrap:*; [Inspectable(category=""Advanced"")] /** * Set to true to wrap the text in the column header * if it does not fit on one line. * If undefined, the AdvancedDataGrid control's wordWrap property * is used. * This property overrides the headerWordWrap property of * the AdvancedDataGrid control. * * @default undefined * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public function get headerWordWrap():* { return _headerWordWrap; } /** * @private */ public function set headerWordWrap(value:*):void { _headerWordWrap = value; /* if (owner) { owner.invalidateList(); } */ } //---------------------------------- // enableIME //---------------------------------- /** * A flag that indicates whether the IME should * be enabled when the component receives focus. * * If an editor is up, it will set enableIME * accordingly. * * @langversion 3.0 * @playerversion Flash 10 * @playerversion AIR 1.5 * @productversion Flex 4 */ /* public function get enableIME():Boolean { return false; } */ //---------------------------------- // imeMode //---------------------------------- /** * @private * Storage for the imeMode property. */ /* private var _imeMode:String; [Inspectable(category=""Other"")] */ /** * Specifies the IME (input method editor) mode. * The IME mode enables users to enter text in Chinese, Japanese, and Korean. * Flex sets the IME mode when the itemFocusIn event occurs, * and sets it back * to the previous value when the itemFocusOut event occurs. * The flash.system.IMEConversionMode class defines constants for * the valid values for this property. * *

    The default value is null, in which case it uses the value of the * AdvancedDataGrid control's imeMode property.

    * * @see flash.system.IMEConversionMode * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function get imeMode():String { return _imeMode; } */ /** * @private */ /* public function set imeMode(value:String):void { _imeMode = value; } */ /* //---------------------------------- // resizable //---------------------------------- [Inspectable(category=""General"")] /!** * Set to true if the user is allowed to resize * the width of the column. * If true, the user can drag the grid lines between * the column headers to resize the column. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public var resizable:Boolean = true; //---------------------------------- // showDataTips //---------------------------------- /!** * @private * Storage for the showDataTips property. *!/ private var _showDataTips:*; [Inspectable(category=""Advanced"")] /!** * Set to true to show data tips in the column. * If true, datatips are displayed for text in the rows. Datatips * are tooltips designed to show the text that is too long for the row. * * @default false * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public function get showDataTips():* { return _showDataTips; } /!** * @private *!/ public function set showDataTips(value:*):void { _showDataTips = value; /!* if (owner) { owner.invalidateList(); } *!/ } //---------------------------------- // sortable //---------------------------------- [Inspectable(category=""General"")] /!** * Set to true to indicate that the user can click on the * header of this column to sort the data provider. * If this property and the AdvancedDataGrid sortableColumns property * are both true, the AdvancedDataGrid control dispatches a * headerRelease event when a user releases the mouse button * on this column's header. * If no other handler calls the preventDefault() method on * the headerRelease event, the dataField * property or sortCompareFunction in the column is used * to reorder the items in the data provider. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public var sortable:Boolean = true; //---------------------------------- // sortCompareFunction //---------------------------------- /!** * @private * Storage for the sortCompareFunction property. *!/ private var _sortCompareFunction:Function; [Bindable(""sortCompareFunctionChanged"")] [Inspectable(category=""Advanced"")] /!** * * A callback function that gets called when sorting the data in * the column. If this property is not specified, the sort tries * to use a basic string or number sort on the data. * If the data is not a string or number or if the dataField * property is not a valid property of the data provider, the sort does * not work or will generate an exception. * If you specify a value of the labelFunction property, * you typically also provide a function to the sortCompareFunction property, * unless sorting is not allowed on this column. * That means you specify a function when the value from the column's dataField * does not sort in the same way as the computed value from the labelFunction property. * *

    The AdvancedDataGrid control uses this function to sort the elements of the data * provider collection. The function signature of * the callback function takes two parameters and has the following form:

    * *
    mySortCompareFunction(obj1:Object, obj2:Object):int 
    * *

    obj1 — A data element to compare.

    * *

    obj2 — Another data element to compare with obj1.

    * *

    The function should return a value based on the comparison * of the objects:

    *
      *
    • -1 if obj1 should appear before obj2 in ascending order.
    • *
    • 0 if obj1 = obj2.
    • *
    • 1 if obj1 should appear after obj2 in ascending order.
    • *
    * *

    Note: The obj1 and * obj2 parameters are entire data provider elements and not * just the data for the item.

    * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public function get sortCompareFunction():Function { return _sortCompareFunction; } /!** * @private *!/ public function set sortCompareFunction(value:Function):void { _sortCompareFunction = value; // dispatchEvent(new Event(""sortCompareFunctionChanged"")); } */ //---------------------------------- // sortCompareType //---------------------------------- /** * @private */ //private var _sortCompareType:String; /** * @inheritDoc * * @langversion 3.0 * @playerversion Flash 11.8 * @playerversion AIR 3.8 * @productversion Flex 4.11 */ /* [Bindable(""sortCompareTypeChanged"")] public function get sortCompareType():String { return _sortCompareType; } */ /** * @private */ /* public function set sortCompareType(value:String):void { if (_sortCompareType != value) { _sortCompareType = value; dispatchEvent(new Event(""sortCompareTypeChanged"")); } } */ /* //---------------------------------- // visible //---------------------------------- /!** * @private * Storage for the visible property. *!/ private var _visible:Boolean = true; [Inspectable(category=""General"", defaultValue=""true"")] /!** * If true, the column is visible. * Set to false to hide the column. * * @default true * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 *!/ public function get visible():Boolean { return _visible; } /!** * @private *!/ public function set visible(value:Boolean):void { if (_visible != value) { _visible = value; if (owner) { (owner as AdvancedDataGrid).columnsInvalid(); // columns invisible at init don't get a dataprovider so // force assignment by faking a dp change (owner as AdvancedDataGrid).model.dispatchEvent(new Event(""dataProviderChanged"")); //owner.invalidateProperties(); //owner.invalidateSize(); //owner.invalidateList(); } } }*/ //---------------------------------- // styleFunction //---------------------------------- /** * @private */ private var _styleFunction:Function; /** * A callback function that is called when rendering each cell. * The signature of the function should be: * *
    function myStyleFunction(data:Object, column:AdvancedDataGridColumn):Object
    * *

    data - data object associated with the item being rendered.

    *

    column - AdvancedDataGridColumn instance with * which the item renderer is associated.

    * *

    The return value should be a object with styles as properties * having the required values. * For example:

    * *
    { color:0xFF0000, fontWeight:""bold"" }
    * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public function get styleFunction():Function { return _styleFunction; } /** * @private */ public function set styleFunction(value:Function):void { _styleFunction = value; /* if (owner) owner.invalidateDisplayList(); */ } //---------------------------------- // formatter //---------------------------------- /** * @private */ //private var _formatter:IFormatter; /** * An instance of a subclasses of mx.formatters.Formatter. * The control use this class to format the column text. * * @default null * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function get formatter():IFormatter { return _formatter; } */ /** * @private */ /* public function set formatter(value:IFormatter):void { _formatter = value; if (owner) owner.invalidateDisplayList(); } */ //-------------------------------------------------------------------------- // // Overridden methods // //-------------------------------------------------------------------------- /** * @private */ /* override mx_internal function addStyleToProtoChain( chain:Object, target:DisplayObject, filterMap:Object = null):Object { var parentGrid:AdvancedDataGridBaseEx = owner; var item:IListItemRenderer = IListItemRenderer(target); chain = super.addStyleToProtoChain(chain, target); // If the target data is a AdvancedDataGridColumn and has a data // field in its data, then it is a header so add the // AdvancedDataGrid.headerStyleName object to the head of the proto chain. if (item.data && (item.data is AdvancedDataGridColumn)) { var s:Object; var headerStyleName:Object = parentGrid.getStyle(""headerStyleName""); if (headerStyleName) { if (headerStyleName is String) { chain = addStylesToProtoChain(String(headerStyleName), chain, target); } if (headerStyleName is CSSStyleDeclaration) chain = headerStyleName.addStyleToProtoChain(chain, target); } headerStyleName = getStyle(""headerStyleName""); if (headerStyleName) { if (headerStyleName is String) { chain = addStylesToProtoChain(String(headerStyleName), chain, target); } if (headerStyleName is CSSStyleDeclaration) chain = headerStyleName.addStyleToProtoChain(chain, target); } } // save the current font context if (!fontPropertiesSet) { fontPropertiesSet = true; saveFontContext(owner ? owner.moduleFactory : null); } return chain; } */ /** * @private */ /* override public function setStyle(styleProp:String, value:*):void { fontPropertiesSet = false; var oldValue:Object = getStyle(styleProp); var regenerate:Boolean = false; // If this AdvancedDataGridColumn didn't previously have a factory, defaultFactory, or // overrides object, then this AdvancedDataGridColumn hasn't been added to the item // renderers proto chains. In that case, we need to regenerate all the item // renderers proto chains. if (factory == null && defaultFactory == null && !overrides && (oldValue !== value)) // must be !== { regenerate = true; } super.setLocalStyle(styleProp, value); // The default implementation of setStyle won't always regenerate // the proto chain when headerStyleName is set, and we need to make sure // that they are regenerated if (styleProp == ""headerStyleName"") { if (owner) { owner.regenerateStyleCache(true); owner.notifyStyleChangeInChildren(""headerStyleName"", true); } return; } if (owner) { if (regenerate) { owner.regenerateStyleCache(true); } if (hasFontContextChanged(owner.moduleFactory)) { owner.columnRendererChanged(this); } owner.invalidateList(); } } */ /** * @private */ /* override public function get specificity():int { // Return 10 as there is a sorting mechanism based on specificity now // and there could be ancestor specificity also!! return 10; } */ //-------------------------------------------------------------------------- // // Methods // //-------------------------------------------------------------------------- /** * @private * Internal function to allow the AdvancedDataGrid to set the width of the * column without locking it as an explicitWidth mx_internal function setWidth(value:Number):void { _width = value; } */ /** * @private * * Apply column's Formatter if present. * */ /* private function applyFormatting(data:String):String { if (formatter != null && data != null) { var label:String = formatter.format(data); // Silently ignore formatter errors. For example, errors occur when // the property corresponding to the dataField is not present in the // row object i.e. it'll be empty and it's not anybody's fault that // it's an error. const mxFormatter:Formatter = formatter as Formatter; if (mxFormatter && mxFormatter.error) return null; return label; } else { return data; } } */ /** * Returns the String that the item renderer displays for the given data object. * If the AdvancedDataGridColumn or its AdvancedDataGrid control * has a non-null labelFunction * property, it applies the function to the data object. * Otherwise, the method extracts the contents of the field specified by the * dataField property, or gets the string value of the data object. * If the method cannot convert the parameter to a String, it returns a * single space. * * @param data Object to be rendered. * * @param withFormatting It true specifies to return * the String with any formatting applied to it. * * @return Displayable String based on the data. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function itemToLabel(data:Object, withFormatting:Boolean=true):String { var label:String = itemToLabelWithoutFormatting(data); if (withFormatting) return applyFormatting(label); return label; } */ /** * @private * * This is the original AdvancedDataGrid.itemToLabel() that has been wrapped with applyFormatting() * */ /* private function itemToLabelWithoutFormatting(data:Object):String { var headerInfo:AdvancedDataGridHeaderInfo = owner.mx_internal::getHeaderInfo(this); // In case of Column grouping, when a column has a parent with dataField/labelFunction set, this column is // supposed to take value from what its parent supplies it if (headerInfo != null && headerInfo.internalLabelFunction != null) data = headerInfo.internalLabelFunction(data, this); if (!data) return "" ""; if (labelFunction != null) return labelFunction(data, this); if (owner.labelFunction != null) return owner.labelFunction(data, this); if (typeof(data) == ""object"" || typeof(data) == ""xml"") { if (dataField != null && dataField in data) data = data[dataField]; else return "" ""; // stops ""[object Object]"" showing } if (data is String) return String(data); try { return data.toString(); } catch(e:Error) { } return "" ""; } */ /** * Returns a String that the item renderer displays as the data tip for the given data object, * based on the dataTipField and dataTipFunction properties. * If the method cannot convert the parameter to a String, it returns a * single space. * *

    This method is for use by developers who are creating subclasses * of the AdvancedDataGridColumn class. * It is not for use by application developers.

    * * @param data Object to be rendered. * * @return Displayable String based on the data. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ /* public function itemToDataTip(data:Object):String { if (dataTipFunction != null) return dataTipFunction(data); if (owner.dataTipFunction != null) return owner.dataTipFunction(data); // for header items, return the header text if (data is AdvancedDataGridColumn) return AdvancedDataGridColumn(data).headerText; if (typeof(data) == ""object"" || typeof(data) == ""xml"") { var field:String = dataTipField; if (!field) field = owner.dataTipField; if (field != null) { if (field in data && data[field] != null) data = data[field]; } else if (dataField != null) { if (dataField in data && data[dataField] != null) data = data[dataField]; else data = null; } } if (data is String) return String(data); try { return data.toString(); } catch(e:Error) { } return "" ""; } */ /** * @private * * Save the current font context to member fields. */ /* private function saveFontContext(flexModuleFactory:IFlexModuleFactory):void { // Save for hasFontContextChanged() hasFontContextBeenSaved = true; var fontName:String = StringUtil.trimArrayElements(getStyle(""fontFamily""), "",""); var fontWeight:String = getStyle(""fontWeight""); var fontStyle:String = getStyle(""fontStyle""); var bold:Boolean = fontWeight == ""bold""; var italic:Boolean = fontStyle == ""italic""; oldEmbeddedFontContext = (noEmbeddedFonts || !embeddedFontRegistry) ? null : embeddedFontRegistry.getAssociatedModuleFactory( fontName, bold, italic, this, flexModuleFactory, owner.systemManager); } */ /** * @private * Test if the current font context has changed * since that last time saveFontContext() was called. */ /* mx_internal function hasFontContextChanged( flexModuleFactory:IFlexModuleFactory):Boolean { // If the font has not been saved yet, then return false, // the font context has not changed. if (!hasFontContextBeenSaved) return false; var fontName:String = StringUtil.trimArrayElements(getStyle(""fontFamily""), "",""); var fontWeight:String = getStyle(""fontWeight""); var fontStyle:String = getStyle(""fontStyle""); // Check if the module factory has changed. var bold:Boolean = fontWeight == ""bold""; var italic:Boolean = fontStyle == ""italic""; var fontContext:IFlexModuleFactory = (noEmbeddedFonts || !embeddedFontRegistry) ? null : embeddedFontRegistry.getAssociatedModuleFactory( fontName, bold, italic, this, flexModuleFactory, owner.systemManager); return fontContext != oldEmbeddedFontContext; } */ /** * @private */ /* private function addStylesToProtoChain(styles:String, chain:Object, target:DisplayObject):Object { var styleNames:Array = styles.split(/\\s+/); for (var c:int=0; c < styleNames.length; c++) { if (styleNames[c].length) { var declaration:CSSStyleDeclaration = owner.styleManager.getMergedStyleDeclaration(""."" + styleNames[c]); if (declaration) chain = declaration.addStyleToProtoChain(chain, target); } } return chain; } */ /** * @private * * Sets the properties of this Object to the given column. * * It sets only the required properties. * * @param col AdvancedDataGridColumn in which the properties are to be set. * */ /* protected function copyProperties(col:AdvancedDataGridColumn):void { // copy properties col.defaultFactory = this.defaultFactory; col.editable = this.editable; col.editorDataField = this.editorDataField; col.editorHeightOffset = this.editorHeightOffset; col.editorUsesEnterKey = this.editorUsesEnterKey; col.editorWidthOffset = this.editorWidthOffset; col.editorXOffset = this.editorXOffset; col.editorYOffset = this.editorYOffset; col.factory = this.factory; col.itemEditor = this.itemEditor; col.rendererIsEditor = this.rendererIsEditor; col.resizable = this.resizable; col.sortable = this.sortable; col.sortDescending = this.sortDescending; col.dataField = this.dataField; col.dataTipField = this.dataTipField; col.dataTipFunction = this.dataTipFunction; col.formatter = this.formatter; col.headerRenderer = this.headerRenderer; col.headerText = this.headerText; col.headerWordWrap = this.headerWordWrap; col.imeMode = this.imeMode; col.itemRenderer = this.itemRenderer; col.labelFunction = this.labelFunction; col.minWidth = this.minWidth; col.showDataTips = this.showDataTips; col.sortCompareFunction = this.sortCompareFunction; col.styleFunction = this.styleFunction; col.visible = this.visible; col.width = this.width; col.wordWrap = this.wordWrap; // copy styles col.public::setStyle(""backgroundColor"",this.getStyle(""backgroundColor"")); col.public::setStyle(""headerStyleName"",this.getStyle(""headerStyleName"")); col.public::setStyle(""paddingLeft"",this.getStyle(""paddingLeft"")); col.public::setStyle(""paddingRight"",this.getStyle(""paddingRight"")); // copy text styles col.public::setStyle(""color"",this.getStyle(""color"")); col.public::setStyle(""disabledColor"",this.getStyle(""disabledColor"")); col.public::setStyle(""fontAntiAliasType"",this.getStyle(""fontAntiAliasType"")); col.public::setStyle(""fontFamily"",this.getStyle(""fontFamily"")); col.public::setStyle(""fontGridFitType"",this.getStyle(""fontGridFitType"")); col.public::setStyle(""fontSharpness"",this.getStyle(""fontSharpness"")); col.public::setStyle(""fontSize"",this.getStyle(""fontSize"")); col.public::setStyle(""fontStyle"",this.getStyle(""fontStyle"")); col.public::setStyle(""fontThickness"",this.getStyle(""fontThickness"")); col.public::setStyle(""fontWeight"",this.getStyle(""fontWeight"")); col.public::setStyle(""kerning"",this.getStyle(""kerning"")); col.public::setStyle(""letterSpacing"",this.getStyle(""letterSpacing"")); col.public::setStyle(""textAlign"",this.getStyle(""textAlign"")); col.public::setStyle(""textDecoration"",this.getStyle(""textDecoration"")); col.public::setStyle(""textIndent"",this.getStyle(""textIndent"")); } */ /** * * Clone this column and return a new Column with the * same properties and styles as this one. * * It does not set all the available properties * * @return col AdvancedDataGridColumn. * * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Royale 0.9.3 */ public function clone():AdvancedDataGridColumn { // make a new column var col:AdvancedDataGridColumn = new AdvancedDataGridColumn(); // copy the properties //copyProperties(col); return col; } } } ",12447,True,2630.152034269679,median "= Collection Management Commands :toclevels: 1 // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // ""License""); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. A collection is a single logical index that uses a single Solr configuration file (`solrconfig.xml`) and a single index schema. [[create]] == CREATE: Create a Collection `/admin/collections?action=CREATE&name=_name_` === CREATE Parameters The CREATE action allows the following parameters: `name`:: The name of the collection to be created. This parameter is required. `router.name`:: The router name that will be used. The router defines how documents will be distributed among the shards. Possible values are `implicit` or `compositeId`, which is the default. + The `implicit` router does not automatically route documents to different shards. Whichever shard you indicate on the indexing request (or within each document) will be used as the destination for those documents. + The `compositeId` router hashes the value in the uniqueKey field and looks up that hash in the collection's clusterstate to determine which shard will receive the document, with the additional ability to manually direct the routing. + When using the `implicit` router, the `shards` parameter is required. When using the `compositeId` router, the `numShards` parameter is required. + For more information, see also the section <>. `numShards`:: The number of shards to be created as part of the collection. This is a required parameter when the `router.name` is `compositeId`. `shards`:: A comma separated list of shard names, e.g., `shard-x,shard-y,shard-z`. This is a required parameter when the `router.name` is `implicit`. `replicationFactor`:: The number of replicas to be created for each shard. The default is `1`. + This will create a NRT type of replica. If you want another type of replica, see the `tlogReplicas` and `pullReplica` parameters below. See the section <> for more information about replica types. `nrtReplicas`:: The number of NRT (Near-Real-Time) replicas to create for this collection. This type of replica maintains a transaction log and updates its index locally. If you want all of your replicas to be of this type, you can simply use `replicationFactor` instead. `tlogReplicas`:: The number of TLOG replicas to create for this collection. This type of replica maintains a transaction log but only updates its index via replication from a leader. See the section <> for more information about replica types. `pullReplicas`:: The number of PULL replicas to create for this collection. This type of replica does not maintain a transaction log and only updates its index via replication from a leader. This type is not eligible to become a leader and should not be the only type of replicas in the collection. See the section <> for more information about replica types. `maxShardsPerNode`:: When creating collections, the shards and/or replicas are spread across all available (i.e., live) nodes, and two replicas of the same shard will never be on the same node. + If a node is not live when the CREATE action is called, it will not get any parts of the new collection, which could lead to too many replicas being created on a single live node. Defining `maxShardsPerNode` sets a limit on the number of replicas the CREATE action will spread to each node. + If the entire collection can not be fit into the live nodes, no collection will be created at all. The default `maxShardsPerNode` value is `1`. A value of `-1` means unlimited. If a `policy` is also specified then the stricter of `maxShardsPerNode` and policy rules apply. `createNodeSet`:: Allows defining the nodes to spread the new collection across. The format is a comma-separated list of node_names, such as `localhost:8983_solr,localhost:8984_solr,localhost:8985_solr`. + If not provided, the CREATE operation will create shard-replicas spread across all live Solr nodes. + Alternatively, use the special value of `EMPTY` to initially create no shard-replica within the new collection and then later use the <> operation to add shard-replicas when and where required. `createNodeSet.shuffle`:: Controls whether or not the shard-replicas created for this collection will be assigned to the nodes specified by the `createNodeSet` in a sequential manner, or if the list of nodes should be shuffled prior to creating individual replicas. + A `false` value makes the results of a collection creation predictable and gives more exact control over the location of the individual shard-replicas, but `true` can be a better choice for ensuring replicas are distributed evenly across nodes. The default is `true`. + This parameter is ignored if `createNodeSet` is not also specified. `collection.configName`:: Defines the name of the configuration (which *must already be stored in ZooKeeper*) to use for this collection. + If not provided, Solr will use the configuration of `_default` configset to create a new (and mutable) configset named `.AUTOCREATED` and will use it for the new collection. When such a collection is deleted, its autocreated configset will be deleted by default when it is not in use by any other collection. `router.field`:: If this parameter is specified, the router will look at the value of the field in an input document to compute the hash and identify a shard instead of looking at the `uniqueKey` field. If the field specified is null in the document, the document will be rejected. + Please note that <> or retrieval by document ID would also require the parameter `\\_route_` (or `shard.keys`) to avoid a distributed search. `perReplicaState`:: If `true` the states of individual replicas will be maintained as individual child of the `state.json`. The default is `false`. `property._name_=_value_`:: Set core property _name_ to _value_. See the section <> for details on supported properties and values. `autoAddReplicas`:: When set to `true`, enables automatic addition of replicas when the number of active replicas falls below the value set for `replicationFactor`. This may occur if a replica goes down, for example. The default is `false`, which means new replicas will not be added. + While this parameter is provided as part of Solr's set of features to provide autoscaling of clusters, it is available even when you have not implemented any other part of autoscaling (such as a policy). See the section <> for more details about this option and how it can be used. [WARNING] ==== The entries in each core.properties file are vital for Solr to function correctly. Overriding entries can result in unusable collections. Altering these entries by specifying `property._name_=_value_` is an expert-level option and should only be used if you have a thorough understanding of the consequences. ==== `async`:: Request ID to track this action which will be <>. `rule`:: Replica placement rules. See the section <> for details. `snitch`:: Details of the snitch provider. See the section <> for details. `policy`:: Name of the collection-level policy. See <> for details. `waitForFinalState`:: If `true`, the request will complete only when all affected replicas become active. The default is `false`, which means that the API will return the status of the single action, which may be before the new replica is online and active. `withCollection`:: The name of the collection with which all replicas of this collection must be co-located. The collection must already exist and must have a single shard named `shard1`. See <> for more details. `alias`:: Starting with version 8.1 when a collection is created additionally an alias can be created that points to this collection. This parameter allows specifying the name of this alias, effectively combining this operation with <> Collections are first created in read-write mode but can be put in `readOnly` mode using the <> action. === CREATE Response The response will include the status of the request and the new core names. If the status is anything other than ""success"", an error message will explain why the request failed. === Examples using CREATE *Input* [source,text] ---- http://localhost:8983/solr/admin/collections?action=CREATE&name=newCollection&numShards=2&replicationFactor=1&wt=xml ---- *Output* [source,xml] ---- 0 3764 0 3450 newCollection_shard1_replica1 0 3597 newCollection_shard2_replica1 ---- [[reload]] == RELOAD: Reload a Collection `/admin/collections?action=RELOAD&name=_name_` The RELOAD action is used when you have changed a configuration in ZooKeeper. === RELOAD Parameters `name`:: The name of the collection to reload. This parameter is required. `async`:: Request ID to track this action which will be <>. === RELOAD Response The response will include the status of the request and the cores that were reloaded. If the status is anything other than ""success"", an error message will explain why the request failed. === Examples using RELOAD *Input* [source,text] ---- http://localhost:8983/solr/admin/collections?action=RELOAD&name=newCollection&wt=xml ---- *Output* [source,xml] ---- 0 1551 0 761 0 1527 ---- [[modifycollection]] == MODIFYCOLLECTION: Modify Attributes of a Collection `/admin/collections?action=MODIFYCOLLECTION&collection=__&____=____&____=____&____=` It's possible to edit multiple attributes at a time. Changing these values only updates the z-node on ZooKeeper, they do not change the topology of the collection. For instance, increasing `replicationFactor` will _not_ automatically add more replicas to the collection but _will_ allow more ADDREPLICA commands to succeed. An attribute can be deleted by passing an empty value. For example, `yet_another_attribute_name=` (with no value) will delete the `yet_another_attribute_name` parameter from the collection. === MODIFYCOLLECTION Parameters `collection`:: The name of the collection to be modified. This parameter is required. `_attribute_=_value_`:: Key-value pairs of attribute names and attribute values. At least one `_attribute_` parameter is required. The attributes that can be modified are: * maxShardsPerNode * replicationFactor * autoAddReplicas * collection.configName * rule * snitch * policy * withCollection * readOnly * async * other custom properties that use a `property.` prefix See the <> section above for details on these attributes. [[readonlymode]] ==== Read-Only Mode Setting the `readOnly` attribute to `true` puts the collection in read-only mode, in which any index update requests are rejected. Other collection-level actions (e.g., adding / removing / moving replicas) are still available in this mode. The transition from the (default) read-write to read-only mode consists of the following steps: * the `readOnly` flag is changed in collection state, * any new update requests are rejected with 403 FORBIDDEN error code (ongoing long-running requests are aborted, too), * a forced commit is performed to flush and commit any in-flight updates. NOTE: This may potentially take a long time if there are still major segment merges running in the background. * a collection <> is executed. Removing the `readOnly` property or setting it to false enables the processing of updates and reloads the collection. [[list]] == LIST: List Collections Fetch the names of the collections in the cluster. `/admin/collections?action=LIST` === Examples using LIST *Input* [source,text] ---- http://localhost:8983/solr/admin/collections?action=LIST ---- *Output* [source,json] ---- { ""responseHeader"":{ ""status"":0, ""QTime"":2011}, ""collections"":[""collection1"", ""example1"", ""example2""]} ---- [[rename]] == RENAME: Rename a Collection `/admin/collections?action=RENAME&name=_existingName_&target=_targetName_` Renaming a collection sets up a standard alias that points to the underlying collection, so that the same (unmodified) collection can now be referred to in query, index and admin operations using the new name. This command does NOT actually rename the underlying Solr collection - it sets up a new one-to-one alias using the new name, or renames the existing alias so that it uses the new name, while still referring to the same underlying Solr collection. However, from the user's point of view the collection can now be accessed using the new name, and the new name can be also referred to in other aliases. The following limitations apply: * the existing name must be either a SolrCloud collection or a standard alias referring to a single collection. Aliases that refer to more than 1 collection are not supported. * the existing name must not be a Routed Alias. * the target name must not be an existing alias. === RENAME Command Parameters `name`:: Name of the existing SolrCloud collection or an alias that refers to exactly one collection and is not a Routed Alias. `target`:: Target name of the collection. This will be the new alias that refers to the underlying SolrCloud collection. The original name (or alias) of the collection will be replaced also in the existing aliases so that they also refer to the new name. Target name must not be an existing alias. === Examples using RENAME Assuming there are two actual SolrCloud collections named `collection1` and `collection2`, and the following aliases already exist: * `col1 -> collection1`: this resolves to `collection1`. * `col2 -> collection2`: this resolves to `collection2`. * `simpleAlias -> col1`: this resolves to `collection1`. * `compoundAlias -> col1,col2`: this resolves to `collection1,collection2` The RENAME of `col1` to `foo` will change the aliases to the following: * `foo -> collection1`: this resolves to `collection1`. * `col2 -> collection2`: this resolves to `collection2`. * `simpleAlias -> foo`: this resolves to `collection1`. * `compoundAlias -> foo,col2`: this resolves to `collection1,collection2`. If we then rename `collection1` (which is an actual collection name) to `collection2` (which is also an actual collection name) the following aliases will exist now: * `foo -> collection2`: this resolves to `collection2`. * `col2 -> collection2`: this resolves to `collection2`. * `simpleAlias -> foo`: this resolves to `collection2`. * `compoundAlias -> foo,col2`: this would resolve now to `collection2,collection2` so it's reduced to simply `collection2`. * `collection1` -> `collection2`: this newly created alias effectively hides `collection1` from regular query and update commands, which are directed now to `collection2`. [[delete]] == DELETE: Delete a Collection `/admin/collections?action=DELETE&name=_collection_` === DELETE Parameters `name`:: The name of the collection to delete. This parameter is required. `async`:: Request ID to track this action which will be <>. === DELETE Response The response will include the status of the request and the cores that were deleted. If the status is anything other than ""success"", an error message will explain why the request failed. === Examples using DELETE *Input* Delete the collection named ""newCollection"". [source,text] ---- http://localhost:8983/solr/admin/collections?action=DELETE&name=newCollection&wt=xml ---- *Output* [source,xml] ---- 0 603 0 19 0 67 ---- [[collectionprop]] == COLLECTIONPROP: Collection Properties Add, edit or delete a collection property. `/admin/collections?action=COLLECTIONPROP&name=_collectionName_&propertyName=_propertyName_&propertyValue=_propertyValue_` === COLLECTIONPROP Parameters `name`:: The name of the collection for which the property would be set. `propertyName`:: The name of the property. `propertyValue`:: The value of the property. When not provided, the property is deleted. === COLLECTIONPROP Response The response will include the status of the request and the properties that were updated or removed. If the status is anything other than ""0"", an error message will explain why the request failed. === Examples using COLLECTIONPROP *Input* [source,text] ---- http://localhost:8983/solr/admin/collections?action=COLLECTIONPROP&name=coll&propertyName=foo&propertyValue=bar&wt=xml ---- *Output* [source,xml] ---- 0 0 ---- [[migrate]] == MIGRATE: Migrate Documents to Another Collection `/admin/collections?action=MIGRATE&collection=_name_&split.key=_key1!_&target.collection=_target_collection_&forward.timeout=60` The MIGRATE command is used to migrate all documents having a given routing key to another collection. The source collection will continue to have the same data as-is but it will start re-routing write requests to the target collection for the number of seconds specified by the `forward.timeout` parameter. It is the responsibility of the user to switch to the target collection for reads and writes after the MIGRATE action completes. The routing key specified by the `split.key` parameter may span multiple shards on both the source and the target collections. The migration is performed shard-by-shard in a single thread. One or more temporary collections may be created by this command during the ‘migrate’ process but they are cleaned up at the end automatically. This is a long running operation and therefore using the `async` parameter is highly recommended. If the `async` parameter is not specified then the operation is synchronous by default and keeping a large read timeout on the invocation is advised. Even with a large read timeout, the request may still timeout but that doesn’t necessarily mean that the operation has failed. Users should check logs, cluster state, source and target collections before invoking the operation again. This command works only with collections using the compositeId router. The target collection must not receive any writes during the time the MIGRATE command is running otherwise some writes may be lost. Please note that the MIGRATE API does not perform any de-duplication on the documents so if the target collection contains documents with the same uniqueKey as the documents being migrated then the target collection will end up with duplicate documents. === MIGRATE Parameters `collection`:: The name of the source collection from which documents will be split. This parameter is required. `target.collection`:: The name of the target collection to which documents will be migrated. This parameter is required. `split.key`:: The routing key prefix. For example, if the uniqueKey of a document is ""a!123"", then you would use `split.key=a!`. This parameter is required. `forward.timeout`:: The timeout, in seconds, until which write requests made to the source collection for the given `split.key` will be forwarded to the target shard. The default is 60 seconds. `property._name_=_value_`:: Set core property _name_ to _value_. See the section <> for details on supported properties and values. `async`:: Request ID to track this action which will be <>. === MIGRATE Response The response will include the status of the request. === Examples using MIGRATE *Input* [source,text] ---- http://localhost:8983/solr/admin/collections?action=MIGRATE&collection=test1&split.key=a!&target.collection=test2&wt=xml ---- *Output* [source,xml] ---- 0 19014 0 1 test2_shard1_0_replica1 BUFFERING 0 2479 split_shard1_0_temp_shard1_0_shard1_replica1 0 1002 0 21 0 1655 split_shard1_0_temp_shard1_0_shard1_replica2 0 4006 0 17 0 1 test2_shard1_0_replica1 EMPTY_BUFFER 0 31 0 31 0 1 test2_shard1_1_replica1 BUFFERING 0 1742 split_shard1_1_temp_shard1_1_shard1_replica1 0 1002 0 15 0 1917 split_shard1_1_temp_shard1_1_shard1_replica2 0 5007 0 8 0 1 test2_shard1_1_replica1 EMPTY_BUFFER 0 30 0 30 ---- [[reindexcollection]] == REINDEXCOLLECTION: Re-Index a Collection `/admin/collections?action=REINDEXCOLLECTION&name=_name_` The REINDEXCOLLECTION command reindexes a collection using existing data from the source collection. NOTE: Reindexing is potentially a lossy operation - some of the existing indexed data that is not available as stored fields may be lost, so users should use this command with caution, evaluating the potential impact by using different source and target collection names first, and preserving the source collection until the evaluation is complete. The target collection must not exist (and may not be an alias). If the target collection name is the same as the source collection then first a unique sequential name will be generated for the target collection, and then after reindexing is done an alias will be created that points from the source name to the actual sequentially-named target collection. When reindexing is started the source collection is put in <> to ensure that all source documents are properly processed. Using optional parameters a different index schema, collection shape (number of shards and replicas) or routing parameters can be requested for the target collection. Reindexing is executed as a streaming expression daemon, which runs on one of the source collection's replicas. It is usually a time-consuming operation so it's recommended to execute it as an asynchronous request in order to avoid request time outs. Only one reindexing operation may execute concurrently for a given source collection. Long-running, erroneous or crashed reindexing operations may be terminated by using the `abort` option, which also removes partial results. === REINDEXCOLLECTION Parameters `name`:: Source collection name, may be an alias. This parameter is required. `cmd`:: Optional command. Default command is `start`. Currently supported commands are: * `start` - default, starts processing if not already running, * `abort` - aborts an already running reindexing (or clears a left-over status after a crash), and deletes partial results, * `status` - returns detailed status of a running reindexing command. `target`:: Target collection name, optional. If not specified a unique name will be generated and after all documents have been copied an alias will be created that points from the source collection name to the unique sequentially-named collection, effectively ""hiding"" the original source collection from regular update and search operations. `q`:: Optional query to select documents for reindexing. Default value is `\\*:*`. `fl`:: Optional list of fields to reindex. Default value is `*`. `rows`:: Documents are transferred in batches. Depending on the average size of the document large batch sizes may cause memory issues. Default value is 100. `configName`:: `collection.configName`:: Optional name of the configset for the target collection. Default is the same as the source collection. There's a number of optional parameters that determine the target collection layout. If they are not specified in the request then their values are copied from the source collection. The following parameters are currently supported (described in details in the <> section): `numShards`, `replicationFactor`, `nrtReplicas`, `tlogReplicas`, `pullReplicas`, `maxShardsPerNode`, `autoAddReplicas`, `shards`, `policy`, `createNodeSet`, `createNodeSet.shuffle`, `router.*`. `removeSource`:: Optional boolean. If true then after the processing is successfully finished the source collection will be deleted. `async`:: Optional request ID to track this action which will be <>. When the reindexing process has completed the target collection is marked using `property.rx: ""finished""`, and the source collection state is updated to become read-write. On any errors the command will delete any temporary and target collections and also reset the state of the source collection's read-only flag. === Examples using REINDEXCOLLECTION *Input* [source,text] ---- http://localhost:8983/solr/admin/collections?action=REINDEXCOLLECTION&name=newCollection&numShards=3&configName=conf2&q=id:aa*&fl=id,string_s ---- This request specifies a different schema for the target collection, copies only some of the fields, selects only the documents matching a query, and also potentially re-shapes the collection by explicitly specifying 3 shards. Since the target collection hasn't been specified in the parameters, a collection with a unique name, e.g., `.rx_newCollection_2`, will be created and on success an alias pointing from `newCollection` to `.rx_newCollection_2` will be created, effectively replacing the source collection for the purpose of indexing and searching. The source collection is assumed to be small so a synchronous request was made. *Output* [source,json] ---- { ""responseHeader"":{ ""status"":0, ""QTime"":10757}, ""reindexStatus"":{ ""phase"":""done"", ""inputDocs"":13416, ""processedDocs"":376, ""actualSourceCollection"":"".rx_newCollection_1"", ""state"":""finished"", ""actualTargetCollection"":"".rx_newCollection_2"", ""checkpointCollection"":"".rx_ck_newCollection"" } } ---- As a result a new collection `.rx_newCollection_2` has been created, with selected documents reindexed to 3 shards, and with an alias pointing from `newCollection` to this one. The status also shows that the source collection was already an alias to `.rx_newCollection_1`, which was likely a result of a previous reindexing. [[colstatus]] == COLSTATUS: Detailed Status of a Collection's Indexes The COLSTATUS command provides a detailed description of the collection status, including low-level index information about segments and field data. This command also checks the compliance of Lucene index field types with the current Solr collection schema and indicates the names of non-compliant fields, i.e., Lucene fields with field types incompatible (or different) from the corresponding Solr field types declared in the current schema. Such incompatibilities may result from incompatible schema changes or after migration of data to a different major Solr release. `/admin/collections?action=COLSTATUS&collection=coll&coreInfo=true&segments=true&fieldInfo=true&sizeInfo=true` === COLSTATUS Parameters `collection`:: Collection name (optional). If missing then it means all collections. `coreInfo`:: Optional boolean. If true then additional information will be provided about SolrCore of shard leaders. `segments`:: Optional boolean. If true then segment information will be provided. `fieldInfo`:: Optional boolean. If true then detailed Lucene field information will be provided and their corresponding Solr schema types. `sizeInfo`:: Optional boolean. If true then additional information about the index files size and their RAM usage will be provided. ==== Index Size Analysis Tool The `COLSTATUS` command also provides a tool for analyzing and estimating the composition of raw index data. Please note that this tool should be used with care because it generates a significant IO load on all shard leaders of the analyzed collections. A sampling threshold and a sampling percent parameters can be adjusted to reduce this load to some degree. Size estimates produced by this tool are only approximate and represent the aggregated size of uncompressed index data. In reality these values would never occur, because Lucene (and Solr) always stores data in a compressed format - still, these values help to understand what occupies most of the space and the relative size of each type of data and each field in the index. In the following sections whenever ""size"" is mentioned it means an estimated aggregated size of uncompressed (raw) data. The following parameters are specific to this tool: `rawSize`:: Optional boolean. If true then run the raw index data analysis tool (other boolean options below imply this option if any of them are true). Command response will include sections that show estimated breakdown of data size per field and per data type. `rawSizeSummary`:: Optional boolean. If true then include also a more detailed breakdown of data size per field and per type. `rawSizeDetails`:: Optional boolean. If true then provide exhaustive details that include statistical distribution of items per field and per type as well as top 20 largest items per field. `rawSizeSamplingPercent`:: Optional float. When the index is larger than a certain threshold (100k documents per shard) only a part of data is actually retrieved and analyzed in order to reduce the IO load, and then the final results are extrapolated. Values must be greater than 0 and less or equal to 100.0. Default value is 5.0. Very small values (between 0.0 and 1.0) may introduce significant estimation errors. Also, values that would result in less than 10 documents being sampled are rejected with an exception. Response for this command always contains two sections: * `fieldsBySize` is a map where field names are keys and values are estimated sizes of raw (uncompressed) data that belongs to the field. The map is sorted by size so that it's easy to see what field occupies most space. * `typesBySize` is a map where data types are the keys and values are estimates sizes of raw (uncompressed) data of particular type. This map is also sorted by size. Optional sections include: * `summary` section containing a breakdown of data sizes for each field by data type. * `details` section containing detailed statistical summary of size distribution within each field, per data type. This section also shows `topN` values by size from each field. Data types shown in the response can be roughly divided into the following groups: * `storedFields` - represents the raw uncompressed data in stored fields. For example, for UTF-8 strings this represents the aggregated sum of the number of bytes in the strings' UTF-8 representation, for long numbers this is 8 bytes per value, etc. * `terms_terms` - represents the aggregated size of the term dictionary. The size of this data is affected by the the number and length of unique terms, which in turn depends on the field size and the analysis chain. * `terms_postings` - represents the aggregated size of all term position and offset information, if present. This information may be absent if position-based searching, such as phrase queries, is not needed. * `terms_payloads` - represents the aggregated size of all per-term payload data, if present. * `norms` - represents the aggregated size of field norm information. This information may be omitted if a field has an `omitNorms` flag in the schema, which is common for fields that don't need weighting or scoring by field length. * `termVectors` - represents the aggregated size of term vectors. * `docValues_*` - represents aggregated size of doc values, by type (e.g., `docValues_numeric`, `docValues_binary`, etc). * `points` - represents aggregated size of point values. === COLSTATUS Response The response will include an overview of the collection status, the number of active or inactive shards and replicas, and additional index information of shard leaders. === Examples using COLSTATUS *Input* [source,text] ---- http://localhost:8983/solr/admin/collections?action=COLSTATUS&collection=gettingstarted&fieldInfo=true&sizeInfo=true ---- *Output* [source,json] ---- { ""responseHeader"": { ""status"": 0, ""QTime"": 50 }, ""gettingstarted"": { ""stateFormat"": 2, ""znodeVersion"": 16, ""properties"": { ""autoAddReplicas"": ""false"", ""maxShardsPerNode"": ""-1"", ""nrtReplicas"": ""2"", ""pullReplicas"": ""0"", ""replicationFactor"": ""2"", ""router"": { ""name"": ""compositeId"" }, ""tlogReplicas"": ""0"" }, ""activeShards"": 2, ""inactiveShards"": 0, ""schemaNonCompliant"": [ ""(NONE)"" ], ""shards"": { ""shard1"": { ""state"": ""active"", ""range"": ""80000000-ffffffff"", ""replicas"": { ""total"": 2, ""active"": 2, ""down"": 0, ""recovering"": 0, ""recovery_failed"": 0 }, ""leader"": { ""coreNode"": ""core_node4"", ""core"": ""gettingstarted_shard1_replica_n1"", ""base_url"": ""http://192.168.0.80:8983/solr"", ""node_name"": ""192.168.0.80:8983_solr"", ""state"": ""active"", ""type"": ""NRT"", ""force_set_state"": ""false"", ""leader"": ""true"", ""segInfos"": { ""info"": { ""minSegmentLuceneVersion"": ""9.0.0"", ""commitLuceneVersion"": ""9.0.0"", ""numSegments"": 40, ""segmentsFileName"": ""segments_w"", ""totalMaxDoc"": 686953, ""userData"": { ""commitCommandVer"": ""1627350608019193856"", ""commitTimeMSec"": ""1551962478819"" } }, ""fieldInfoLegend"": [ ""I - Indexed"", ""D - DocValues"", ""xxx - DocValues type"", ""V - TermVector Stored"", ""O - Omit Norms"", ""F - Omit Term Frequencies & Positions"", ""P - Omit Positions"", ""H - Store Offsets with Positions"", ""p - field has payloads"", ""s - field uses soft deletes"", "":x:x:x - point data dim : index dim : num bytes"" ], ""segments"": { ""_i"": { ""name"": ""_i"", ""delCount"": 738, ""softDelCount"": 0, ""hasFieldUpdates"": false, ""sizeInBytes"": 109398213, ""size"": 70958, ""age"": ""2019-03-07T12:34:24.761Z"", ""source"": ""merge"", ""version"": ""9.0.0"", ""createdVersionMajor"": 9, ""minVersion"": ""9.0.0"", ""diagnostics"": { ""os"": ""Mac OS X"", ""java.vendor"": ""Oracle Corporation"", ""java.version"": ""1.8.0_191"", ""java.vm.version"": ""25.191-b12"", ""lucene.version"": ""9.0.0"", ""mergeMaxNumSegments"": ""-1"", ""os.arch"": ""x86_64"", ""java.runtime.version"": ""1.8.0_191-b12"", ""source"": ""merge"", ""mergeFactor"": ""10"", ""os.version"": ""10.14.3"", ""timestamp"": ""1551962064761"" }, ""attributes"": { ""Lucene50StoredFieldsFormat.mode"": ""BEST_SPEED"" }, ""largestFiles"": { ""_i.fdt"": ""42.5 MB"", ""_i_Lucene80_0.dvd"": ""35.3 MB"", ""_i_Lucene50_0.pos"": ""11.1 MB"", ""_i_Lucene50_0.doc"": ""10 MB"", ""_i_Lucene50_0.tim"": ""4.3 MB"" }, ""ramBytesUsed"": { ""total"": 49153, ""postings [PerFieldPostings(segment=_i formats=1)]"": { ""total"": 31023, ""fields"": { ""dc"": { ""flags"": ""I-----------"", ""schemaType"": ""text_general"" }, ""dc_str"": { ""flags"": ""-Dsrs-------"", ""schemaType"": ""strings"" }, ""dc.title"": { ""flags"": ""I-----------"", ""docCount"": 70958, ""sumDocFreq"": 646756, ""sumTotalTermFreq"": 671817, ""schemaType"": ""text_general"" }, ""dc.date"": { ""flags"": ""-Dsrn-------:1:1:8"", ""schemaType"": ""pdates"" } }}}}}}}}}}} ---- Example of using the raw index data analysis tool: *Input* [source,text] ---- http://localhost:8983/solr/admin/collections?action=COLSTATUS&collection=gettingstarted&rawSize=true&rawSizeSamplingPercent=0.1 ---- *Output* [source,json] ---- { ""responseHeader"": { ""status"": 0, ""QTime"": 26812 }, ""gettingstarted"": { ""stateFormat"": 2, ""znodeVersion"": 33, ""properties"": { ""autoAddReplicas"": ""false"", ""maxShardsPerNode"": ""-1"", ""nrtReplicas"": ""2"", ""pullReplicas"": ""0"", ""replicationFactor"": ""2"", ""router"": { ""name"": ""compositeId"" }, ""tlogReplicas"": ""0"" }, ""activeShards"": 2, ""inactiveShards"": 0, ""schemaNonCompliant"": [ ""(NONE)"" ], ""shards"": { ""shard1"": { ""state"": ""active"", ""range"": ""80000000-ffffffff"", ""replicas"": { ""total"": 2, ""active"": 2, ""down"": 0, ""recovering"": 0, ""recovery_failed"": 0 }, ""leader"": { ""coreNode"": ""core_node5"", ""core"": ""gettingstarted_shard1_replica_n2"", ""base_url"": ""http://192.168.0.80:8983/solr"", ""node_name"": ""192.168.0.80:8983_solr"", ""state"": ""active"", ""type"": ""NRT"", ""force_set_state"": ""false"", ""leader"": ""true"", ""segInfos"": { ""info"": { ""minSegmentLuceneVersion"": ""9.0.0"", ""commitLuceneVersion"": ""9.0.0"", ""numSegments"": 46, ""segmentsFileName"": ""segments_4h"", ""totalMaxDoc"": 3283741, ""userData"": { ""commitCommandVer"": ""1635676266902323200"", ""commitTimeMSec"": ""1559902446318"" } }, ""rawSize"": { ""fieldsBySize"": { ""revision.text"": ""7.9 GB"", ""revision.text_str"": ""734.7 MB"", ""revision.comment_str"": ""259.1 MB"", ""revision"": ""239.2 MB"", ""revision.sha1"": ""211.9 MB"", ""revision.comment"": ""201.3 MB"", ""title"": ""114.9 MB"", ""revision.contributor"": ""103.5 MB"", ""revision.sha1_str"": ""96.4 MB"", ""revision.id"": ""75.2 MB"", ""ns"": ""75.2 MB"", ""revision.timestamp"": ""75.2 MB"", ""revision.contributor.id"": ""74.7 MB"", ""revision.format"": ""69 MB"", ""id"": ""65 MB"", ""title_str"": ""26.8 MB"", ""revision.model_str"": ""25.4 MB"", ""_version_"": ""24.9 MB"", ""_root_"": ""24.7 MB"", ""revision.contributor.ip_str"": ""22 MB"", ""revision.contributor_str"": ""21.8 MB"", ""revision_str"": ""15.5 MB"", ""revision.contributor.ip"": ""13.5 MB"", ""restrictions_str"": ""428.7 KB"", ""restrictions"": ""164.2 KB"", ""name_str"": ""84 KB"", ""includes_str"": ""8.8 KB"" }, ""typesBySize"": { ""storedFields"": ""7.8 GB"", ""docValues_sortedSet"": ""1.2 GB"", ""terms_postings"": ""788.8 MB"", ""terms_terms"": ""342.2 MB"", ""norms"": ""237 MB"", ""docValues_sortedNumeric"": ""124.3 MB"", ""points"": ""115.7 MB"", ""docValues_numeric"": ""24.9 MB"", ""docValues_sorted"": ""18.5 MB"" } } } } }, ""shard2"": { ""state"": ""active"", ""range"": ""0-7fffffff"", ""replicas"": { ""total"": 2, ""active"": 2, ""down"": 0, ""recovering"": 0, ""recovery_failed"": 0 }, ""leader"": { ""coreNode"": ""core_node8"", ""core"": ""gettingstarted_shard2_replica_n6"", ""base_url"": ""http://192.168.0.80:8983/solr"", ""node_name"": ""192.168.0.80:8983_solr"", ""state"": ""active"", ""type"": ""NRT"", ""force_set_state"": ""false"", ""leader"": ""true"", ""segInfos"": { ""info"": { ""minSegmentLuceneVersion"": ""9.0.0"", ""commitLuceneVersion"": ""9.0.0"", ""numSegments"": 55, ""segmentsFileName"": ""segments_4d"", ""totalMaxDoc"": 3284863, ""userData"": { ""commitCommandVer"": ""1635676259742646272"", ""commitTimeMSec"": ""1559902445005"" } }, ""rawSize"": { ""fieldsBySize"": { ""revision.text"": ""8.3 GB"", ""revision.text_str"": ""687.5 MB"", ""revision"": ""238.9 MB"", ""revision.sha1"": ""212 MB"", ""revision.comment_str"": ""211.5 MB"", ""revision.comment"": ""201.7 MB"", ""title"": ""115.9 MB"", ""revision.contributor"": ""103.4 MB"", ""revision.sha1_str"": ""96.3 MB"", ""ns"": ""75.2 MB"", ""revision.id"": ""75.2 MB"", ""revision.timestamp"": ""75.2 MB"", ""revision.contributor.id"": ""74.6 MB"", ""revision.format"": ""69 MB"", ""id"": ""67 MB"", ""title_str"": ""29.5 MB"", ""_version_"": ""24.8 MB"", ""revision.model_str"": ""24 MB"", ""revision.contributor_str"": ""21.7 MB"", ""revision.contributor.ip_str"": ""20.9 MB"", ""revision_str"": ""15.5 MB"", ""revision.contributor.ip"": ""13.8 MB"", ""restrictions_str"": ""411.1 KB"", ""restrictions"": ""132.9 KB"", ""name_str"": ""42 KB"", ""includes_str"": ""41 KB"" }, ""typesBySize"": { ""storedFields"": ""8.2 GB"", ""docValues_sortedSet"": ""1.1 GB"", ""terms_postings"": ""787.4 MB"", ""terms_terms"": ""337.5 MB"", ""norms"": ""236.6 MB"", ""docValues_sortedNumeric"": ""124.1 MB"", ""points"": ""115.7 MB"", ""docValues_numeric"": ""24.9 MB"", ""docValues_sorted"": ""20.5 MB"" } } } } } } } } ---- [[backup]] == BACKUP: Backup Collection Backs up Solr collections and associated configurations to a shared filesystem - for example a Network File System. `/admin/collections?action=BACKUP&name=myBackupName&collection=myCollectionName&location=/path/to/my/shared/drive` The BACKUP command will backup Solr indexes and configurations for a specified collection. The BACKUP command <>. For configurations, it backs up the configset that was associated with the collection and metadata. Backup data is stored in the repository based on the provided `name` and `location`. Each backup location can hold multiple backups for the same collection, allowing users to later restore from any of these ""backup points"" as desired. Within a location backups are done incrementally, so that index files uploaded previously are skipped and not duplicated in the backup repository. [NOTE] ==== Previous versions of Solr supported a different snapshot-based backup method without the incremental support described above. Solr can still restore from backups that use this old format, but creating new backups of this format is not recommended and snapshot-based backups are officially deprecated. See the `incremental` parameter below for more information. ==== === BACKUP Parameters `collection`:: The name of the collection to be backed up. This parameter is required. `name`:: What to name the backup that is created. This is checked to make sure it doesn't already exist, and otherwise an error message is raised. This parameter is required. `location`:: The location on a shared drive for the backup command to write to. This parameter is required, unless a default location is defined on the repository configuration, or set as a <>. + If the location path is on a mounted drive, the mount must be available on the node that serves as the overseer, even if the overseer node does not host a replica of the collection being backed up. Since any node can take the overseer role at any time, a best practice to avoid possible backup failures is to ensure the mount point is available on all nodes of the cluster. + Each backup location can only hold a backup for one collection, however the same location can be used for repeated backups of the same collection. Repeated backups of the same collection are done incrementally, so that files unchanged since the last backup are not duplicated in the backup repository. `async`:: Request ID to track this action which will be <>. `repository`:: The name of a repository to be used for the backup. If no repository is specified then the local filesystem repository will be used automatically. `maxNumBackupPoints`:: The upper-bound on how many backups should be retained at the backup location. If the current number exceeds this bound, older backups will be deleted until only `maxNumBackupPoints` backups remain. This parameter has no effect if `incremental=false` is specified. `incremental`:: A boolean parameter allowing users to choose whether to create an incremental (`incremental=true`) or a ""snapshot"" (`incremental=false`) backup. If unspecified, backups are done incrementally by default. Incremental backups are preferred in all known circumstances and snapshot backups are deprecated, so this parameter should only be used after much consideration. [[listbackup]] == LISTBACKUP: List Backups Lists information about each backup stored at the specified repository location. Basic metadata is returned about each backup including: the timestamp the backup was created, the Lucene version used to create the index, and the size of the backup both in number of files and total filesize. [NOTE] ==== Previous versions of Solr supported a different snapshot-based backup file structure that did not support the storage of multiple backups at the same location. Solr can still restore backups stored in this old format, but it is deprecated and will be removed in subsequent versions of Solr. The LISTBACKUP API does not support the deprecated format and attempts to use this API on a location holding an older backup will result in an error message. ==== The file structure used by Solr internally to represent backups changed in 8.9.0. While backups created prior to this format change can still be restored, the `LISTBACKUP` and `DELETEBACKUP` API commands are only valid on this newer format. Attempting to use them on a location holding an older backup will result in an error message. === LISTBACKUP Parameters `name`:: The name of the backups to list. The backup name usually corresponds to the collection-name, but isn't required to. This parameter is required. `location`:: The repository location to list backups from. This parameter is required, unless a default location is defined on the repository configuration, or set as a <>. + If the location path is on a mounted drive, the mount must be available on the node that serves as the overseer, even if the overseer node does not host a replica of the collection being backed up. Since any node can take the overseer role at any time, a best practice to avoid possible backup failures is to ensure the mount point is available on all nodes of the cluster. `repository`:: The name of a repository to be used for accessing backup information. If no repository is specified then the local filesystem repository will be used automatically. `async`:: Request ID to track this action which will be <>. === LISTBACKUP Example *Input* [.dynamic-tabs] -- [example.tab-pane#v1listbackup] ==== [.tab-label]*V1 API* [source,bash] ---- http://localhost:8983/solr/admin/collections?action=LISTBACKUP&name=myBackupName&location=/path/to/my/shared/drive ---- ==== [example.tab-pane#v2listbackup] ==== [.tab-label]*V2 API* [source,bash] ---- POST http://localhost:8983/v2/collections/backups { ""list-backups"" : { ""name"": ""myBackupName"", ""location"": ""/path/to/my/shared/drive"" } } ---- ==== -- *Output* [source,json] ---- { ""responseHeader"":{ ""status"":0, ""QTime"":4}, ""collection"":""books"", ""backups"":[{ ""indexFileCount"":0, ""indexSizeMB"":0.0, ""shardBackupIds"":{ ""shard2"":""md_shard2_0.json"", ""shard1"":""md_shard1_0.json""}, ""collection.configName"":""books"", ""backupId"":0, ""collectionAlias"":""books"", ""startTime"":""2021-02-09T03:19:52.085653Z"", ""indexVersion"":""9.0.0""}, { ""indexFileCount"":0, ""indexSizeMB"":0.0, ""shardBackupIds"":{ ""shard2"":""md_shard2_1.json"", ""shard1"":""md_shard1_1.json""}, ""collection.configName"":""books"", ""backupId"":1, ""collectionAlias"":""books"", ""startTime"":""2021-02-09T03:19:52.268804Z"", ""indexVersion"":""9.0.0""}]} ---- [[restore]] == RESTORE: Restore Collection Restores Solr indexes and associated configurations to a specified collection. `/admin/collections?action=RESTORE&name=myBackupName&location=/path/to/my/shared/drive&collection=myRestoredCollectionName` The RESTORE operation will replace the content of a collection with files from the specified backup. If the provided `collection` value matches an existing collection, Solr will use it for restoration, assuming it is compatible (same number of shards, etc.) with the stored backup files. If the provided `collection` value doesn't exist, a new collection with that name is created in a way compatible with the stored backup files. The collection created will be have the same number of shards and replicas as the original collection, preserving routing information, etc. Optionally, you can override some parameters documented below. While restoring, if a configset with the same name exists in ZooKeeper then Solr will reuse that, or else it will upload the backed up configset in ZooKeeper and use that. You can use the collection <> command to make sure clients don't need to change the endpoint to query or index against the newly restored collection. === RESTORE Parameters `collection`:: The collection where the indexes will be restored into. This parameter is required. `name`:: The name of the existing backup that you want to restore. This parameter is required. `location`:: The location on a shared drive for the RESTORE command to read from. Alternately it can be set as a <>. `async`:: Request ID to track this action which will be <>. `repository`:: The name of a repository to be used for the backup. If no repository is specified then the local filesystem repository will be used automatically. `backupId`:: The ID of a specific backup point to restore from. + Backup locations can hold multiple backups of the same collection. This parameter allows users to choose which of those backups should be used to restore from. If not specified the most recent backup point is used. There are also optional parameters that determine the target collection layout. The following parameters are currently supported (described in detail in the <> section): `createNodeSet`, `createNodeSet.shuffle`. Note: for `createNodeSet` the special value of `EMPTY` is not allowed with this command. *Overridable Parameters* Additionally, there are several parameters that may have been set on the original collection that can be overridden when restoring the backup (described in detail in the <> section): `collection.configName`, `replicationFactor`, `nrtReplicas`, `tlogReplicas`, `pullReplicas`, `property._name_=_value_`. [[deletebackup]] == DELETEBACKUP: Delete backup files from the remote repository Deletes backup files stored at the specified repository location. [NOTE] ==== Previous versions of Solr supported a different snapshot-based backup file structure that did not support the storage of multiple backups at the same location. Solr can still restore backups stored in this old format, but it is deprecated and will be removed in subsequent versions of Solr. The DELETEBACKUP API does not support the deprecated format and attempts to use this API on a location holding an older backup will result in an error message. ==== Solr allows storing multiple backups for the same collection at any given logical ""location"". These backup points are each given an identifier (`backupId`) which can be used to delete them specifically with this API. Alternatively Solr can be told to keep the last `maxNumBackupPoints` backups, deleting everything else at the given location. Deleting backup points in these ways can orphan index files that are no longer referenced by any backup points. These orphaned files can be detected and deleted using the `purgeUnused` option. See the parameter descriptions below for more information. === DELETEBACKUP Example *Input* The following API command deletes the first backup (`backupId=0`) at the specified repository location. [.dynamic-tabs] -- [example.tab-pane#v1deletebackup] ==== [.tab-label]*V1 API* [source,bash] ---- http://localhost:8983/solr/admin/collections?action=DELETEBACKUP&name=myBackupName&location=/path/to/my/shared/drive&backupId=0 ---- ==== [example.tab-pane#v2deletebackup] ==== [.tab-label]*V2 API* [source,bash] ---- POST http://localhost:8983/v2/collections/backups { ""delete-backups"" : { ""name"": ""myBackupName"", ""location"": ""/path/to/my/shared/drive"", ""backupId"": 0 } } ---- ==== -- *Output* [source,json] ---- { ""responseHeader"":{ ""status"":0, ""QTime"":940}, ""deleted"":[[ ""startTime"",""2021-02-09T03:19:52.085653Z"", ""backupId"",0, ""size"",28381, ""numFiles"",53]], ""collection"":""books""} ---- === DELETEBACKUP Parameters `name`:: The backup name to delete backup files from. This parameter is required. `location`:: The repository location to delete backups from. This parameter is required, unless a default location is defined on the repository configuration, or set as a <>. + If the location path is on a mounted drive, the mount must be available on the node that serves as the overseer, even if the overseer node does not host a replica of the collection being backed up. Since any node can take the overseer role at any time, a best practice to avoid possible backup failures is to ensure the mount point is available on all nodes of the cluster. `repository`:: The name of a repository to be used for deleting backup files. If no repository is specified then the local filesystem repository will be used automatically. `backupId`:: Explicitly specify a single backup-ID to delete. Only one of `backupId`, `maxNumBackupPoints`, and `purgeUnused` may be specified per DELETEBACKUP request. `maxNumBackupPoints`:: Specify how many backups should be retained, deleting all others. Only one of `backupId`, `maxNumBackupPoints`, and `purgeUnused` may be specified per DELETEBACKUP request. `purgeUnused`:: Solr's incremental backup support can orphan files if the backups referencing them are deleted. The `purgeUnused` flag parameter triggers a scan to detect these orphaned files and delete them. Administrators doing repeated backups at the same location should plan on using this parameter sporadically to reclaim disk space. Only one of `backupId`, `maxNumBackupPoints`, and `purgeUnused` may be specified per DELETEBACKUP request. `async`:: Request ID to track this action which will be <>. [[rebalanceleaders]] == REBALANCELEADERS: Rebalance Leaders Reassigns leaders in a collection according to the preferredLeader property across active nodes. `/admin/collections?action=REBALANCELEADERS&collection=collectionName` Leaders are assigned in a collection according to the `preferredLeader` property on active nodes. This command should be run after the preferredLeader property has been assigned via the BALANCESHARDUNIQUE or ADDREPLICAPROP commands. NOTE: It is not _required_ that all shards in a collection have a `preferredLeader` property. Rebalancing will only attempt to reassign leadership to those replicas that have the `preferredLeader` property set to `true` _and_ are not currently the shard leader _and_ are currently active. === REBALANCELEADERS Parameters `collection`:: The name of the collection to rebalance `preferredLeaders` on. This parameter is required. `maxAtOnce`:: The maximum number of reassignments to have queue up at once. Values \\<=0 are use the default value Integer.MAX_VALUE. + When this number is reached, the process waits for one or more leaders to be successfully assigned before adding more to the queue. `maxWaitSeconds`:: Defaults to `60`. This is the timeout value when waiting for leaders to be reassigned. If `maxAtOnce` is less than the number of reassignments that will take place, this is the maximum interval that any _single_ wait for at least one reassignment. + For example, if 10 reassignments are to take place and `maxAtOnce` is `1` and `maxWaitSeconds` is `60`, the upper bound on the time that the command may wait is 10 minutes. === REBALANCELEADERS Response The response will include the status of the request. A status of ""0"" indicates the request was _processed_, not that all assignments were successful. Examine the ""Summary"" section for that information. === Examples using REBALANCELEADERS *Input* Either of these commands would cause all the active replicas that had the `preferredLeader` property set and were _not_ already the preferred leader to become leaders. [source,text] ---- http://localhost:8983/solr/admin/collections?action=REBALANCELEADERS&collection=collection1&wt=json http://localhost:8983/solr/admin/collections?action=REBALANCELEADERS&collection=collection1&maxAtOnce=5&maxWaitSeconds=30&wt=json ---- *Output* In this example: * In the ""alreadyLeaders"" section, core_node5 was already the leader, so there were no changes in leadership for shard1. * In the ""inactivePreferreds"" section, core_node57 had the preferredLeader property set, but the node was not active, the leader for shard7 was not changed. This is considered successful. * In the ""successes"" section, core_node23 was _not_ the leader for shard3, so leadership was assigned to that replica. The ""Summary"" section with the ""Success"" tag indicates that the command rebalanced all _active_ replicas with the preferredLeader property set as requried. If a replica cannot be made leader due to not being healthy (for example, it is on a Solr instance that is not running), it's also considered success. [source,json] ---- { ""responseHeader"":{ ""status"":0, ""QTime"":3054}, ""Summary"":{ ""Success"":""All active replicas with the preferredLeader property set are leaders""}, ""alreadyLeaders"":{ ""core_node5"":{ ""status"":""skipped"", ""msg"":""Replica core_node5 is already the leader for shard shard1. No change necessary""}}, ""inactivePreferreds"":{ ""core_node57"":{ ""status"":""skipped"", ""msg"":""Replica core_node57 is a referredLeader for shard shard7, but is inactive. No change necessary""}}, ""successes"":{ ""shard3"":{ ""status"":""success"", ""msg"":""Successfully changed leader of slice shard3 to core_node23""}}} ---- Examining the clusterstate after issuing this call should show that every active replica that has the `preferredLeader` property should also have the ""leader"" property set to _true_. NOTE: The added work done by an NRT leader is quite small and only present when indexing. The primary use-case is to redistribute the leader role if there are a large number of leaders concentrated on a small number of nodes. Rebalancing will likely not improve performance unless the imbalance of leadership roles is measured in multiples of 10. NOTE: The BALANCESHARDUNIQUE command that distributes the preferredLeader property does not guarantee perfect distribution and in some collection topologies it is impossible to make that guarantee. ",16280,True,2710.087693129386,median